五、登录日志、操作日志

1. 登录日志

1.1 登录成功、失败的日志示例
    // 记录登录成功日志
    AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
    // 记录登录失败日志(异常信息为:用户不存在/密码错误)
    AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
1.2 AsyncFactory.recordLogininfor
    // recordLogininfor用来创建SysLogininfor对象,并插入到数据库中,并将这些操作封装成实现了Runnable的TimerTask,交由线程池异步调度、执行
    public static TimerTask recordLogininfor(final String username, final String status, final String message,
            final Object... args) {
        // 创建任务(TimeTask实现了Runnable,可作为一个任务交由线程池执行,由线程池异步调度执行)
        return new TimerTask() {
            // 重写run方法
            @Override
            public void run() {
                // 构造登录日志对象
                SysLogininfor logininfor = new SysLogininfor();
                // 设置登录日志信息
                logininfor.setUserName(username);
                logininfor.setIpaddr(ip);
                logininfor.setLoginLocation(address);
                logininfor.setBrowser(browser);
                logininfor.setOs(os);
                logininfor.setMsg(message);
                // 设置日志状态
                if (StringUtils.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER)) {
                    logininfor.setStatus(Constants.SUCCESS);
                } else if (Constants.LOGIN_FAIL.equals(status)) {
                    logininfor.setStatus(Constants.FAIL);
                }
                // 插入日志数据
                SpringUtils.getBean(ISysLogininforService.class).insertLogininfor(logininfor);
            }
        };
    }
1.3 AsyncManager.me
public class AsyncManager {
  
    private AsyncManager(){}
    // 饿汉式单例模式
    private static AsyncManager me = new AsyncManager();

    public static AsyncManager me() {
        return me;
    }

    // 其余(略)
}
1.4 AsyncManager.execute
public class AsyncManager {

    // 操作延迟10毫秒
    private final int OPERATE_DELAY_TIME = 10;

    // (通过beanName获取bean)
    // 异步操作任务调度线程池(实现类是ScheduledThreadPoolExecutor,
    // ScheduledThreadPoolExecutor可用来执行周期性、延迟性任务)
    private ScheduledExecutorService executor = SpringUtils.getBean("scheduledExecutorService");

    // 执行任务
    public void execute(TimerTask task) {
        // 延迟10毫秒执行
        executor.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);
    }
}
1.5 创建ScheduledExecutorService
    @Bean(name = "scheduledExecutorService")
    protected ScheduledExecutorService scheduledExecutorService()
    {
        return new ScheduledThreadPoolExecutor(corePoolSize,
                new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build(),
                new ThreadPoolExecutor.CallerRunsPolicy())
        {
            // 这里重写了afterExecute方法,如果执行任务时出现异常,会将异常传递到afterExecute的参数中
            @Override
            protected void afterExecute(Runnable r, Throwable t)
            {
                super.afterExecute(r, t);
                // 记录异常信息
                Threads.printException(r, t);
            }
        };
    }

    综上,可知记录登录日志是先通过AsyncFactory.recordLogininfor创建SysLogininfor并插入到数据库中,并将这些操作封装成实现了Runnable的TimerTask,之后交由ScheduledThreadPoolExecutor异步调度,延迟10毫秒执行。

2. 操作日志

2.1 操作日志示例

    在需要记录操作日志的方法上贴上@Log注解,并传入模块名、功能名等参数对日志属性进行设置:

    @PreAuthorize("@ss.hasPermi('system:config:add')")
    @Log(title = "参数管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysConfig config)
    {
        if (UserConstants.NOT_UNIQUE.equals(configService.checkConfigKeyUnique(config)))
        {
            return AjaxResult.error("新增参数'" + config.getConfigName() + "'失败,参数键名已存在");
        }
        config.setCreateBy(getUsername());
        return toAjax(configService.insertConfig(config));
    }
2.2 操作日志切面

    在LogAspect中,会以@Log注解为织入点,在方法返回后或抛异常后对贴有@Log注解的方法进行处理:

// 日志切面
@Aspect
@Component
public class LogAspect {
    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);

    // 方法返回后执行
    // jsonResult是方法的返回值
    @AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Log controllerLog, Object jsonResult) {
        // 调用handleLog处理@Log注解及请求、响应参数
        handleLog(joinPoint, controllerLog, null, jsonResult);
    }

    // 抛异常后执行
    // e为异常对象
    @AfterThrowing(value = "@annotation(controllerLog)", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Log controllerLog, Exception e) {
        // 调用handleLog处理@Log注解及请求、响应参数
        handleLog(joinPoint, controllerLog, e, null);
    }

}
LogAspect.handleLog
    protected void handleLog(final JoinPoint joinPoint, Log controllerLog, final Exception e, Object jsonResult) {
        try {
            // 获取当前登录用户
            LoginUser loginUser = SecurityUtils.getLoginUser();

            // 创建操作日志对象
            SysOperLog operLog = new SysOperLog();
            // 将操作状态设置为成功
            operLog.setStatus(BusinessStatus.SUCCESS.ordinal());
            // 请求的地址
            String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
            operLog.setOperIp(ip);
            // 设置请求url
            operLog.setOperUrl(ServletUtils.getRequest().getRequestURI());
            if (loginUser != null) {
                // 设置操作人
                operLog.setOperName(loginUser.getUsername());
            }
            // e不为null,即方法抛异常了
            if (e != null) {
                // 将操作状态设置为失败,并设置异常信息
                operLog.setStatus(BusinessStatus.FAIL.ordinal());
                operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
            }
            // 设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            operLog.setMethod(className + "." + methodName + "()");
            // 设置请求方式
            operLog.setRequestMethod(ServletUtils.getRequest().getMethod());
            // 将controllerLog中配置的参数信息设置到operLog中
            // 将joinPoint中的请求信息设置到operLog中
            // 将jsonResult中的响应信息设置到operLog中
            getControllerMethodDescription(joinPoint, controllerLog, operLog, jsonResult);
            // AsyncFactory.recordOper:将操作日志插入到数据库中并封装成实现了Runnable的TimerTask作为线程池的任务
            // AsyncManager.me().execute:将任务放入ScheduledThreadPoolExecutor中,延迟10毫秒执行
            AsyncManager.me().execute(AsyncFactory.recordOper(operLog));
        } catch (Exception exp) {
            // 记录本地异常日志
            log.error("==前置通知异常==");
            log.error("异常信息:{}", exp.getMessage());
            exp.printStackTrace();
        }
    }

    综上,可知记录登录日志、操作日志是先创建对应的日志对象并插入到数据库中,并将这些操作封装成实现了Runnable的TimerTask,之后交由ScheduledThreadPoolExecutor异步调度,延迟10毫秒执行。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容