SpringbootAop 记录请求日志
SpringbootAop 记录请求日志
导包
<!--aop-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
添加配置类
/**
* @description: 请求日志切面
* @program: toolkit
* @author: Mikael
* @date: 2021-06-22 13:55
**/
@Aspect
@Component
@Slf4j
public class HttpAspect {
//所有的controller之前
@Pointcut("execution(* com.immortal.toolkit.*.controller..*.*(..))")
public void logPointCut(){
}
@Before("logPointCut()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 记录下请求内容
log.info("请求地址 : " + request.getRequestURL().toString());
log.info("HTTP METHOD : " + request.getMethod());
// 获取真实的ip地址
log.info("IP : " + request.getRemoteAddr());
log.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "."
+ joinPoint.getSignature().getName());
log.info("参数 : " + Arrays.toString(joinPoint.getArgs()));
}
@AfterReturning(returning = "ret", pointcut = "logPointCut()")// returning的值和doAfterReturning的参数名一致
public void doAfterReturning(Object ret) throws Throwable {
// 处理完请求,返回内容(返回值太复杂时,打印的是物理存储空间的地址)
log.debug("返回值 : " + ret);
}
@Around("logPointCut()")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
long startTime = System.currentTimeMillis();
Object ob = pjp.proceed();// ob 为方法的返回值
log.info("耗时 : " + (System.currentTimeMillis() - startTime));
return ob;
}
}
效果


浙公网安备 33010602011771号