前言
工作中,使用利用spring aop 切面的方式记录日志
一、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
二、项目结构
三、注解类
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AuditLog {
String title() default "";
String desc() default "";
}
四、切面类
@Aspect
@Component
public class AuditLogAspect {
private static final Logger log = LoggerFactory.getLogger("audit_log");
public AuditLogAspect() {
}
@Pointcut("@annotation(com.cch.auditlog.common.auditlog.AuditLog)")
public void logPointCut() {
}
@AfterReturning(
pointcut = "logPointCut()"
)
public void doAfterReturning(JoinPoint joinPoint) {
this.handleAfterLog(joinPoint);
}
@Before(value = "logPointCut()")
public void doBefore(JoinPoint joinPoint) {
this.handleBeforeLog(joinPoint);
}
@AfterThrowing(
value = "logPointCut()",
throwing = "e"
)
public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
this.handleAfterThrowingLog(joinPoint, e);
}
private AuditLog getAnnotationLog(JoinPoint joinPoint) throws Exception {
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
return method != null ? (AuditLog) method.getAnnotation(AuditLog.class) : null;
}
private void handleBeforeLog(JoinPoint joinPoint) {
try {
AuditLog controllerLog = this.getAnnotationLog(joinPoint);
if (controllerLog == null) {
return;
}
log.info("before ----> title:{}, desc:{}", controllerLog.title(), controllerLog.desc());
} catch (Exception var10) {
log.error("operlog exception:{}", var10);
}
}
protected void handleAfterLog(JoinPoint joinPoint) {
try {
AuditLog controllerLog = this.getAnnotationLog(joinPoint);
if (controllerLog == null) {
return;
}
log.info("after ----> title:{}, desc:{}", controllerLog.title(), controllerLog.desc());
return;
} catch (Exception var10) {
log.error("operlog exception:{}", var10);
return;
}
}
protected void handleAfterThrowingLog(JoinPoint joinPoint, Exception e) {
try {
AuditLog controllerLog = this.getAnnotationLog(joinPoint);
if (controllerLog == null) {
return;
}
log.info("发生异常:{}", e.getMessage());
} catch (Exception var10) {
log.error("operlog exception:{}", var10);
}
}
}
五、启动springboot 测试
AopTestController
@RestController
@RequestMapping(value = "/aoptest")
public class AopTestController {
@AuditLog(title = "标题",desc = "牛逼的方法")
@RequestMapping(value = "",method = RequestMethod.GET)
public void aopTestMethod(){
System.out.println("哈哈哈");
}
}
结果如下:
总结
本篇只是写个简单的demo示例,大家可以根据该工程结合自身公司业务场景进行扩展