[Spring Aop] 日志记录进阶

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/errizh/article/details/84697848

背景需求:1.项目需要记录用户的访问信息,即操作日志,对关键信息的修改,还需要记录修改字段的旧值和原值。

整个工程前后端分离,前端Web使用了VUE框架,通过Ajax访问后端Rest接口,完成登陆及服务请求。

J2EE后端使用Spring mvc构建http接口,工程的采用老式xml context配置,还未切换到spring boot。

技术点:

1.登陆后,激活Session,标志不同的用户

2.使用自定义Annotation配置不同接口的日志记录参数,包括操作大类(新增、修改、删除)、操作内容、操作库表、是否记录修改值。。

3.在Aspect中获取前端请求参数及controller返回值

4.在Aspect 的beforeActon中获取旧值,并按用户Session保存

5.在Aspect的AfterReturning中记录具体的日志信息

@AfterReturning(returning = "resp", pointcut = "operateAspect()")
    public void afterReturning(JoinPoint joinPoint,Response resp){
        try{
    
        //获取request
        ServletRequestAttributes servletRequestAttributes =             (ServletRequestAttributes)         RequestContextHolder.getRequestAttributes();
            HttpServletRequest req = servletRequestAttributes.getRequest();
            if(req == null){
                return;
            }

            LogOperation operation = new LogOperation();
            operation.setOperateTime(LocalDateTime.now());
            operation.setRequestHost(getIpAddr(req));
            //获取请求url
            operation.setRequestUrl(req.getRequestURI()); 
            //获取请求参数
            operation.setRequestData(JSON.toJSONString(req.getParameterMap()));
            operation.setResponseContent(JSON.toJSONString(resp));
            Admin admin = adminManager.getLoginAdmin();
            operation.setAdminId(admin.getId());
            operation.setAdminAccount(admin.getAccount());
            operation.setAdminOrgId(admin.getOrganizationId());
            operation.setAdminName(admin.getName());
            operation.setAdminEmail(admin.getEmail());
            operation.setAdminPhoneNo(admin.getPhoneNo());

            logOperationDao.insert(operation);
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }

猜你喜欢

转载自blog.csdn.net/errizh/article/details/84697848
今日推荐