在SpringBoot中,可以使用aop来记录控制层的所有请求,将其记录到日志中,如果哪个请求发生异常,便于我们查阅。实际,体现了一种切面的思想。
首先需要导入aop的包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
然后创建一个记录请求的类。
package com.qfcwx.springbootlogback.aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
/**
* @ClassName: HttpAspect
* @Author: 清风一阵吹我心
* @Description: TODO 使用aop记录每一个请求
* @Date: 2019/3/24 21:55
* @Version 1.0
**/
@Aspect
@Component
public class HttpAspect {
private static final Logger LOGGER = LoggerFactory.getLogger(HttpAspect.class);
@Pointcut("execution(public * com.qfcwx.springbootlogback.controller.*.*(..))")
public void log() {
}
@Before("log()")
public void doBefore(JoinPoint joinPoint) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
//url
LOGGER.info("url:{}", request.getRequestURL());
//method
LOGGER.info("method:{}", request.getMethod());
//ip
LOGGER.info("ip:{}", request.getRemoteAddr());
//类方法
LOGGER.info("class_method:{}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
//参数(joinPoint.getArgs()返回一个参数数组)
LOGGER.info("args:{}", Arrays.asList(joinPoint.getArgs()));
}
@AfterReturning(returning = "object", pointcut = "log()")
public void doAfterReturning(Object object) {
LOGGER.info("response:{}", object.toString());
}
}
注意:这里joinPoint.getArgs()返回的是一个参数的数组,所以需要对其进行遍历。这里使用了java8的新特性。
@Pointcut:声明切入点表达式。
@Before:前置通知,在方法执行前执行。
@AfterReturning:返回通知,在方法返回结果之后执行。
基本上aop处理日志的功能就完成了,是不是很简单呢?接下来到了测试的环节。
创建一个控制器,写一个简单的方法。
@RestController
public class AspectController {
@GetMapping("/aop")
public Map<String, String> getMapInfo(@RequestParam("name") String name, @RequestParam("password") String password) {
Map<String, String> map = new HashMap<>();
map.put("name", name);
map.put("password", password);
return map;
}
}
启动项目,访问地址:http://localhost:8080/aop,然后看控制台输出的日志。
可以清楚的看到。显示了aop类中记录的相关内容,证明记录请求日志的切面完成了。
当你凝视深渊的时候,深渊也在凝视你!