利用RestControllerAdvice统一打印日志

需求描述

在springboot微服务中,会提供各种服务接口,在服务调用时,一般都会打印请求参数、以及返回值信息,方便查看日志调试问题,那么多接口就需一个统一的日志打印的功能。

实现方法

  1. 自定义aop实现,统一一个地方打印日志
  2. 利用spring提供的RestControllerAdvice增强controller切面处理,本人实现方法
    代码如下:
/**
 1. Title: RequestAopLogComponent
 2. Description: 统一参数打印
 3.  
 4. @author gejx
 5. @version V1.0
 6. @date 2019-05-25
 */
@Slf4j
@RestControllerAdvice
public class RequestAopLogComponent implements RequestBodyAdvice {

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

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

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
                                Type targetType, Class> converterType) {
        RequestMapping requestMapping = parameter.getMethodAnnotation(RequestMapping.class);
        log.debug("请求地址====>{}", StringUtils.arrayToDelimitedString(requestMapping.value(), ","));
        log.debug("请求参数====>{}", JSON.toJSONString(body));
        return body;
    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
                                  Type targetType, Class> converterType) {
        RequestMapping requestMapping = parameter.getMethodAnnotation(RequestMapping.class);
        log.debug("请求地址====>{}", StringUtils.arrayToDelimitedString(requestMapping.value(), ","));
        return body;
    }
}

说明:

统一请求参数打印切面只对@RestController且参数类型为@RequestBody接口有效

/**
 * Title: RequestAopLogComponent
 * Description: 统一返回值日志打印
 *
 * @author gejx
 * @version V1.0
 * @date 2019-05-25
 */
@Slf4j
@RestControllerAdvice
public class ResponseAopLogComponent implements ResponseBodyAdvice {

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

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        if (body instanceof ApiResult) {
            log.debug("请求返回====>{}", JSON.toJSONString(body));
        }
        return body;
    }
}

说明
统一返回值日志打印由于项目接入prometheus监控,所以监控的请求的返回值也会打印,所以增加一个统一返回实体类型的判断。

你可能感兴趣的:(工作总结)