使用拦截器(intercept)和AOP记录操作日志-springboot

日志拦截器方法

方法一 .创建拦截器类(使用拦截器全局拦截所有请求)

public class LogInterceptor implements HandlerInterceptor {
  private final Logger logger = LoggerFactory.getLogger(LogInterceptor.class);
  @Override
  public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
    //把整个log中的参数,交给logUtil来获取,并返回log对象
    Log log = null;
    try {
      log = LoggerUtil.getLog(httpServletRequest);
    }catch (GeneralException g){
      logger.warn("logger",g.getMessage());
    }catch (Exception e){
      logger.error("logger",e.getMessage());
    }
    httpServletRequest.setAttribute(LoggerUtil.LOG_OPERATE,log);
    return true;
  }

  @Override
  public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

  }

  @Override
  public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    //返回视图时,插入操作日志
    LogMapper logMapper = getMapper(LogMapper.class,httpServletRequest);
    Log log = (Log) httpServletRequest.getAttribute(LoggerUtil.LOG_OPERATE);
    if(log == null){
      logger.warn("日志信息为空",log);
    }else{
      logMapper.insert(log);
    }
  }
  private  T getMapper(Class clazz,HttpServletRequest request)
  {
    BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
    return factory.getBean(clazz);
  }

}
  •  

拦截器的执行顺序,这里不解释了。这里注意mapper类是如何创建的。 
2. 注册拦截器

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new UserInterceptor()).addPathPatterns("/**").excludePathPatterns("/user/login");
        registry.addInterceptor(new LogInterceptor()).addPathPatterns("/**");
        super.addInterceptors(registry);
    }
}
  •  
  1. LoggerUtil类(保存数据入库使用)
public class LoggerUtil {
    public static final String LOG_TARGET_TYPE="targetType";
    public static final String LOG_ACTION="action";
    public static final String LOG_REMARK="remark";
    public LoggerUtil(){}

    public static Log getLog(HttpServletRequest request){
        //1.依次获取每个属性信息 userId,operator,action,remark,ip,targetType
        Log log = new Log();
        log.setIp(LoggerUtil.getCliectIp(request));
        log.setOperator("operator");
        log.setUserId(1);
        log.setAction("create");
        log.setCustomerId("0000-1111");
        log.setTargetType("message");
        log.setRemark("消息发布");
        return log;
    }
    /**
     * 获取客户端ip地址
     * @param request
     * @return
     */
    public static String getCliectIp(HttpServletRequest request){
        String ip = request.getHeader("X-Real-IP");
        if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
        ip = request.getHeader("X-Forwarded-For");
        if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个IP值,第一个为真实IP。
            int index = ip.indexOf(',');
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        } else {
            return request.getRemoteAddr();
        }
    }

}
  •  
  • loggerUtil类主要返回一个Log对象的实体类。

方法二   AOP记录操作日志

参考:https://blog.csdn.net/axela30w/article/details/82384611

  1. 引入springboot的aop的jar

            org.springframework.boot
            spring-boot-starter-aop
        
  •  
  1. LogAopAction类
@Aspect
@Component
public class LogAopAction {
    private final Logger logger = LoggerFactory.getLogger(LogAopAction.class);
    @Autowired
    private OperatorLogService operatorLogService;
    @Autowired
    private OperationUserService userService;

    @Pointcut("@annotation(com.yitao.cms.config.aopLog.LogAnnotation)")//配置切点
    private void pointCutMethod() {
    }

    //around可获取请求和返回参数!
     @AfterReturning(value = "pointCutMethod()",returning = "rtv")  //执行后操作
    public void after(JoinPoint joinPoint, Object rtv) {
        // 接收到请求,记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession != null) {
            //获取请求参数
            String beanName = joinPoint.getSignature().getDeclaringTypeName();
            String methodName = joinPoint.getSignature().getName();
            String url = request.getRequestURI();
            String remoteAddr = getIpAddr(request);
            String requestMethod = request.getMethod();
            try {
                String targetName = joinPoint.getTarget().getClass().getName();
                Class targetClass = Class.forName(targetName);
                Method[] methods = targetClass.getMethods();
                OperatorLogDto optLog = new OperatorLogDto();
                //请求参数
                if (request.getParameterMap()!=null && request.getParameterMap().isEmpty()!=true) {//dan
                    optLog.setRequestPara(JSON.toJSONString(request.getParameterMap()));
                }else {
                    Object[] object = joinPoint.getArgs();
                    if (object.length>1){
                        optLog.setRequestPara(JSON.toJSONString(object[1]));
                    }
                }
                optLog.setResponsePara(JSON.toJSONString(rtv));//返回参数
                for (Method method : methods) {
                    if (method.getName().equals(methodName)) {
                        LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);
                        if (logAnnotation != null) {
                            optLog.setDescription(logAnnotation.remark());
                            optLog.setTargetType(logAnnotation.targetType());

                        }
                    }
                }
                optLog.setOperatorUrl(url);
                optLog.setMethodName(methodName);
                optLog.setRemoteAddr(remoteAddr);
                operatorLogService.operatorLogAdd(optLog, request);
            } catch (Exception e) {
                logger.error("***操作请求日志记录失败doBefore()***", e);
            }
        }
    }
  •  

2.1 Pointcut优化部分

//切入点设置到自定义的log注解上
    @Pointcut("@annotation(cn.vobile.hss.annotation.LogAnnotation)")
    private void pointCutMethod(){}
  •  

我们可以将切入方法设置到自定义的log注解上,这样aop就会只在有log注解的方法进行拦截了。

  1. 特殊字段的注解
@Retention(RetentionPolicy.RUNTIME)//注解会在class中存在,运行时可通过反射获取
@Target(ElementType.METHOD)//目标是方法
@Documented//文档生成时,该注解将被包含在javadoc中,可去掉
public @interface LogAnnotation {
    String targetType() default "";
    String remark() default "";
}
  •  
  1. 引用部分
    @ApiOperation("商品列表-删除")
    @LogAnnotation(targetType = "ProductInfo-Delete", remark = "商品删除")//切点信息
    @RequestMapping(value = "/deleteProductById", method = RequestMethod.POST)
    public DataOutput deleteProductById(
            HttpServletRequest request,
            @ApiParam(value = "商品Id") @RequestParam(value = "productId") String productId) {
        return productCmsService.deleteProductById(request,productId);
    }

你可能感兴趣的:(Springboot相关知识,开源工具相关知识)