利用切面打印日志
在配置 AOP 切面之前,我们需要了解下 aspectj
相关注解的作用:
- @Aspect:声明该类为一个注解类;
- @Pointcut:定义一个切点,后面跟随一个表达式,表达式可以定义为某个 package 下的方法,也可以是自定义注解等;
- 切点定义好后,就是围绕这个切点做文章了:
- @Before: 在切点之前,织入相关代码;
- @After: 在切点之后,织入相关代码;
- @AfterReturning: 在切点返回内容后,织入相关代码,一般用于对返回值做些加工处理的场景;
- @AfterThrowing: 用来处理当织入的代码抛出异常后的逻辑处理;
- @Around: 在切入点前后织入代码,并且可以自由的控制何时执行切点;
package com.tools.toolmange.common.aop;
import cn.hutool.json.JSONUtil;
import com.tools.toolmange.common.contextholder.SecurityContextHolder;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
/*
* @功能描述:
* @作者:lr
* @时间:2020-04-20
* @备注:
*/
@Aspect
@Configuration
@Log4j2
public class LogConsole {
// 定义切点Pointcut
@Pointcut("execution(* com.tools.toolmange.handler.*.*(..))")
public void executeService() {
}
/**
* 在切点之前织入
*/
@Before("executeService()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
// 开始打印请求日志
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
if (request == null)
return;
String username = "";
try{
username = SecurityContextHolder.getUserDetails().getUsername();
}catch (Exception e){
log.info("打印请求参数,用户登陆过期 无法获取请求参数");
}
// 打印请求相关参数
log.info("========================================== Start ==========================================");
//请求人
log.info("UserCode :"+ username );
// 打印请求 url
log.info("URL : {}", request.getRequestURL().toString());
// 打印 Http method
log.info("HTTP Method : {}", request.getMethod());
// 打印调用 controller 的全路径以及执行方法
log.info("Class Method : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
// 打印请求的 IP
log.info("IP : {}", request.getRemoteAddr());
// 打印请求入参
log.info("Request Args : {}", JSONUtil.toJsonStr(joinPoint.getArgs()));
}
/**
* 在切点之后织入
*/
@After("executeService()")
public void doAfter() throws Throwable {
log.info("=========================================== End ===========================================");
// 每个请求之间空一行
log.info("");
}
/**
* 环绕
*/
@Around("executeService()")
public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
long startTime = System.currentTimeMillis();
Object result = proceedingJoinPoint.proceed();
// 执行耗时
log.info("Time-Consuming : {} ms", System.currentTimeMillis() - startTime);
return result;
}
}