Spring Boot AOP 实现日志持久化

项目需要做日志管理,并持久化到数据库中

首先创建LogInterceptor,并在类的上方加上注解

 1 @Aspect
 2 @Component
 3 public class LogInterceptor {
 4   
    
    //注入repository 5 @Autowired 6 private LogRepositories logRepositories; 7    8 @After(value = "execution(* com.bosch.WPCR.application.service.impl.*.*(..)))") //定义JointPoint为impl路径下的所有类的所有方法 9 public void addLog(JoinPoint joinPoint) { 10 TB_Log log = new TB_Log(); 11 12 MethodSignature signature = (MethodSignature) joinPoint.getSignature(); 13 String className = joinPoint.getTarget().getClass().getName(); //获取当前类名 14 Method method = signature.getMethod(); 15 String methodName = method.getName(); //获取当前方法名 16 17 if(!methodName.equals("loadUserByUsername")) { 当调用这个方法时,线程里还没有当前用户 18 String userName = getCurrentUser().getUsername(); 19 log.setUserName(userName); 20 } 21 22 Object[] args = joinPoint.getArgs(); 23 String params = JSONObject.toJSON(args).toString(); 24 log.setOperationType(className + " || " + methodName); 25 log.setParams(params); 26 log.setDate(new Date()); 27 logRepositories.save(log); 28 } 29 30 public UserContext getCurrentUser() { 31 UserContext userContext =(UserContext) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); 32 //org.springframework.security.core.userdetails.User user = (org.springframework.security.core.userdetails.User)userDetails; 33 return userContext; 34 } 35 36 }

需要额外注意的是,最开始时,我直接在addLog方法里调用了userService的getCurrentUser()方法,同时这个方法也是定义的JointPoint之一,导致陷入了死循环之中

最后,附上数据库记录

 

转载于:https://www.cnblogs.com/JINJAY/p/11153840.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值