Spring Boot 接口全局日志打印

@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;
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值