本文共 3158 字,大约阅读时间需要 10 分钟。
工作中,使用利用spring aop 切面的方式记录日志
org.springframework.boot spring-boot-starter-aop
@Target({ ElementType.PARAMETER, ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface AuditLog { String title() default ""; String desc() default "";}
@Aspect@Componentpublic 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); } }}
AopTestController
@RestController@RequestMapping(value = "/aoptest")public class AopTestController { @AuditLog(title = "标题",desc = "牛逼的方法") @RequestMapping(value = "",method = RequestMethod.GET) public void aopTestMethod(){ System.out.println("哈哈哈"); }}
结果如下:
本篇只是写个简单的demo示例,大家可以根据该工程结合自身公司业务场景进行扩展
转载地址:http://ekrii.baihongyu.com/