操作日志记录方法实现

一、首先定义一个Log注解,需要标明 操作的 title、业务类型、功能、操作人类别、是否保留请求参数
@Target({ ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log{
/**
* 模块
*/
public String title() default "";

/**
 * 功能
 */
public BusinessType businessType() default BusinessType.OTHER;

/**
 * 操作人类别
 */
public OperatorType operatorType() default OperatorType.MANAGE;

/**
 * 是否保存请求的参数
 */
public boolean isSaveRequestData() default true;

}

二、定义LogAspect切面增强类,拦截所有使用@Log注解的方法
@Component
public class LogAspect {
// 切面
@Pointcut("@annotation(com.ruoyi.common.annotation.Log)")
public void logPointCut() { }

// 切点,方法结束后
@AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
public void doAfterReturning(JoinPoint joinPoint, Object jsonResult){
    一、获取 方法中的Log注解
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        Log controllerLog = method.getAnnotation(Log.class);
        没有注解的方法不记录日志
        if (controllerLog == null){
            return;
        }
  二、获取登录用户、请求URL链接、请求客户端IP、请求成功标志,请求的类、方法、方法中的请求参数
       
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();  
  三、获取Log注解的日志信息
    // 设置action动作
    operLog.setBusinessType(log.businessType().ordinal());
    // 设置标题
    operLog.setTitle(log.title());
    // 设置操作人类别
    operLog.setOperatorType(log.operatorType().ordinal());
    // 是否需要保存request,参数和值
    if (log.isSaveRequestData())
    {
        // 获取参数的信息,传入到数据库中。
        setRequestValue(operLog);
    }

  四、将Log交给Spring定时器,定时保存到数据库日志表
    private ScheduledExecutorService executor = SpringUtils.getBean("scheduledExecutorService");
    public void execute(TimerTask task) {
    executor.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);}

五、异步Task工厂类 AsyncFactory
public static TimerTask recordOper(final SysOperLog operLog) {
return new TimerTask()
{
@Override
public void run()
{
// 远程查询操作地点
operLog.setOperLocation(AddressUtils.getRealAddressByIP(operLog.getOperIp()));
SpringUtils.getBean(ISysOperLogService.class).insertOperlog(operLog);
}
};
}
}

}

posted @   vello  阅读(33)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示