Spring Boot记录操作日志

刚刚开通了一个公众号,会分享一些技术博客和自己觉得比较好的项目,同时会更新一些自己使用的工具和图书资料,后面会整理一些面试资料进行分享,觉得有兴趣的可以关注一下。
在这里插入图片描述


背景

最近的工作需求需要记录一下操作日志,什么人什么时间做的什么事情。在此分享一下。项目的认证使用的是OAUTH2认证,会从认证服务器请求回来一个JWT TOKEN,项目验证Token并且判断是否有权限,以此为基础。


实现

方案

为防止代码入侵业务,肯定是需要使用AOP来进行操作的。设置下切面和切点就可以了,最主要的是需要在切面的方法里找到当前的请求路径,还要获取请求的用户信息,请求的具体方法就可以用AOPJoinPoint来获取就可以了。

实际上Spring Boot已经提供了两个工具类来实现这两个需求。RequestContextHolder来获取具体的请求信息ServletRequestAttributes,SecurityContextHolder可以获取当前的用户验证信息。


代码

  • 切点使用注解
public @interface RecordLog {
}

  • 切面
@Aspect
@Component
public class RecordLogAspect {

    @Resource
    private RecordLogMapper recordLogMapper;
    @Pointcut("@annotation(RecordLog)")
    public void pointcut(){}

    @AfterReturning("pointcut()")
    public void doAfter(JoinPoint joinPoint) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String url = request.getRequestURL().toString();
        String methodName = joinPoint.getSignature().getDeclaringTypeName()+"-->"
                +joinPoint.getSignature().getName();

        RecordLogEntity recordLogEntity = new RecordLogEntity();
        recordLogEntity.setUrl(url);
        recordLogEntity.setMethod(methodName);
        recordLogEntity.setUserName(SecurityContextHolder.getContext().getAuthentication().getName());
        recordLogEntity.setOpTime(LocalDateTime.now(ZoneId.of("Asia/Shanghai")));
        recordLogMapper.insertRecordLog(recordLogEntity);
    }
}

SecurityContextHolder.getContext().getAuthentication()来获取了验证信息,.getName()获取用户名。

这样就可以使用注解RecordLog,哪个需要被记录,就放在哪个请求上即可,项目主要记录写操作,对于读操作没必要记录。


打完收工!

  • 7
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦幻D开始

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值