利用RestControllerAdvice统一打印日志

编程入门 行业动态 更新时间:2024-10-10 08:19:38

利用RestControllerAdvice统一打印<a href=https://www.elefans.com/category/jswz/34/1770796.html style=日志"/>

利用RestControllerAdvice统一打印日志

需求描述

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

实现方法

  1. 自定义aop实现,统一一个地方打印日志
  2. 利用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统一打印日志

本文发布于:2024-02-07 09:22:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1755386.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:日志   RestControllerAdvice

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!