添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
配置开启aop
# AOP spring.aop.auto=true # 使用cglib spring.aop.proxy-target-class=false
入口类添加
@EnableAspectJAutoProxy
不开启会导致切面类不执行
切面类实现
/** * 李成阳 * 2018/3/23 * 日志切面类 */ @Aspect @Component public class AspectLogs { private Logger logger = Logger.getLogger(getClass()); ThreadLocal<Long> startTime = new ThreadLocal(); @Pointcut("execution(public * com.rzt.controller.*.*(..))") public void webLog(){} @Before("webLog()") public void doBefore(JoinPoint joinPoint) throws Throwable { startTime.set(System.currentTimeMillis()); // 接收到请求,记录请求内容 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); // 记录下请求内容 logger.info("URL : " + request.getRequestURL().toString()); logger.info("HTTP_METHOD : " + request.getMethod()); logger.info("IP : " + request.getRemoteAddr()); logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()); logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs())); } @AfterReturning(returning = "ret", pointcut = "webLog()") public void doAfterReturning(Object ret) throws Throwable { //处理完返回内容 logger.info("RESPONSE : " + ret); logger.info("SPEND TIME : " + (System.currentTimeMillis() - startTime.get())); } }
@RequestMapping("/test") public String test(){ return "test!!"; }
访问 http://127.0.0.1:2222/test 查看日志
2018-03-23 10:24:35.417 INFO 4692 --- [nio-2222-exec-1] com.rzt.aop.AspectLogs : URL : http://127.0.0.1:2222/test
2018-03-23 10:24:35.417 INFO 4692 --- [nio-2222-exec-1] com.rzt.aop.AspectLogs : HTTP_METHOD : GET
2018-03-23 10:24:35.421 INFO 4692 --- [nio-2222-exec-1] com.rzt.aop.AspectLogs : IP : 127.0.0.1
2018-03-23 10:24:35.421 INFO 4692 --- [nio-2222-exec-1] com.rzt.aop.AspectLogs : CLASS_METHOD : com.rzt.controller.ComputeController.test
2018-03-23 10:24:35.421 INFO 4692 --- [nio-2222-exec-1] com.rzt.aop.AspectLogs : ARGS : []
2018-03-23 10:24:35.428 INFO 4692 --- [nio-2222-exec-1] com.rzt.aop.AspectLogs : RESPONSE : test!!
2018-03-23 10:24:35.428 INFO 4692 --- [nio-2222-exec-1] com.rzt.aop.AspectLogs : SPEND TIME : 6312