spring boot aop日志管理(MongoDB)
程序员文章站
2022-04-25 20:05:59
...
aop拦截的是controller层请求,正常的请求用@Before来拦截,
异常的请求用@AfterThrowing来拦截
1、引用aop jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>2.0.3.RELEASE</version>
</dependency>
2、代码实现
@Aspect
@Component
@Slf4j
public class LogAop {
@Autowired
private MongoTemplate mongoTemplate;
@Pointcut("execution(public * com.caody.muyi.controller.*.*(..))")
public void logAop(){};
@Before("logAop()")
public void around(JoinPoint joinPoint){
log.info("user:cdy");
log.info("time:"+new Date());
log.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature
().getName());
log.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
OperationLog operationLog = new OperationLog();
operationLog.setLogname("cdy");
operationLog.setLogtype("业务日志");
operationLog.setCreatetime(new Date());
operationLog.setUserid(1);
operationLog.setClassname(joinPoint.getSignature().getDeclaringTypeName());
operationLog.setMethod(joinPoint.getSignature().getName());
operationLog.setSucceed("成功");
operationLog.setMessage("");
mongoTemplate.save(operationLog);
}
// @AfterReturning(returning = "object", pointcut = "logAop()")
// public void after(Object object){
// System.out.println(object);
// log.info("RESPONSE : " + object);
// }
@AfterThrowing(pointcut = "logAop()", throwing="e")
public void afterThrowing(JoinPoint joinPoint, Throwable e){
log.info("user:cdy");
log.info("time:"+new Date());
log.info("path : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature
().getName());
log.info("param : " + Arrays.toString(joinPoint.getArgs()));
log.info("异常代码:" + e.getClass().getName());
log.info("异常信息:" + e.getMessage());
OperationLog operationLog = new OperationLog();
operationLog.setLogname("cdy");
operationLog.setLogtype("异常日志");
operationLog.setCreatetime(new Date());
operationLog.setUserid(1);
operationLog.setClassname(joinPoint.getSignature().getDeclaringTypeName());
operationLog.setMethod(joinPoint.getSignature().getName());
operationLog.setSucceed("失败");
operationLog.setMessage(e.getMessage());
mongoTemplate.save(operationLog);
}
}
推荐阅读
-
Spring Boot使用AOP防止重复提交的方法示例
-
详解Spring Boot配置使用Logback进行日志记录的实战
-
spring boot aop 记录方法执行时间代码示例
-
Spring Boot 入门(五):集成 AOP 进行日志管理
-
spring-boot-2.0.3不一样系列之番外篇 - 自定义session管理,绝对有值得你看的地方
-
Spring Boot 日志配置方法(超详细)
-
Spring boot配置MongoDB以及Morphia踩坑记录
-
SpringBoot 源码解析 (十)----- Spring Boot 精髓:集成AOP
-
Spring AOP 切面编程记录日志和接口执行时间
-
Spring Boot 会员管理系统之处理文件上传功能