AOP切面技术,大家应该都听知道,Spring框架的主要功能之一。
AOP切面的用途很广,其中一个常见的用途就是打印接口方法的运行日志和运行时间。
日志对于一个项目很是重要,不仅有助于调错,还是后期大数据分析的重要数据来源,这里我就简单介绍一下如何在SpringBoot中利用AOP切面打印后端接口的运行情况。
2、切面代码
实现方式很简单,在SpringBoot工程中,增加切面类,代码如下:
import cn.zhuifengren.util.JsonUtils; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Aspect @Component @Order(Integer.MIN_VALUE) public class MyAspect { public static final Logger log = LoggerFactory.getLogger(MyAspect.class); @Around("execution(* cn.zhuifengren.controller..*Controller.*(..))") public Object recordTimeLog(ProceedingJoinPoint joinPoint) throws Throwable { // 记录开始时间 long begin = System.currentTimeMillis(); log.info("类信息:{}", joinPoint.getTarget().getClass()); log.info("方法名:{}", joinPoint.getSignature().getName()); // 获得request对象 RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); ServletRequestAttributes sra = (ServletRequestAttributes) requestAttributes; HttpServletRequest req = sra.getRequest(); log.info("请求地址: {}",req.getRequestURI()); log.info("请求设备: {}", req.getHeader("user-agent")); // 获得参数 Object[] args = joinPoint.getArgs(); if (args!=null && args.length>0){ for (int i = 0; i < args.length; i++) { if (args[i] instanceof HttpServletRequest || args[i] instanceof HttpServletResponse) continue; log.info("参数:" + ( args[i]==null? "": JsonUtils.objectToJson(args[i]))); } } // 执行目标 service Object result = joinPoint.proceed(); log.info("响应:" + JsonUtils.objectToJson(result)); // 记录结束时间 long end = System.currentTimeMillis(); long time = end - begin; log.info("执行时间:{} 毫秒", time); return result; } }