Spring Boot 接口全局日志打印

本文档介绍了如何在Spring MVC控制器中实现全局的日志处理,记录了请求地址、方式、参数和操作者,使用ResponseBodyAdvice和RequestBodyAdvice进行前后端交互的参数管理和日志输出。
摘要由CSDN通过智能技术生成
@Slf4j
@ControllerAdvice
public class GlobalInterfaceLogHandler implements ResponseBodyAdvice<Object>, RequestBodyAdvice {

    private String bodyParams = "无";

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        StringBuffer sb = new StringBuffer();
        sb.append("\n请求访问地址:{}");
        sb.append("\n请求方式:{}");
        sb.append("\n请求body参数:{}");
        sb.append("\n操作人:{}");
        sb.append("\n返回结果:{}");

        String username = "获取服务当前用户信息";
        

        log.info(sb.toString(),
                request.getURI(),
                request.getMethodValue(),
                getBodyParams(),
                username,
                JacksonUtil.obj2Str(body));
        return body;
    }

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        return inputMessage;
    }

    @SneakyThrows
    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        setBodyParams(body);
        return body;
    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }

    private void setBodyParams(Object body) throws IOException {
        this.bodyParams = "body转json字符串";
    }

    private String getBodyParams() {
        String bodyParams = "无";
        if(!bodyParams.equals(this.bodyParams)){
            bodyParams = this.bodyParams;
            this.bodyParams = "无";
        }
        return bodyParams;
    }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值