SpringBoot 通过aop获取@RequestBody以及RequestQueryString 参数记录到日志

一  目的。

通过使用Spring的aop中point.getArgs()方法可以获取body参数,这种对源代码的侵入性比较小,优先选择。

二 最终的日志展示效果

请求接口时间:2022-01-06 17:08:44,信息为:
【request_id】:b541f6ce42d249e781233b5fbb911efd
【请求 URL】:http://localhost:802/busquery/testloghandle
【请求 IP】:0:0:0:0:0:0:0:1
【请求类名】:com.siisoo.ontimebusquery.controller.QueryController【请求方法名】:testLogHandle
【body】:[{"age":"20","phone":"1234567"}]
【请求参数】:{"is_up_down":["1"],"line_no":["9"]} 

三  切面类源码

 1 package com.siisoo.ontimebusquery.handle;
 2 
 3 import cn.hutool.core.util.IdUtil;
 4 import com.alibaba.fastjson.JSON;
 5 import com.siisoo.ontimebusquery.util.DateUtil;
 6 import org.aspectj.lang.ProceedingJoinPoint;
 7 import org.aspectj.lang.annotation.Around;
 8 import org.aspectj.lang.annotation.Aspect;
 9 import org.aspectj.lang.annotation.Pointcut;
10 import org.slf4j.Logger;
11 import org.slf4j.LoggerFactory;
12 import org.springframework.stereotype.Component;
13 import org.springframework.web.bind.annotation.ControllerAdvice;
14 import org.springframework.web.bind.annotation.ResponseBody;
15 import org.springframework.web.bind.annotation.RestControllerAdvice;
16 import org.springframework.web.context.request.RequestAttributes;
17 import org.springframework.web.context.request.RequestContextHolder;
18 import org.springframework.web.context.request.ServletRequestAttributes;
19 
20 import javax.servlet.http.HttpServletRequest;
21 import java.util.Map;
22 
23 /**
24 
25  * REST接口统一的日志处理
26  */
27 @Aspect
28 @Component
29 public class LogHandle {
30     private final Logger logger = LoggerFactory.getLogger(this.getClass());
31     @Pointcut("execution(* com.siisoo.ontimebusquery.controller..*.*(..))")
32     public void restLog(){}
33     @Around("restLog()")
34     public void doAround(ProceedingJoinPoint joinPoint) throws Throwable {
35         // 生成本次请求时间戳
36         String timestamp = System.currentTimeMillis()+"";
37         RequestAttributes ra = RequestContextHolder.getRequestAttributes();
38         ServletRequestAttributes sra = (ServletRequestAttributes) ra;
39         HttpServletRequest request = sra.getRequest();
40         String url = request.getRequestURL().toString();
41         String method = request.getMethod();
42         String uri = request.getRequestURI();
43         String queryString = request.getQueryString();
44         Map<String, String[]> parameterMap = request.getParameterMap();
45         StringBuffer sb = new StringBuffer();
46         String requestId = IdUtil.simpleUUID();
47         sb.append("\n【request_id】:").append(requestId);
48         sb.append("\n【请求 URL】:").append(request.getRequestURL());
49         sb.append("\n【请求 IP】:").append(getIp(request));
50         sb.append("\n【请求类名】:").append(joinPoint.getSignature().getDeclaringTypeName());
51         sb.append("【请求方法名】:").append(joinPoint.getSignature().getName());
52         sb.append("\n【body】:").append(JSON.toJSONString(joinPoint.getArgs()));
53         sb.append("\n【请求参数】:").append(JSON.toJSONString(parameterMap));
54 
55         String requestLog=sb.toString();
56 
57         logger.info(" \n 请求接口时间:"+ DateUtil.getCurrentDateTime() + ",信息为:{} ", requestLog);
58         // result的值就是被拦截方法的返回值
59         Object result = joinPoint.proceed();
60         logger.info(timestamp + " , " + result.toString());
61     }
62 
63     private String getIp(HttpServletRequest request) {
64         String ip = request.getHeader("x-forwarded-for");
65         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
66             ip = request.getHeader("Proxy-Client-IP");
67         }
68         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
69             ip = request.getHeader("WL-Proxy-Client-IP");
70         }
71         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
72             ip = request.getRemoteAddr();
73         }
74         return ip;
75     }
76 
77 }

四  pom.xml中的maven依赖

 <dependency>
    <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>

<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.18</version>
</dependency>

<dependency>
<groupId>eu.bitwalker</groupId>
<artifactId>UserAgentUtils</artifactId>
<version>1.21</version>
</dependency>

五 请求测试

 可以看到,分别记录下了requestparameter以及requestbody的所传进来的所有参数信息,方便后续业务中进行BUG定位。

半斤八两开始写BLOG了
原文地址:https://www.cnblogs.com/freewsf/p/15772003.html