先看一張圖:
有同學(xué)問:日志中[]中類似uuid的這個traceId是怎么實(shí)現(xiàn)的,這邊文章就介紹下如何在springboot工程下用MDC實(shí)現(xiàn)日志文件中打印traceId。
1. 為什么需要這個traceId
我們在定位問題的時候需要去日志中查找對應(yīng)的位置,當(dāng)我們一個接口的請求同用唯一的一個traceId,那我們只需要知道這個traceId,使用 grep ‘traceId' xxx.log 語句就能準(zhǔn)確的定位到目標(biāo)日志。在這邊文章會介紹如何去設(shè)置這個traceId,而后如何在接口返回這個traceId。
1
2
3
4
5
6
7
8
|
#接口返回: { "code": "0", "dealStatus": "1", "TRACE_ID": "a10e6e8d-9953-4de9-b145-32eee6aa5562" } #查詢?nèi)罩?/code> grep 'a10e6e8d-9953-4de9-b145-32eee6aa5562' xxxx.log |
2.通過MDC設(shè)置traceId
筆者目前遇到的項(xiàng)目,可以有三種情況去設(shè)置traceId。先簡單的介紹MDC
1
2
3
4
5
6
7
8
|
#MDC定義 Mapped Diagnostic Context,即:映射診斷環(huán)境。 MDC是 log4j 和 logback 提供的一種方便在多線程條件下記錄日志的功能。 MDC 可以看成是一個與當(dāng)前線程綁定的哈希表,可以往其中添加鍵值對。 #MDC的使用方法 向MDC中設(shè)置值:MDC.put(key, value); 從MDC中取值:MDC.get(key); 將MDC中內(nèi)容打印到日志中:%X{key} |
2.1 使用filter過濾器設(shè)置traceId
新建一個過濾器,實(shí)現(xiàn)Filter,重寫init,doFilter,destroy方法,設(shè)置traceId放在doFilter中,在destroy中調(diào)用MDC.clear()方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
@Slf4j @WebFilter (filterName = "traceIdFilter" ,urlPatterns = "/*" ) public class traceIdFilter implements Filter { /** * 日志跟蹤標(biāo)識 */ 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這部分的日志就不會帶上traceId,因此我們需要把代碼放在jwtFilter中,如圖:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
/** * token過濾器 驗(yàn)證token有效性 * * @author china */ @Component public class JwtAuthenticationTokenFilter extends OncePerRequestFilter { @Autowired private TokenService tokenService; /** * 日志跟蹤標(biāo)識 */ 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
定義一個攔截器,重寫preHandle方法,在方法中通過MDC設(shè)置traceId
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
/** * 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{***}]是一個模板,中間屬性名是我們使用MDC put進(jìn)去的。
1
2
3
4
|
#之前 < 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
異步方法會開啟一個新線程,我們想要是異步方法和主線程共用同一個traceId,首先先新建一個任務(wù)適配器MdcTaskDecorator,如圖:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
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è)置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
/** * 線程池配置 * * @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開啟異步方法即可
1
2
|
@Async ( "threadPoolTaskExecutor" ) void testSyncMethod(); |
5.在接口放回中,增加traceId返回
在筆者項(xiàng)目中,接口返回都使用了一個叫AjaxResult自定義類來包裝,所以只需要把這個類的構(gòu)造器中增加traceId返回即可,相對簡單。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
/** * 日志跟蹤標(biāo)識 */ private static final String TRACE_ID = "TRACE_ID" ; /** * 初始化一個新創(chuàng)建的 AjaxResult 對象,使其表示一個空消息。 */ public AjaxResult() { super .put(TRACE_ID, MDC.get(TRACE_ID)); } /** * 初始化一個新創(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)); } /** * 初始化一個新創(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)注服務(wù)器之家其它相關(guān)文章!
原文鏈接:https://blog.csdn.net/weixin_38117908/article/details/107285978