spring boot使用aop记录每一次的请求
在最近写一个课程项目的时候,有一个需求,要求是记录每一次请求的方法名,ip,请求参数等信息,我想到了利用AOP来获取请求日志。
-
首先创建一个maven工程,导入相关依赖
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
-
实现日志打印的代码
@Aspect //把当前类标识为一个切面供容器读取 @Component //注入到ICO容器中 public class LogAspect { private final Logger logger = LoggerFactory.getLogger(this.getClass()); //切入点,用于匹配方法执行的切入点。切入点是com.heiye.web包下的所有请求 @Pointcut("execution(* com.heiye.web.*.*(..))") //Point签名 public void log() {} @Before("log()") //前置增强 public void doBefore(JoinPoint joinPoint) { //获取request请求 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); //通过请求获取url,ip String url = request.getRequestURL().toString(); String ip = request.getRemoteAddr(); //获取方法所在的包名和类名 String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName(); //获取请求的参数 Object[] args = joinPoint.getArgs(); RequestLog requestLog = new RequestLog(url, ip, classMethod, args); logger.info("Request : {}", requestLog); } @After("log()") //标识为一个后置增强方法,不管程序会不会抛出异常都会执行。 public void doAfter() { } //后置增强,在方法正常退出的时候执行 @AfterReturning(returning = "result",pointcut = "log()") public void doAfterRuturn(Object result) { logger.info("Result : {}", result); } //请求记录参数实体类 private class RequestLog { private String url; //请求的url private String ip; //请求ip private String classMethod; //请求方法 private Object[] args; //请求参数 public RequestLog(String url, String ip, String classMethod, Object[] args) { this.url = url; this.ip = ip; this.classMethod = classMethod; this.args = args; } @Override public String toString() { return "{" + "url='" + url + '\'' + ", ip='" + ip + '\'' + ", classMethod='" + classMethod + '\'' + ", args=" + Arrays.toString(args) + '}'; } } }