SpringBoot通过aop获取@RequestBody参数记录到⽇志⽬录
⼀、前⾔
通过InputStream();的⽅式获取body参数实现起来⽐较复杂,因为输⼊流只能被使⽤⼀次。通过使⽤Spring的aop中Args()⽅法可以获取body参数,这种对源代码的侵⼊性⽐较⼩,优先选择。
参考:
⼆、效果展⽰
2020-07-23 14:19:59.124 |-INFO [http-nio-8080-exec-1] com.fig.AopLog [56] -|
【request_id】:6181ae98c4404481a522eeb8d2508f17
【请求 URL】:localhost:8080/test3
【请求 IP】:0:0:0:0:0:0:0:1
【请求类名】:com.ller.DemoController【请求⽅法名】:test3
【body】:[{"name":"lisi","id":1}]
【请求参数】:{}
2020-07-23 14:19:59.140 |-INFO [http-nio-8080-exec-1] com.fig.AopLog [84] -|
【request_id】:6181ae98c4404481a522eeb8d2508f17
【返回值】:获取body传参的参数测试 - {"id":1,"name":"lisi"}
2020-07-23 14:19:59.154 |-INFO [http-nio-8080-exec-1] com.fig.AopLog [108] -|
【request_id】:6181ae98c4404481a522eeb8d2508f17
【请求耗时】:17毫秒
【浏览器类型】:UNKNOWN
【操作系统】:UNKNOWN
【原始User-Agent】:PostmanRuntime/7.26.1
三、切⾯类源码
package com.fig;
import util.IdUtil;
import cn.hutool.json.JSONUtil;
import eu.bitwalker.useragentutils.UserAgent;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.t.request.RequestContextHolder;
import org.t.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Objects;
@Aspect
@Component
public class AopLog {
private static final Logger log = Logger(AopLog.class);
private static final String START_TIME = "request-start";
private static final String REQUEST_ID = "request_id";
private static final String REQUEST_ID = "request_id";
/**
* 切⼊点
*/
@Pointcut("execution(public * oller.*Controller.*(..))")
public void log() {
}
/**
* 前置操作
*
* @param point 切⼊点
*/
@Before("log()")
public void beforeLog(JoinPoint point) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestAttributes();
HttpServletRequest request = quireNonNull(attributes).getRequest();
Map<String, String[]> parameterMap = ParameterMap();
StringBuffer sb = new StringBuffer();
String requestId = IdUtil.simpleUUID();
sb.append("\n【request_id】:").append(requestId);
sb.append("\n【请求 URL】:").RequestURL());
sb.append("\n【请求 IP】:").append(getIp(request));
sb.append("\n【请求类名】:").Signature().getDeclaringTypeName());
sb.append("【请求⽅法名】:").Signature().getName());
sb.append("\n【body】:").Args()));
sb.append("\n【请求参数】:").JsonStr(parameterMap));
log.String());
// log.info("【请求 URL】:{}", RequestURL());
// log.info("【请求 IP】:{}", RemoteAddr());
// log.info("【请求类名】:{},【请求⽅法名】:{}", Signature().getDeclaringTypeName(), Signature().getName()); // log.info("【body】:{},", Args()));
// log.info("【请求参数】:{},", JsonStr(parameterMap));
Long start = System.currentTimeMillis();
request.setAttribute(START_TIME, start);
request.setAttribute(REQUEST_ID, requestId);
}
/**
* 环绕操作
*
* @param point 切⼊点
* @return 原⽅法返回值
* @throws Throwable 异常信息
*/
@Around("log()")
public Object aroundLog(ProceedingJoinPoint point) throws Throwable {
Object result = point.proceed();
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestAttributes();
HttpServletRequest request = quireNonNull(attributes).getRequest();
String requestId = (String) Attribute(REQUEST_ID);
StringBuffer sb = new StringBuffer();
sb.append("\n【request_id】:").append(requestId);
sb.append("\n【返回值】:").JsonStr(result));
log.String());
// log.info("\n【request_id】:" + requestId + "\n【返回值】:{}", JsonStr(result));
return result;
}
/**
* 后置操作
*/
@AfterReturning("log()")
@AfterReturning("log()")
public void afterReturning() {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestAttributes();
HttpServletRequest request = quireNonNull(attributes).getRequest();
String requestId = (String) Attribute(REQUEST_ID);
StringBuffer sb = new StringBuffer();
sb.append("\n【request_id】:").append(requestId);
Long start = (Long) Attribute(START_TIME);
Long end = System.currentTimeMillis();
sb.append("\n【请求耗时】:").append((end - start)).append("毫秒");
String header = Header("User-Agent");
UserAgent userAgent = UserAgent.parseUserAgentString(header);
sb.append("\n【浏览器类型】:").Browser().toString());
sb.append("\n【操作系统】:").OperatingSystem());
sb.append("\n【原始User-Agent】:").append(header);
log.String());
// log.info("【请求耗时】:{}毫秒", end - start);
/
/ log.info("【浏览器类型】:{},【操作系统】:{},【原始User-Agent】:{}", Browser().toString(), OperatingSystem().toString(), }
private String getIp(HttpServletRequest request) {
String ip = Header("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = Header("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = Header("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = RemoteAddr();
}
return ip;
}
}
四、maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>springboot aop
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.2.5</version>
</dependency>
<dependency>
<groupId>eu.bitwalker</groupId>
<artifactId>UserAgentUtils</artifactId>
<version>1.21</version>
</dependency>
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论