Springboot+MDC+traceId日志中打印唯一traceId
先看一張圖:
有同學(xué)問:日志中[]中類似uuid的這個(gè)traceId是怎么實(shí)現(xiàn)的,這邊文章就介紹下如何在springboot工程下用MDC實(shí)現(xiàn)日志文件中打印traceId。
1. 為什么需要這個(gè)traceId
我們在定位問題的時(shí)候需要去日志中查找對應(yīng)的位置,當(dāng)我們一個(gè)接口的請求同用唯一的一個(gè)traceId,那我們只需要知道這個(gè)traceId,使用 grep ‘traceId' xxx.log 語句就能準(zhǔn)確的定位到目標(biāo)日志。在這邊文章會(huì)介紹如何去設(shè)置這個(gè)traceId,而后如何在接口返回這個(gè)traceId。
#接口返回: { "code": "0", "dealStatus": "1", "TRACE_ID": "a10e6e8d-9953-4de9-b145-32eee6aa5562" } #查詢?nèi)罩? grep 'a10e6e8d-9953-4de9-b145-32eee6aa5562' xxxx.log
2.通過MDC設(shè)置traceId
筆者目前遇到的項(xiàng)目,可以有三種情況去設(shè)置traceId。先簡單的介紹MDC
#MDC定義 Mapped Diagnostic Context,即:映射診斷環(huán)境。 MDC是 log4j 和 logback 提供的一種方便在多線程條件下記錄日志的功能。 MDC 可以看成是一個(gè)與當(dāng)前線程綁定的哈希表,可以往其中添加鍵值對。 #MDC的使用方法 向MDC中設(shè)置值:MDC.put(key, value); 從MDC中取值:MDC.get(key); 將MDC中內(nèi)容打印到日志中:%X{key}
2.1 使用filter過濾器設(shè)置traceId
新建一個(gè)過濾器,實(shí)現(xiàn)Filter,重寫init,doFilter,destroy方法,設(shè)置traceId放在doFilter中,在destroy中調(diào)用MDC.clear()方法。
@Slf4j @WebFilter(filterName = "traceIdFilter",urlPatterns = "/*") public class traceIdFilter implements Filter { /** * 日志跟蹤標(biāo)識(shí) */ private static final String TRACE_ID = "TRACE_ID"; @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { MDC.put(TRACE_ID, UUID.randomUUID().toString()); filterChain.doFilter(request, servletResponse); } @Override public void destroy() { MDC.clear(); } }
2.2 使用JWT token過濾器的項(xiàng)目
springboot項(xiàng)目經(jīng)常使用spring security+jwt來做權(quán)限限制,在這種情況下,我們通過新建filter過濾器來設(shè)置traceId,那么在驗(yàn)證token這部分的日志就不會(huì)帶上traceId,因此我們需要把代碼放在jwtFilter中,如圖:
/** * token過濾器 驗(yàn)證token有效性 * * @author china */ @Component public class JwtAuthenticationTokenFilter extends OncePerRequestFilter { @Autowired private TokenService tokenService; /** * 日志跟蹤標(biāo)識(shí) */ private static final String TRACE_ID = "TRACE_ID"; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { MDC.put(TRACE_ID, UUID.randomUUID().toString()); LoginUser loginUser = tokenService.getLoginUser(request); if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication())) { tokenService.verifyToken(loginUser); UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities()); authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(authenticationToken); } chain.doFilter(request, response); } @Override public void destroy() { MDC.clear(); } }
2.3 使用Interceptor攔截器設(shè)置traceId
定義一個(gè)攔截器,重寫preHandle方法,在方法中通過MDC設(shè)置traceId
/** * MDC設(shè)置traceId攔截器 * * @author china */ @Component public abstract class TraceIdInterceptor extends HandlerInterceptorAdapter { private static final String UNIQUE_ID = "TRACE_ID"; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { MDC.put(UNIQUE_ID, UUID.randomUUID().toString()); return true; } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception { MDC.clear(); } }
3.logback.xml中配置traceId
與之前的相比只是添加了[%X{TRACE_ID}], [%X{***}]是一個(gè)模板,中間屬性名是我們使用MDC put進(jìn)去的。
#之前 <property name="log.pattern" value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{20} - [%method,%line] - %msg%n" /> #增加traceId后 <property name="log.pattern" value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{20} - [%method,%line] - [%X{TRACE_ID}] - %msg%n" />
4.補(bǔ)充異步方法帶入上下文的traceId
異步方法會(huì)開啟一個(gè)新線程,我們想要是異步方法和主線程共用同一個(gè)traceId,首先先新建一個(gè)任務(wù)適配器MdcTaskDecorator,如圖:
public class MdcTaskDecorator implements TaskDecorator /** * 使異步線程池獲得主線程的上下文 * @param runnable * @return */ @Override public Runnable decorate(Runnable runnable) { Map<String,String> map = MDC.getCopyOfContextMap(); return () -> { try{ MDC.setContextMap(map); runnable.run(); } finally { MDC.clear(); } }; } }
然后,在線程池配置中增加executor.setTaskDecorator(new MdcTaskDecorator())的設(shè)置
/** * 線程池配置 * * @author china **/ @EnableAsync @Configuration public class ThreadPoolConfig { private int corePoolSize = 50; private int maxPoolSize = 200; private int queueCapacity = 1000; private int keepAliveSeconds = 300; @Bean(name = "threadPoolTaskExecutor") public ThreadPoolTaskExecutor threadPoolTaskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setMaxPoolSize(maxPoolSize); executor.setCorePoolSize(corePoolSize); executor.setQueueCapacity(queueCapacity); executor.setKeepAliveSeconds(keepAliveSeconds); executor.setTaskDecorator(new MdcTaskDecorator()); // 線程池對拒絕任務(wù)(無線程可用)的處理策略 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); return executor; } }
最后,在業(yè)務(wù)代碼上使用@Async開啟異步方法即可
@Async("threadPoolTaskExecutor") void testSyncMethod();
5.在接口放回中,增加traceId返回
在筆者項(xiàng)目中,接口返回都使用了一個(gè)叫AjaxResult自定義類來包裝,所以只需要把這個(gè)類的構(gòu)造器中增加traceId返回即可,相對簡單。
/** * 日志跟蹤標(biāo)識(shí) */ private static final String TRACE_ID = "TRACE_ID"; /** * 初始化一個(gè)新創(chuàng)建的 AjaxResult 對象,使其表示一個(gè)空消息。 */ public AjaxResult() { super.put(TRACE_ID, MDC.get(TRACE_ID)); } /** * 初始化一個(gè)新創(chuàng)建的 AjaxResult 對象 * * @param code 狀態(tài)碼 * @param msg 返回內(nèi)容 */ public AjaxResult(int code, String msg) { super.put(CODE_TAG, code); super.put(MSG_TAG, msg); super.put(TRACE_ID, MDC.get(TRACE_ID)); } /** * 初始化一個(gè)新創(chuàng)建的 AjaxResult 對象 * * @param code 狀態(tài)碼 * @param msg 返回內(nèi)容 * @param data 數(shù)據(jù)對象 */ public AjaxResult(int code, String msg, Object data) { super.put(CODE_TAG, code); super.put(MSG_TAG, msg); super.put(TRACE_ID, MDC.get(TRACE_ID)); if (StringUtils.isNotNull(data)) { super.put(DATA_TAG, data); } }
以上就是Springboot+MDC+traceId日志中打印唯一traceId的詳細(xì)內(nèi)容,更多關(guān)于Springboot 打印唯一traceId的資料請關(guān)注腳本之家其它相關(guān)文章!
- Springboot MDC+logback實(shí)現(xiàn)日志追蹤的方法
- SpringBoot利用MDC機(jī)制過濾單次請求的所有日志
- SpringBoot項(xiàng)目使用slf4j的MDC日志打點(diǎn)功能(最新推薦)
- SpringBoot MDC全鏈路調(diào)用日志跟蹤實(shí)現(xiàn)詳解
- SpringBoot+MDC實(shí)現(xiàn)鏈路調(diào)用日志的方法
- SpringBoot 項(xiàng)目添加 MDC 日志鏈路追蹤的執(zhí)行流程
- SpringBoot項(xiàng)目使用MDC給日志增加唯一標(biāo)識(shí)的實(shí)現(xiàn)步驟
相關(guān)文章
SpringBoot Actuator監(jiān)控的項(xiàng)目實(shí)踐
本文主要結(jié)合 Spring Boot Actuator,跟大家一起分享微服務(wù)Spring Boot Actuator 的常見用法,方便我們在日常中對我們的微服務(wù)進(jìn)行監(jiān)控治理,感興趣的可以了解一下2024-01-01Java實(shí)現(xiàn)通過IP獲取IP歸屬地的方法(離線+在線)
我們都知道安全攻擊都是在某臺(tái)客戶機(jī)上執(zhí)行某些惡意操作致使服務(wù)端響應(yīng)異常崩潰亦或響應(yīng)數(shù)據(jù)被篡改,首先我想到的是對訪問的web端做一個(gè)IP的校驗(yàn),那么我們首先得知道客戶端的IP是多少,接下來此文重點(diǎn)介紹如何獲得,需要的朋友可以參考下2023-10-10feignclient?https?接口調(diào)用報(bào)證書錯(cuò)誤的解決方案
這篇文章主要介紹了feignclient?https?接口調(diào)用報(bào)證書錯(cuò)誤的解決方案,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03Windows安裝兩個(gè)或多個(gè)JDK并實(shí)現(xiàn)自由切換的方法
最近新接手一個(gè)項(xiàng)目,啟動(dòng)的時(shí)候,發(fā)現(xiàn)有些jar和現(xiàn)在正在使用的JDK版本不一致,一直啟動(dòng)有問題,想著就多裝一個(gè)JDK,由于為了保證java的運(yùn)行環(huán)境和編譯環(huán)境保持一致,就需要我們設(shè)置jdk的環(huán)境變量,所以本文給大家介紹了Windows安裝兩個(gè)或多個(gè)JDK并實(shí)現(xiàn)自由切換的方法2025-03-03微信公眾號(hào)支付(二)實(shí)現(xiàn)統(tǒng)一下單接口
本篇文章主要給大家介紹調(diào)用微信公眾支付的統(tǒng)一下單API,通過參數(shù)封裝為xml格式并發(fā)送到微信給的接口地址就可以獲得返回內(nèi)容,需要的朋友可以參考下本文2015-09-09