• 使用SpringBoot AOP 记录操作日志、异常日志


            平时我们在做项目时经常需要对一些重要功能操作记录日志,方便以后跟踪是谁在操作此功能;我们在操作某些功能时也有可能会发生异常,但是每次发生异常要定位原因我们都要到服务器去查询日志才能找到,而且也不能对发生的异常进行统计,从而改进我们的项目,要是能做个功能专门来记录操作日志和异常日志那就好了, 当然我们肯定有方法来做这件事情,而且也不会很难,我们可以在需要的方法中增加记录日志的代码,和在每个方法中增加记录异常的代码,最终把记录的日志存到数据库中。听起来好像很容易,但是我们做起来会发现,做这项工作很繁琐,而且都是在做一些重复性工作,还增加大量冗余代码,这种方式记录日志肯定是不可行的。

           我们以前学过Spring 三大特性,IOC(控制反转),DI(依赖注入),AOP(面向切面),那其中AOP的主要功能就是将日志记录,性能统计,安全控制,事务处理,异常处理等代码从业务逻辑代码中划分出来。今天我们就来用springBoot Aop 来做日志记录,好了,废话说了一大堆还是上货吧。

    一、创建日志记录表、异常日志表,表结构如下:

          

           操作日志表

          

            异常日志表

    二、添加Maven依赖

    1 <dependency>
    2     <groupId>org.springframework.boot</groupId>
    3     <artifactId>spring-boot-starter-aop</artifactId>
    4 </dependency>

    三、创建操作日志注解类OperLog.java

     1 package com.hyd.zcar.cms.common.utils.annotation;
     2 
     3 import java.lang.annotation.Documented;
     4 import java.lang.annotation.ElementType;
     5 import java.lang.annotation.Retention;
     6 import java.lang.annotation.RetentionPolicy;
     7 import java.lang.annotation.Target;
     8 
     9 /**
    10  * 自定义操作日志注解
    11  * @author wu
    12  */
    13 @Target(ElementType.METHOD) //注解放置的目标位置,METHOD是可注解在方法级别上
    14 @Retention(RetentionPolicy.RUNTIME) //注解在哪个阶段执行
    15 @Documented 
    16 public @interface OperLog {
    17     String operModul() default ""; // 操作模块
    18     String operType() default "";  // 操作类型
    19     String operDesc() default "";  // 操作说明
    20 }

    四、创建切面类记录操作日志

      1 package com.hyd.zcar.cms.common.utils.aop;
      2 
      3 import java.lang.reflect.Method;
      4 import java.util.Date;
      5 import java.util.HashMap;
      6 import java.util.Map;
      7 
      8 import javax.servlet.http.HttpServletRequest;
      9 
     10 import org.aspectj.lang.JoinPoint;
     11 import org.aspectj.lang.annotation.AfterReturning;
     12 import org.aspectj.lang.annotation.AfterThrowing;
     13 import org.aspectj.lang.annotation.Aspect;
     14 import org.aspectj.lang.annotation.Pointcut;
     15 import org.aspectj.lang.reflect.MethodSignature;
     16 import org.springframework.beans.factory.annotation.Autowired;
     17 import org.springframework.beans.factory.annotation.Value;
     18 import org.springframework.stereotype.Component;
     19 import org.springframework.web.context.request.RequestAttributes;
     20 import org.springframework.web.context.request.RequestContextHolder;
     21 
     22 import com.gexin.fastjson.JSON;
     23 import com.hyd.zcar.cms.common.utils.IPUtil;
     24 import com.hyd.zcar.cms.common.utils.annotation.OperLog;
     25 import com.hyd.zcar.cms.common.utils.base.UuidUtil;
     26 import com.hyd.zcar.cms.common.utils.security.UserShiroUtil;
     27 import com.hyd.zcar.cms.entity.system.log.ExceptionLog;
     28 import com.hyd.zcar.cms.entity.system.log.OperationLog;
     29 import com.hyd.zcar.cms.service.system.log.ExceptionLogService;
     30 import com.hyd.zcar.cms.service.system.log.OperationLogService;
     31 
     32 /**
     33  * 切面处理类,操作日志异常日志记录处理
     34  * 
     35  * @author wu
     36  * @date 2019/03/21
     37  */
     38 @Aspect
     39 @Component
     40 public class OperLogAspect {
     41 
     42     /**
     43      * 操作版本号
     44      * <p>
     45      * 项目启动时从命令行传入,例如:java -jar xxx.war --version=201902
     46      * </p>
     47      */
     48     @Value("${version}")
     49     private String operVer;
     50 
     51     @Autowired
     52     private OperationLogService operationLogService;
     53 
     54     @Autowired
     55     private ExceptionLogService exceptionLogService;
     56 
     57     /**
     58      * 设置操作日志切入点 记录操作日志 在注解的位置切入代码
     59      */
     60     @Pointcut("@annotation(com.hyd.zcar.cms.common.utils.annotation.OperLog)")
     61     public void operLogPoinCut() {
     62     }
     63 
     64     /**
     65      * 设置操作异常切入点记录异常日志 扫描所有controller包下操作
     66      */
     67     @Pointcut("execution(* com.hyd.zcar.cms.controller..*.*(..))")
     68     public void operExceptionLogPoinCut() {
     69     }
     70 
     71     /**
     72      * 正常返回通知,拦截用户操作日志,连接点正常执行完成后执行, 如果连接点抛出异常,则不会执行
     73      * 
     74      * @param joinPoint 切入点
     75      * @param keys      返回结果
     76      */
     77     @AfterReturning(value = "operLogPoinCut()", returning = "keys")
     78     public void saveOperLog(JoinPoint joinPoint, Object keys) {
     79         // 获取RequestAttributes
     80         RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
     81         // 从获取RequestAttributes中获取HttpServletRequest的信息
     82         HttpServletRequest request = (HttpServletRequest) requestAttributes
     83                 .resolveReference(RequestAttributes.REFERENCE_REQUEST);
     84 
     85         OperationLog operlog = new OperationLog();
     86         try {
     87             operlog.setOperId(UuidUtil.get32UUID()); // 主键ID
     88 
     89             // 从切面织入点处通过反射机制获取织入点处的方法
     90             MethodSignature signature = (MethodSignature) joinPoint.getSignature();
     91             // 获取切入点所在的方法
     92             Method method = signature.getMethod();
     93             // 获取操作
     94             OperLog opLog = method.getAnnotation(OperLog.class);
     95             if (opLog != null) {
     96                 String operModul = opLog.operModul();
     97                 String operType = opLog.operType();
     98                 String operDesc = opLog.operDesc();
     99                 operlog.setOperModul(operModul); // 操作模块
    100                 operlog.setOperType(operType); // 操作类型
    101                 operlog.setOperDesc(operDesc); // 操作描述
    102             }
    103             // 获取请求的类名
    104             String className = joinPoint.getTarget().getClass().getName();
    105             // 获取请求的方法名
    106             String methodName = method.getName();
    107             methodName = className + "." + methodName;
    108 
    109             operlog.setOperMethod(methodName); // 请求方法
    110 
    111             // 请求的参数
    112             Map<String, String> rtnMap = converMap(request.getParameterMap());
    113             // 将参数所在的数组转换成json
    114             String params = JSON.toJSONString(rtnMap);
    115 
    116             operlog.setOperRequParam(params); // 请求参数
    117             operlog.setOperRespParam(JSON.toJSONString(keys)); // 返回结果
    118             operlog.setOperUserId(UserShiroUtil.getCurrentUserLoginName()); // 请求用户ID
    119             operlog.setOperUserName(UserShiroUtil.getCurrentUserName()); // 请求用户名称
    120             operlog.setOperIp(IPUtil.getRemortIP(request)); // 请求IP
    121             operlog.setOperUri(request.getRequestURI()); // 请求URI
    122             operlog.setOperCreateTime(new Date()); // 创建时间
    123             operlog.setOperVer(operVer); // 操作版本
    124             operationLogService.insert(operlog);
    125         } catch (Exception e) {
    126             e.printStackTrace();
    127         }
    128     }
    129 
    130     /**
    131      * 异常返回通知,用于拦截异常日志信息 连接点抛出异常后执行
    132      * 
    133      * @param joinPoint 切入点
    134      * @param e         异常信息
    135      */
    136     @AfterThrowing(pointcut = "operExceptionLogPoinCut()", throwing = "e")
    137     public void saveExceptionLog(JoinPoint joinPoint, Throwable e) {
    138         // 获取RequestAttributes
    139         RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    140         // 从获取RequestAttributes中获取HttpServletRequest的信息
    141         HttpServletRequest request = (HttpServletRequest) requestAttributes
    142                 .resolveReference(RequestAttributes.REFERENCE_REQUEST);
    143 
    144         ExceptionLog excepLog = new ExceptionLog();
    145         try {
    146             // 从切面织入点处通过反射机制获取织入点处的方法
    147             MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    148             // 获取切入点所在的方法
    149             Method method = signature.getMethod();
    150             excepLog.setExcId(UuidUtil.get32UUID());
    151             // 获取请求的类名
    152             String className = joinPoint.getTarget().getClass().getName();
    153             // 获取请求的方法名
    154             String methodName = method.getName();
    155             methodName = className + "." + methodName;
    156             // 请求的参数
    157             Map<String, String> rtnMap = converMap(request.getParameterMap());
    158             // 将参数所在的数组转换成json
    159             String params = JSON.toJSONString(rtnMap);
    160             excepLog.setExcRequParam(params); // 请求参数
    161             excepLog.setOperMethod(methodName); // 请求方法名
    162             excepLog.setExcName(e.getClass().getName()); // 异常名称
    163             excepLog.setExcMessage(stackTraceToString(e.getClass().getName(), e.getMessage(), e.getStackTrace())); // 异常信息
    164             excepLog.setOperUserId(UserShiroUtil.getCurrentUserLoginName()); // 操作员ID
    165             excepLog.setOperUserName(UserShiroUtil.getCurrentUserName()); // 操作员名称
    166             excepLog.setOperUri(request.getRequestURI()); // 操作URI
    167             excepLog.setOperIp(IPUtil.getRemortIP(request)); // 操作员IP
    168             excepLog.setOperVer(operVer); // 操作版本号
    169             excepLog.setOperCreateTime(new Date()); // 发生异常时间
    170 
    171             exceptionLogService.insert(excepLog);
    172 
    173         } catch (Exception e2) {
    174             e2.printStackTrace();
    175         }
    176 
    177     }
    178 
    179     /**
    180      * 转换request 请求参数
    181      * 
    182      * @param paramMap request获取的参数数组
    183      */
    184     public Map<String, String> converMap(Map<String, String[]> paramMap) {
    185         Map<String, String> rtnMap = new HashMap<String, String>();
    186         for (String key : paramMap.keySet()) {
    187             rtnMap.put(key, paramMap.get(key)[0]);
    188         }
    189         return rtnMap;
    190     }
    191 
    192     /**
    193      * 转换异常信息为字符串
    194      * 
    195      * @param exceptionName    异常名称
    196      * @param exceptionMessage 异常信息
    197      * @param elements         堆栈信息
    198      */
    199     public String stackTraceToString(String exceptionName, String exceptionMessage, StackTraceElement[] elements) {
    200         StringBuffer strbuff = new StringBuffer();
    201         for (StackTraceElement stet : elements) {
    202             strbuff.append(stet + "
    ");
    203         }
    204         String message = exceptionName + ":" + exceptionMessage + "
    	" + strbuff.toString();
    205         return message;
    206     }
    207 }

    五、在Controller层方法添加@OperLog注解

     六、操作日志、异常日志查询功能

  • 相关阅读:
    php json_decode无法处理解决方法
    jquery ajax怎么使用jsonp跨域访问
    jquery ajax怎么使用jsonp跨域访问
    查看xml源码的方法
    php array_push 与 $arr[]=$value 性能比较
    生成个性二维码方法
    PHP匿名函数的写法
    PHP rand和mt_rand 区别
    C++ 顺序表
    线索树的建立与遍历
  • 原文地址:https://www.cnblogs.com/wm-dv/p/11735828.html
Copyright © 2020-2023  润新知