使用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 + "\n");
203         }
204         String message = exceptionName + ":" + exceptionMessage + "\n\t" + strbuff.toString();
205         return message;
206     }
207 }

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

 六、操作日志、異常日志查詢功能

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM