日志"/>
利用RestControllerAdvice统一打印日志
需求描述
在springboot微服务中,会提供各种服务接口,在服务调用时,一般都会打印请求参数、以及返回值信息,方便查看日志调试问题,那么多接口就需一个统一的日志打印的功能。
实现方法
- 自定义aop实现,统一一个地方打印日志
- 利用spring提供的RestControllerAdvice增强controller切面处理,本人实现方法
代码如下:
/**1. Title: RequestAopLogComponent2. Description: 统一参数打印3. 4. @author gejx5. @version V1.06. @date 2019-05-25*/
@Slf4j
@RestControllerAdvice
public class RequestAopLogComponent implements RequestBodyAdvice {@Overridepublic boolean supports(MethodParameter methodParameter, Type targetType,Class<? extends HttpMessageConverter<?>> converterType) {return true;}@Overridepublic HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,Class<? extends HttpMessageConverter<?>> converterType) throws IOException {return inputMessage;}@Overridepublic Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter,Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {RequestMapping requestMapping = parameter.getMethodAnnotation(RequestMapping.class);log.debug("请求地址====>{}", StringUtils.arrayToDelimitedString(requestMapping.value(), ","));log.debug("请求参数====>{}", JSON.toJSONString(body));return body;}@Overridepublic Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter,Type targetType, Class<? extends HttpMessageConverter<?>> 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 {@Overridepublic boolean supports(MethodParameter returnType, Class converterType) {return true;}@Overridepublic 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监控,所以监控的请求的返回值也会打印,所以增加一个统一返回实体类型的判断。
更多推荐
利用RestControllerAdvice统一打印日志
发布评论