激情久久久_欧美视频区_成人av免费_不卡视频一二三区_欧美精品在欧美一区二区少妇_欧美一区二区三区的

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達(dá)式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務(wù)器之家 - 編程語言 - Java教程 - Springboot+MDC+traceId日志中打印唯一traceId

Springboot+MDC+traceId日志中打印唯一traceId

2022-02-21 13:19W3C_0101 Java教程

本文主要介紹了Springboot+MDC+traceId日志中打印唯一traceId,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下

先看一張圖:

Springboot+MDC+traceId日志中打印唯一traceId

有同學(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

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 国产精品毛片无码 | 羞羞视频免费网站含羞草 | 国产二三区 | 久久吊| 欧美日韩一 | 性色av一区二区三区在线播放亚… | 亚洲人片在线观看 | 亚洲人成网站免费播放 | 成人毛片网 | 国产视频在线免费观看 | 国产精品色综合 | 黄网站免费入口 | 少妇一级淫片免费放播放 | 欧美a在线播放 | 宅男视频在线观看免费 | 国产麻豆交换夫妇 | 黄色网址免费在线 | 在线中文字幕观看 | www中文在线| 国产午夜精品在线 | 亚洲婷婷日日综合婷婷噜噜噜 | 在线小视频国产 | 成人区精品一区二区婷婷 | 国产精品视频免费在线观看 | 黄色特级毛片 | 最新中文字幕日本 | 在线视频观看一区二区 | 欧美成年人视频在线观看 | 国产精品久久久久久影院8一贰佰 | 中文字幕综合在线观看 | 日本在线视频二区 | 色精品国产 | 中文字幕欧美视频 | 特黄一区二区三区 | 成人毛片网 | 中文字幕免费看 | 欧美大胆xxxx肉体摄影 | 亚洲一区二区三区高清视频 | 久久色在线 | 日本成人一二三区 | 性欧美xx |