平時我們在做項目時經常需要對一些重要功能操作記錄日志,友善以後跟蹤是誰在操作此功能;我們在操作某些功能時也有可能會發生異常,但是每次發生異常要定位原因我們都要到伺服器去查詢日志才能找到,而且也不能對發生的異常進行統計,進而改進我們的項目,要是能做個功能專門來記錄記錄檔和異常日志那就好了, 當然我們肯定有方法來做這件事情,而且也不會很難,我們可以在需要的方法中增加記錄日志的代碼,和在每個方法中增加記錄異常的代碼,最終把記錄的日志存到資料庫中。聽起來好像很容易,但是我們做起來會發現,做這項工作很繁瑣,而且都是在做一些重複性工作,還增加大量備援代碼,這種方式記錄日志肯定是不可行的。
我們以前學過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注解
六、記錄檔、異常日志查詢功能