- 資訊首頁(yè) > 開(kāi)發(fā)技術(shù) >
- 使用SpringBoot AOP 記錄操作日志、異常日志的過(guò)程
平時(shí)我們在做項目時(shí)經(jīng)常需要對一些重要功能操作記錄日志,方便以后跟蹤是誰(shuí)在操作此功能;我們在操作某些功能時(shí)也有可能會(huì )發(fā)生異常,但是每次發(fā)生異常要定位原因我們都要到服務(wù)器去查詢(xún)日志才能找到,而且也不能對發(fā)生的異常進(jìn)行統計,從而改進(jìn)我們的項目,要是能做個(gè)功能專(zhuān)門(mén)來(lái)記錄操作日志和異常日志那就好了, 當然我們肯定有方法來(lái)做這件事情,而且也不會(huì )很難,我們可以在需要的方法中增加記錄日志的代碼,和在每個(gè)方法中增加記錄異常的代碼,最終把記錄的日志存到數據庫中。聽(tīng)起來(lái)好像很容易,但是我們做起來(lái)會(huì )發(fā)現,做這項工作很繁瑣,而且都是在做一些重復性工作,還增加大量冗余代碼,這種方式記錄日志肯定是不可行的。
我們以前學(xué)過(guò)Spring 三大特性,IOC(控制反轉),DI(依賴(lài)注入),AOP(面向切面),那其中AOP的主要功能就是將日志記錄,性能統計,安全控制,事務(wù)處理,異常處理等代碼從業(yè)務(wù)邏輯代碼中劃分出來(lái)。今天我們就來(lái)用springBoot Aop 來(lái)做日志記錄,好了,廢話(huà)說(shuō)了一大堆還是上貨吧。
操作日志表
異常日志表
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
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) //注解放置的目標位置,METHOD是可注解在方法級別上 @Retention(RetentionPolicy.RUNTIME) //注解在哪個(gè)階段執行 @Documented public @interface OperLog { String operModul() default ""; // 操作模塊 String operType() default ""; // 操作類(lèi)型 String operDesc() default ""; // 操作說(shuō)明 }
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; /** * 切面處理類(lèi),操作日志異常日志記錄處理 * * @author wu * @date 2019/03/21 */ @Aspect @Component public class OperLogAspect { /** * 操作版本號 * <p> * 項目啟動(dòng)時(shí)從命令行傳入,例如:java -jar xxx.war --version=201902 * </p> */ @Value("${version}") private String operVer; @Autowired private OperationLogService operationLogService; @Autowired private ExceptionLogService exceptionLogService; /** * 設置操作日志切入點(diǎn) 記錄操作日志 在注解的位置切入代碼 */ @Pointcut("@annotation(com.hyd.zcar.cms.common.utils.annotation.OperLog)") public void operLogPoinCut() { } /** * 設置操作異常切入點(diǎn)記錄異常日志 掃描所有controller包下操作 */ @Pointcut("execution(* com.hyd.zcar.cms.controller..*.*(..))") public void operExceptionLogPoinCut() { } /** * 正常返回通知,攔截用戶(hù)操作日志,連接點(diǎn)正常執行完成后執行, 如果連接點(diǎn)拋出異常,則不會(huì )執行 * * @param joinPoint 切入點(diǎn) * @param keys 返回結果 */ @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)處通過(guò)反射機制獲取織入點(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); // 操作類(lèi)型 operlog.setOperDesc(operDesc); // 操作描述 } // 獲取請求的類(lèi)名 String className = joinPoint.getTarget().getClass().getName(); // 獲取請求的方法名 String methodName = method.getName(); methodName = className + "." + methodName; operlog.setOperMethod(methodName); // 請求方法 // 請求的參數 Map<String, String> rtnMap = converMap(request.getParameterMap()); // 將參數所在的數組轉換成json String params = JSON.toJSONString(rtnMap); operlog.setOperRequParam(params); // 請求參數 operlog.setOperRespParam(JSON.toJSONString(keys)); // 返回結果 operlog.setOperUserId(UserShiroUtil.getCurrentUserLoginName()); // 請求用戶(hù)ID operlog.setOperUserName(UserShiroUtil.getCurrentUserName()); // 請求用戶(hù)名稱(chēng) operlog.setOperIp(IPUtil.getRemortIP(request)); // 請求IP operlog.setOperUri(request.getRequestURI()); // 請求URI operlog.setOperCreateTime(new Date()); // 創(chuàng )建時(shí)間 operlog.setOperVer(operVer); // 操作版本 operationLogService.insert(operlog); } catch (Exception e) { e.printStackTrace(); } } /** * 異常返回通知,用于攔截異常日志信息 連接點(diǎn)拋出異常后執行 * * @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)處通過(guò)反射機制獲取織入點(diǎn)處的方法 MethodSignature signature = (MethodSignature) joinPoint.getSignature(); // 獲取切入點(diǎn)所在的方法 Method method = signature.getMethod(); excepLog.setExcId(UuidUtil.get32UUID()); // 獲取請求的類(lèi)名 String className = joinPoint.getTarget().getClass().getName(); // 獲取請求的方法名 String methodName = method.getName(); methodName = className + "." + methodName; // 請求的參數 Map<String, String> rtnMap = converMap(request.getParameterMap()); // 將參數所在的數組轉換成json String params = JSON.toJSONString(rtnMap); excepLog.setExcRequParam(params); // 請求參數 excepLog.setOperMethod(methodName); // 請求方法名 excepLog.setExcName(e.getClass().getName()); // 異常名稱(chēng) excepLog.setExcMessage(stackTraceToString(e.getClass().getName(), e.getMessage(), e.getStackTrace())); // 異常信息 excepLog.setOperUserId(UserShiroUtil.getCurrentUserLoginName()); // 操作員ID excepLog.setOperUserName(UserShiroUtil.getCurrentUserName()); // 操作員名稱(chēng) excepLog.setOperUri(request.getRequestURI()); // 操作URI excepLog.setOperIp(IPUtil.getRemortIP(request)); // 操作員IP excepLog.setOperVer(operVer); // 操作版本號 excepLog.setOperCreateTime(new Date()); // 發(fā)生異常時(shí)間 exceptionLogService.insert(excepLog); } catch (Exception e2) { e2.printStackTrace(); } } /** * 轉換request 請求參數 * * @param paramMap request獲取的參數數組 */ 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; } /** * 轉換異常信息為字符串 * * @param exceptionName 異常名稱(chēng) * @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; } }
到此這篇關(guān)于使用SpringBoot AOP 記錄操作日志、異常日志的過(guò)程的文章就介紹到這了,更多相關(guān)SpringBoot AOP 操作日志、異常日志內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自互聯(lián)網(wǎng)轉載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權請聯(lián)系QQ:712375056 進(jìn)行舉報,并提供相關(guān)證據,一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容。
Copyright ? 2009-2021 56dr.com. All Rights Reserved. 特網(wǎng)科技 特網(wǎng)云 版權所有 珠海市特網(wǎng)科技有限公司 粵ICP備16109289號
域名注冊服務(wù)機構:阿里云計算有限公司(萬(wàn)網(wǎng)) 域名服務(wù)機構:煙臺帝思普網(wǎng)絡(luò )科技有限公司(DNSPod) CDN服務(wù):阿里云計算有限公司 中國互聯(lián)網(wǎng)舉報中心 增值電信業(yè)務(wù)經(jīng)營(yíng)許可證B2
建議您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流瀏覽器瀏覽本網(wǎng)站