使用SpringBoot AOP 記錄操作日志、異常日志的過程
平時(shí)我們?cè)谧鲰?xiàng)目時(shí)經(jīng)常需要對(duì)一些重要功能操作記錄日志,方便以后跟蹤是誰在操作此功能;我們?cè)诓僮髂承┕δ軙r(shí)也有可能會(huì)發(fā)生異常,但是每次發(fā)生異常要定位原因我們都要到服務(wù)器去查詢?nèi)罩静拍苷业?,而且也不能?duì)發(fā)生的異常進(jìn)行統(tǒng)計(jì),從而改進(jìn)我們的項(xiàng)目,要是能做個(gè)功能專門來記錄操作日志和異常日志那就好了, 當(dāng)然我們肯定有方法來做這件事情,而且也不會(huì)很難,我們可以在需要的方法中增加記錄日志的代碼,和在每個(gè)方法中增加記錄異常的代碼,最終把記錄的日志存到數(shù)據(jù)庫中。聽起來好像很容易,但是我們做起來會(huì)發(fā)現(xiàn),做這項(xiàng)工作很繁瑣,而且都是在做一些重復(fù)性工作,還增加大量冗余代碼,這種方式記錄日志肯定是不可行的。
我們以前學(xué)過Spring 三大特性,IOC(控制反轉(zhuǎn)),DI(依賴注入),AOP(面向切面),那其中AOP的主要功能就是將日志記錄,性能統(tǒng)計(jì),安全控制,事務(wù)處理,異常處理等代碼從業(yè)務(wù)邏輯代碼中劃分出來。今天我們就來用springBoot Aop 來做日志記錄,好了,廢話說了一大堆還是上貨吧。
一、創(chuàng)建日志記錄表、異常日志表,表結(jié)構(gòu)如下:
操作日志表
異常日志表
二、添加Maven依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
三、創(chuàng)建操作日志注解類OperLog.java
package com.hyd.zcar.cms.common.utils.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 自定義操作日志注解 * @author wu */ @Target(ElementType.METHOD) //注解放置的目標(biāo)位置,METHOD是可注解在方法級(jí)別上 @Retention(RetentionPolicy.RUNTIME) //注解在哪個(gè)階段執(zhí)行 @Documented public @interface OperLog { String operModul() default ""; // 操作模塊 String operType() default ""; // 操作類型 String operDesc() default ""; // 操作說明 }
四、創(chuàng)建切面類記錄操作日志
package com.hyd.zcar.cms.common.utils.aop; import java.lang.reflect.Method; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; import com.gexin.fastjson.JSON; import com.hyd.zcar.cms.common.utils.IPUtil; import com.hyd.zcar.cms.common.utils.annotation.OperLog; import com.hyd.zcar.cms.common.utils.base.UuidUtil; import com.hyd.zcar.cms.common.utils.security.UserShiroUtil; import com.hyd.zcar.cms.entity.system.log.ExceptionLog; import com.hyd.zcar.cms.entity.system.log.OperationLog; import com.hyd.zcar.cms.service.system.log.ExceptionLogService; import com.hyd.zcar.cms.service.system.log.OperationLogService; /** * 切面處理類,操作日志異常日志記錄處理 * * @author wu * @date 2019/03/21 */ @Aspect @Component public class OperLogAspect { /** * 操作版本號(hào) * <p> * 項(xiàng)目啟動(dòng)時(shí)從命令行傳入,例如:java -jar xxx.war --version=201902 * </p> */ @Value("${version}") private String operVer; @Autowired private OperationLogService operationLogService; @Autowired private ExceptionLogService exceptionLogService; /** * 設(shè)置操作日志切入點(diǎn) 記錄操作日志 在注解的位置切入代碼 */ @Pointcut("@annotation(com.hyd.zcar.cms.common.utils.annotation.OperLog)") public void operLogPoinCut() { } /** * 設(shè)置操作異常切入點(diǎn)記錄異常日志 掃描所有controller包下操作 */ @Pointcut("execution(* com.hyd.zcar.cms.controller..*.*(..))") public void operExceptionLogPoinCut() { } /** * 正常返回通知,攔截用戶操作日志,連接點(diǎn)正常執(zhí)行完成后執(zhí)行, 如果連接點(diǎn)拋出異常,則不會(huì)執(zhí)行 * * @param joinPoint 切入點(diǎn) * @param keys 返回結(jié)果 */ @AfterReturning(value = "operLogPoinCut()", returning = "keys") public void saveOperLog(JoinPoint joinPoint, Object keys) { // 獲取RequestAttributes RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); // 從獲取RequestAttributes中獲取HttpServletRequest的信息 HttpServletRequest request = (HttpServletRequest) requestAttributes .resolveReference(RequestAttributes.REFERENCE_REQUEST); OperationLog operlog = new OperationLog(); try { operlog.setOperId(UuidUtil.get32UUID()); // 主鍵ID // 從切面織入點(diǎn)處通過反射機(jī)制獲取織入點(diǎn)處的方法 MethodSignature signature = (MethodSignature) joinPoint.getSignature(); // 獲取切入點(diǎn)所在的方法 Method method = signature.getMethod(); // 獲取操作 OperLog opLog = method.getAnnotation(OperLog.class); if (opLog != null) { String operModul = opLog.operModul(); String operType = opLog.operType(); String operDesc = opLog.operDesc(); operlog.setOperModul(operModul); // 操作模塊 operlog.setOperType(operType); // 操作類型 operlog.setOperDesc(operDesc); // 操作描述 } // 獲取請(qǐng)求的類名 String className = joinPoint.getTarget().getClass().getName(); // 獲取請(qǐng)求的方法名 String methodName = method.getName(); methodName = className + "." + methodName; operlog.setOperMethod(methodName); // 請(qǐng)求方法 // 請(qǐng)求的參數(shù) Map<String, String> rtnMap = converMap(request.getParameterMap()); // 將參數(shù)所在的數(shù)組轉(zhuǎn)換成json String params = JSON.toJSONString(rtnMap); operlog.setOperRequParam(params); // 請(qǐng)求參數(shù) operlog.setOperRespParam(JSON.toJSONString(keys)); // 返回結(jié)果 operlog.setOperUserId(UserShiroUtil.getCurrentUserLoginName()); // 請(qǐng)求用戶ID operlog.setOperUserName(UserShiroUtil.getCurrentUserName()); // 請(qǐng)求用戶名稱 operlog.setOperIp(IPUtil.getRemortIP(request)); // 請(qǐng)求IP operlog.setOperUri(request.getRequestURI()); // 請(qǐng)求URI operlog.setOperCreateTime(new Date()); // 創(chuàng)建時(shí)間 operlog.setOperVer(operVer); // 操作版本 operationLogService.insert(operlog); } catch (Exception e) { e.printStackTrace(); } } /** * 異常返回通知,用于攔截異常日志信息 連接點(diǎn)拋出異常后執(zhí)行 * * @param joinPoint 切入點(diǎn) * @param e 異常信息 */ @AfterThrowing(pointcut = "operExceptionLogPoinCut()", throwing = "e") public void saveExceptionLog(JoinPoint joinPoint, Throwable e) { // 獲取RequestAttributes RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); // 從獲取RequestAttributes中獲取HttpServletRequest的信息 HttpServletRequest request = (HttpServletRequest) requestAttributes .resolveReference(RequestAttributes.REFERENCE_REQUEST); ExceptionLog excepLog = new ExceptionLog(); try { // 從切面織入點(diǎn)處通過反射機(jī)制獲取織入點(diǎn)處的方法 MethodSignature signature = (MethodSignature) joinPoint.getSignature(); // 獲取切入點(diǎn)所在的方法 Method method = signature.getMethod(); excepLog.setExcId(UuidUtil.get32UUID()); // 獲取請(qǐng)求的類名 String className = joinPoint.getTarget().getClass().getName(); // 獲取請(qǐng)求的方法名 String methodName = method.getName(); methodName = className + "." + methodName; // 請(qǐng)求的參數(shù) Map<String, String> rtnMap = converMap(request.getParameterMap()); // 將參數(shù)所在的數(shù)組轉(zhuǎn)換成json String params = JSON.toJSONString(rtnMap); excepLog.setExcRequParam(params); // 請(qǐng)求參數(shù) excepLog.setOperMethod(methodName); // 請(qǐng)求方法名 excepLog.setExcName(e.getClass().getName()); // 異常名稱 excepLog.setExcMessage(stackTraceToString(e.getClass().getName(), e.getMessage(), e.getStackTrace())); // 異常信息 excepLog.setOperUserId(UserShiroUtil.getCurrentUserLoginName()); // 操作員ID excepLog.setOperUserName(UserShiroUtil.getCurrentUserName()); // 操作員名稱 excepLog.setOperUri(request.getRequestURI()); // 操作URI excepLog.setOperIp(IPUtil.getRemortIP(request)); // 操作員IP excepLog.setOperVer(operVer); // 操作版本號(hào) excepLog.setOperCreateTime(new Date()); // 發(fā)生異常時(shí)間 exceptionLogService.insert(excepLog); } catch (Exception e2) { e2.printStackTrace(); } } /** * 轉(zhuǎn)換request 請(qǐng)求參數(shù) * * @param paramMap request獲取的參數(shù)數(shù)組 */ public Map<String, String> converMap(Map<String, String[]> paramMap) { Map<String, String> rtnMap = new HashMap<String, String>(); for (String key : paramMap.keySet()) { rtnMap.put(key, paramMap.get(key)[0]); } return rtnMap; } /** * 轉(zhuǎn)換異常信息為字符串 * * @param exceptionName 異常名稱 * @param exceptionMessage 異常信息 * @param elements 堆棧信息 */ public String stackTraceToString(String exceptionName, String exceptionMessage, StackTraceElement[] elements) { StringBuffer strbuff = new StringBuffer(); for (StackTraceElement stet : elements) { strbuff.append(stet + "\n"); } String message = exceptionName + ":" + exceptionMessage + "\n\t" + strbuff.toString(); return message; } }
五、在Controller層方法添加@OperLog注解
六、操作日志、異常日志查詢功能
到此這篇關(guān)于使用SpringBoot AOP 記錄操作日志、異常日志的過程的文章就介紹到這了,更多相關(guān)SpringBoot AOP 操作日志、異常日志內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring sentinel哨兵模式相關(guān)原理解析
這篇文章主要介紹了Spring sentinel哨兵模式相關(guān)原理解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-11-11最簡(jiǎn)單的spring boot打包docker鏡像的實(shí)現(xiàn)
這篇文章主要介紹了最簡(jiǎn)單的spring boot打包docker鏡像的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10JavaWeb?使用DBUtils實(shí)現(xiàn)增刪改查方式
這篇文章主要介紹了JavaWeb?使用DBUtils實(shí)現(xiàn)增刪改查方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12詳解Spring Security中權(quán)限注解的使用
這篇文章主要為大家詳細(xì)介紹一下Spring Security中權(quán)限注解的使用方法,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)或工作有一定參考價(jià)值,需要的可以參考一下2022-05-05eclipse啟動(dòng)出現(xiàn)“failed to load the jni shared library”問題解決
這篇文章主要介紹了eclipse啟動(dòng)出現(xiàn)“failed to load the jni shared library”問題解決,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-11-11RestFul風(fēng)格 — 使用@PathVariable傳遞參數(shù)報(bào)錯(cuò)404的解決
這篇文章主要介紹了RestFul風(fēng)格 — 使用@PathVariable傳遞參數(shù)報(bào)錯(cuò)404的解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-10-10Java實(shí)現(xiàn)經(jīng)典游戲俄羅斯方塊(升級(jí)版)的示例代碼
俄羅斯方塊是一款風(fēng)靡全球,從一開始到現(xiàn)在都一直經(jīng)久不衰的電腦、手機(jī)、掌上游戲機(jī)產(chǎn)品,是一款游戲規(guī)則簡(jiǎn)單,但又不缺乏樂趣的簡(jiǎn)單經(jīng)典小游戲。本文將用Java語言實(shí)現(xiàn)這一經(jīng)典游戲,需要的可以參考一下2022-09-09