前言
仔代码检视时,讨论到在controller层手动添加日志太麻烦,于是想要注解和切面实现日志的自动输出,简化代码、简练程序
利用Aspect实现日志切面
1、添加aop依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2、定义注解作为切点
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface log {
String value() default "";
}
3、声明切面,完成日志记录
@Aspect // 使用@Aspect注解声明一个切面
@Component
@Slf4j
public class LogAspect {
private static final String START = "start";
private static final String END = "end";
@Pointcut("@annotation(com.zh.live.aspect.log)")
public void logPointCut() {}
@Before("logPointCut()") //前置通知
public void before(JoinPoint point) throws Throwable {
try {
printLog(point,START);
} catch (Exception e) {
}
}
@After("logPointCut()") //后置通知
public void after(JoinPoint point) throws Throwable {
try {
printLog(point,END);
} catch (Exception e) {
}
}
private void printLog(JoinPoint joinPoint, String type) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String beginTime = dateFormat.format(new Date());
//请求的 类名、方法名
String className = joinPoint.getTarget().getClass().getName();
String methodName = signature.getName();
//请求的参数
Object[] args = joinPoint.getArgs();
//打印日志
log.info("{} {} {} | time: {} param: {} " , className,methodName,type,beginTime,args);
}
}
4、在controller中需要添加日志的方法上添加@log注解
@log
@PostMapping("/registerUser")
public R registerUser(@RequestBody UserTo user)
5、postman发送请求进行测试
至此,日志切面就完全结束了,我这里写的比较简单,大家也可以任意扩展