使用SpringBoot AOP 記錄操作日誌、異常日誌

来源:https://www.cnblogs.com/wm-dv/archive/2019/10/24/11735828.html
-Advertisement-
Play Games

平時我們在做項目時經常需要對一些重要功能操作記錄日誌,方便以後跟蹤是誰在操作此功能;我們在操作某些功能時也有可能會發生異常,但是每次發生異常要定位原因我們都要到伺服器去查詢日誌才能找到,而且也不能對發生的異常進行統計,從而改進我們的項目,要是能做個功能專門來記錄操作日誌和異常日誌那就好了, 當然我們 ...


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

       我們以前學過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註解

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

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 之前我們瞭解了一條查詢語句的執行流程,並介紹了執行過程中涉及的處理模塊。一條查詢語句的執行過程一般是經過連接器、分析器、優化器、執行器等功能模塊,最後到達存儲引擎。 那麼,一條 SQL 更新語句的執行流程又是怎樣的呢? 首先我們創建一個表 user_info,主鍵為 id,創建語句如下: CREAT ...
  • 1 工廠模式(Factory) 1.1 簡單工廠模式 1.2 工廠方法模式 1.3 抽象工廠模式 2 單例模式(Singleton) 3 建造模式(Build) 4 原型模式(Proto) 5 適配器模式(Adapter) 將一個類的介面轉換成客戶希望的另外一個介面。Adapter模式使得原本由於接 ...
  • 引子 媽媽要我的時候已經40歲了。她一定是下了很大的決定才決定終究還是想要個女孩,希望這個女孩可以解救她的孤獨。上高三的時候,有次又是因為哥哥的事情,媽媽把我從學校接回家。一個勁兒的問我怎麼辦好。在我能和她一起思考前的50多年裡,她該是多麼無助。所以當我不斷看自己的掌紋,上面的起起伏伏。在想這一切解 ...
  • 前言 相信大部分開發者對下麵這張架構圖並不陌生吧,現在很多網站/應用都採用了動靜分離的架構進行部署。博主的博客也不例外,主機採用的是阿裡雲的 ECS,使用 CDN 做靜態內容分發,不過靜態文件還是存儲在 ECS,採用的是 Nginx 做動靜分離。今天我們來學習一下如何使用阿裡雲 OSS 做動靜分離。 ...
  • 前言 今天我們來看看備忘錄模式【MementoPattern】,我們平時寫文檔的時候一不小心寫錯了一些字或者刪除了一些東西怎麼辦呢?不用怕、Windows裡面提供了Ctrl+Z,後退一步,可以一直後退。這個東西怎麼實現的呢?我們記得之前講過一個命令模式。命令保存的是發起人的具體命令(對應的行為)、我 ...
  • 運行springboot項目報錯: *************************** APPLICATION FAILED TO START *************************** Description: Field userMapper in com.whohim.spri ...
  • 2019-10-24-23:21:17 目錄 1.抽象的方法 2.抽象類 3.抽象類和抽象方法的使用 4.抽象類的註意事項 5.案例代碼 1.抽象的方法 What:如果父類當中的方法不確定如何進行{}方法體實現,那麼這就是一個抽象方法。 抽象方法:就是加上abstract關鍵字,然後去掉大括弧,直接 ...
  • 1 #是將傳入的值當做字元串的形式,eg:select id,name,age from student where id =#{id},當前端把id值1,傳入到後臺的時候,就相當於 select id,name,age from student where id ='1'. 2 $是將傳入的數據直 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...