基于Spring AOP實(shí)現(xiàn)日志自動(dòng)打印功能
概述
日志記錄是現(xiàn)代應(yīng)用程序開發(fā)中的重要組成部分。然而,在實(shí)際開發(fā)中,我們經(jīng)常面臨一些痛點(diǎn):
- 重復(fù)打印出入?yún)?/strong>:在開發(fā)中經(jīng)常需要在每個(gè)方法中手動(dòng)編寫日志代碼,這樣的工作不僅重復(fù),而且使代碼顯得冗余和雜亂。
- 統(tǒng)一的追蹤標(biāo)識(shí): 在排查問(wèn)題時(shí),我們經(jīng)常通過(guò)接口請(qǐng)求信息去查日志,這個(gè)時(shí)候我們一般需要一個(gè)traceId將所有請(qǐng)求串起來(lái),這幾乎是每個(gè)方法都必須實(shí)現(xiàn)的功能:打印traceId。
- 接口requestId的返回: 為了方便上下游查問(wèn)題,一般在接口設(shè)計(jì)時(shí),響應(yīng)體都包含一個(gè)requestId字段,這個(gè) requestId 字段,一般就是我們打印的traceId。如果我們每次都手動(dòng)設(shè)置,需要對(duì)各種返回情況(如204、500)等進(jìn)行判斷,顯得代碼雜亂和臃腫。
- 接口耗時(shí)打印:我們需要記錄每個(gè)功能耗時(shí)的情況,方便性能問(wèn)題排查。
使用 Spring AOP和Logback來(lái)封裝日志打印組件
1. 引入相關(guān)依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> </dependency>
2. 創(chuàng)建Aop切面
import com.fasterxml.jackson.databind.ObjectMapper; import com.gis.components.dto.Response; import com.gis.components.dto.StatusCode; import com.gis.components.exception.BizException; import com.gis.components.exception.SysException; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.slf4j.MDC; import org.springframework.core.annotation.AnnotationUtils; import java.lang.reflect.Method; import java.util.Arrays; import java.util.UUID; import java.util.function.Function; @Slf4j @Aspect public class LogAspect { private static ObjectMapper objectMapper = new ObjectMapper(); public static final String REQUEST_TRACE_ID = "REQUEST_TRACE_ID"; /** * @LogTag 注解攔截器 * 在方法執(zhí)行前后記錄日志,并在出現(xiàn)異常時(shí)拋出RuntimeException。 * @param proceedingJoinPoint 切入點(diǎn)對(duì)象,提供了對(duì)目標(biāo)方法的控制權(quán)。 * @return 目標(biāo)方法的執(zhí)行結(jié)果。 */ @Pointcut("execution(* com.yourpackage..*(..))") public Object logExecution(ProceedingJoinPoint proceedingJoinPoint) { return logExecutionInner(proceedingJoinPoint,e -> { throw new RuntimeException(e); }); } /** * 記錄方法執(zhí)行日志和處理異常。 * @param proceedingJoinPoint 切入點(diǎn)對(duì)象,用于獲取方法信息和執(zhí)行方法。 * @param exceptionHandler 異常處理函數(shù),當(dāng)方法執(zhí)行過(guò)程中出現(xiàn)異常時(shí)交由異常處理函數(shù)處理 * @return 方法執(zhí)行的結(jié)果。 */ private Object logExecutionInner(ProceedingJoinPoint proceedingJoinPoint, Function<Throwable,Object> exceptionHandler) { long start = System.currentTimeMillis(); String traceId = null; String currentTrace = MDC.get(REQUEST_TRACE_ID); if(currentTrace == null || currentTrace.isEmpty()){ traceId = UUID.randomUUID().toString().replaceAll("-", ""); }else { traceId = currentTrace; } MDC.put(REQUEST_TRACE_ID, traceId); // 獲取方法聲明 MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature(); Method method = signature.getMethod(); String s = proceedingJoinPoint.getSignature().toString(); log.info("START PROCESSING: {}",s); // 方法入?yún)? Object[] args = proceedingJoinPoint.getArgs(); try { log.info("method[{}] request:{}",method.getName(), objectMapper.writeValueAsString(args)); // 執(zhí)行方法 Object result = proceedingJoinPoint.proceed(); Class returnType = signature.getReturnType(); if(returnType == Response.class || returnType.getGenericSuperclass() == Response.class){ ((Response<?>) result).setRequestId(traceId); } log.info("method[{}] response:{}",method.getName(),objectMapper.writeValueAsString(result)); return result; } catch (Throwable e){ log.info("method[{}] 執(zhí)行異常",method.getName(),e); return exceptionHandler.apply(e); }finally { // 方法執(zhí)行時(shí)間 long executionTime = System.currentTimeMillis() - start; log.info("END PROCESSING,cost:{} ms",executionTime); MDC.remove(REQUEST_TRACE_ID); } } }
通過(guò)上述代碼,你就能夠?qū)崿F(xiàn)切入點(diǎn)的方法的日志自動(dòng)化打印、traceId自動(dòng)打印、requestId自動(dòng)填充的功能了。但還不夠通用,如果你想將上述功能封裝為一個(gè)包,提供給別人使用,該如何去做呢?請(qǐng)看下文。
使用自動(dòng)裝配以及注解進(jìn)行擴(kuò)展
1. 取消LogAspect類上的@Component注解,通過(guò)配置類進(jìn)行創(chuàng)建bean對(duì)象。
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; @Configuration @EnableAspectJAutoProxy public class LogAutoConfiguration { @Bean @ConditionalOnMissingBean(LogAspect.class) public LogAspect catchLogAspect() { return new LogAspect(); } }
2. 創(chuàng)建注解
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 日志注解,用于打印日志出入?yún)⒌裙δ? */ @Target({ElementType.METHOD,ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface LogTag { /** * 日志前綴 * @return */ String prefix() default ""; /** * 是否將出入?yún)?duì)象JSON化打印 * @return true 表示轉(zhuǎn)化為JSON,false 表示打印原始入?yún)ⅰ? */ boolean printToJson() default true; }
3.修改Aop切面代碼,改為攔截注解
import com.fasterxml.jackson.databind.ObjectMapper; import com.gis.components.dto.Response; import com.gis.components.dto.StatusCode; import com.gis.components.exception.BizException; import com.gis.components.exception.SysException; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.slf4j.MDC; import org.springframework.core.annotation.AnnotationUtils; import java.lang.reflect.Method; import java.util.Arrays; import java.util.UUID; import java.util.function.Function; @Slf4j @Aspect @Component public class LogAspect { private static ObjectMapper objectMapper = new ObjectMapper(); public static final String REQUEST_TRACE_ID = "REQUEST_TRACE_ID"; @Pointcut("@annotation(LogTag) || @within(LogTag)") public void logPointcut() { } /** * @LogTag 注解攔截器 * 在方法執(zhí)行前后記錄日志,并在出現(xiàn)異常時(shí)拋出RuntimeException。 * @param proceedingJoinPoint 切入點(diǎn)對(duì)象,提供了對(duì)目標(biāo)方法的控制權(quán)。 * @return 目標(biāo)方法的執(zhí)行結(jié)果。 */ @Around("logPointcut()") public Object logExecution(ProceedingJoinPoint proceedingJoinPoint) { return logExecutionInner(proceedingJoinPoint,e -> { throw new RuntimeException(e); }); } /** * 記錄方法執(zhí)行日志和處理異常。 * @param proceedingJoinPoint 切入點(diǎn)對(duì)象,用于獲取方法信息和執(zhí)行方法。 * @param exceptionHandler 異常處理函數(shù),當(dāng)方法執(zhí)行過(guò)程中出現(xiàn)異常時(shí)交由異常處理函數(shù)處理 * @return 方法執(zhí)行的結(jié)果。 */ private Object logExecutionInner(ProceedingJoinPoint proceedingJoinPoint, Function<Throwable,Object> exceptionHandler) { long start = System.currentTimeMillis(); String traceId = null; String currentTrace = MDC.get(REQUEST_TRACE_ID); if(currentTrace == null || currentTrace.isEmpty()){ traceId = UUID.randomUUID().toString().replaceAll("-", ""); }else { traceId = currentTrace; } MDC.put(REQUEST_TRACE_ID, traceId); // 獲取方法聲明 MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature(); Method method = signature.getMethod(); // 獲取注解 LogTag logTag = AnnotationUtils.findAnnotation(method, LogTag.class); if (logTag == null) { logTag = AnnotationUtils.findAnnotation(signature.getDeclaringType(), LogTag.class); } String LOG_PRE = logTag.prefix(); String s = proceedingJoinPoint.getSignature().toString(); log.info("{} START PROCESSING: {}", LOG_PRE,s); // 方法入?yún)? Object[] args = proceedingJoinPoint.getArgs(); try { log.info("{} method[{}] request:{}",LOG_PRE,method.getName(), logTag.printToJson() ? objectMapper.writeValueAsString(args) : Arrays.toString(args)); // 執(zhí)行方法 Object result = proceedingJoinPoint.proceed(); Class returnType = signature.getReturnType(); if(returnType == Response.class || returnType.getGenericSuperclass() == Response.class){ ((Response<?>) result).setRequestId(traceId); } log.info("{} method[{}] response:{}",LOG_PRE,method.getName(),logTag.printToJson() ? objectMapper.writeValueAsString(result) : result); return result; } catch (Throwable e){ log.info("{} method[{}] 執(zhí)行異常",LOG_PRE,method.getName(),e); return exceptionHandler.apply(e); }finally { // 方法執(zhí)行時(shí)間 long executionTime = System.currentTimeMillis() - start; log.info("{} END PROCESSING,cost:{} ms", LOG_PRE,executionTime); MDC.remove(REQUEST_TRACE_ID); } } }
4. 配置自動(dòng)裝載
在resource目錄下,新建META-INF文件夾,文件夾中新建文件spring.factories
,文件內(nèi)容為:
org.springframework.boot.autoconfigure.EnableAutoConfiguration =com.xxx.log.LogAutoConfiguration
效果展示
到此這篇關(guān)于基于Spring AOP實(shí)現(xiàn)日志自動(dòng)打印功能的文章就介紹到這了,更多相關(guān)Spring AOP日志自動(dòng)打印內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springboot整合 beatlsql的實(shí)例代碼
這篇文章主要介紹了springboot整合 beatlsql的實(shí)例代碼,BeetSql是一個(gè)全功能DAO工具,同時(shí)具有hibernate 優(yōu)點(diǎn) & Mybatis優(yōu)點(diǎn)功能,有興趣的可以了解一下2017-05-05IntelliJ?IDEA教程之clean或者install?Maven項(xiàng)目的操作方法
這篇文章主要介紹了IntelliJ?IDEA教程之clean或者install?Maven項(xiàng)目的操作方法,本文分步驟給大家介紹兩種方式講解如何調(diào)試出窗口,需要的朋友可以參考下2023-04-04MyBatisPlus批量添加的優(yōu)化與報(bào)錯(cuò)解決
MybatisPlus是一個(gè)高效的java持久層框架,它在Mybatis的基礎(chǔ)上增加了一些便捷的功能,提供了更加易用的API,可以大幅度提高開發(fā)效率,這篇文章主要給大家介紹了關(guān)于MyBatisPlus批量添加的優(yōu)化與報(bào)錯(cuò)解決的相關(guān)資料,需要的朋友可以參考下2023-05-05Java FTPClient連接池的實(shí)現(xiàn)
這篇文章主要介紹了Java FTPClient連接池的實(shí)現(xiàn),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-06-06