免费视频淫片aa毛片_日韩高清在线亚洲专区vr_日韩大片免费观看视频播放_亚洲欧美国产精品完整版

打開APP
userphoto
未登錄

開通VIP,暢享免費(fèi)電子書等14項(xiàng)超值服

開通VIP
Spring Boot + MDC 實(shí)現(xiàn)全鏈路調(diào)用日志跟蹤

寫在前面

通過本文將了解到什么是 MDC、MDC 應(yīng)用中存在的問題、如何解決存在的問題。

MDC 介紹


簡介

MDC(Mapped Diagnostic Context,映射調(diào)試上下文)是 log4j 、logback及l(fā)og4j2 提供的一種方便在多線程條件下記錄日志的功能。MDC 可以看成是一個與當(dāng)前線程綁定的哈希表,可以往其中添加鍵值對。MDC 中包含的內(nèi)容可以被同一線程中執(zhí)行的代碼所訪問。當(dāng)前線程的子線程會繼承其父線程中的 MDC 的內(nèi)容。當(dāng)需要記錄日志時,只需要從 MDC 中獲取所需的信息即可。MDC 的內(nèi)容則由程序在適當(dāng)?shù)臅r候保存進(jìn)去。對于一個 Web 應(yīng)用來說,通常是在請求被處理的最開始保存這些數(shù)據(jù)。

API 說明

  • clear() => 移除所有 MDC

  • get (String key) => 獲取當(dāng)前線程 MDC 中指定 key 的值

  • getContext() => 獲取當(dāng)前線程 MDC 的 MDC

  • put(String key, Object o) => 往當(dāng)前線程的 MDC 中存入指定的鍵值對

  • remove(String key) => 刪除當(dāng)前線程 MDC 中指定的鍵值對


優(yōu)點(diǎn)

代碼簡潔,日志風(fēng)格統(tǒng)一,不需要在 log 打印中手動拼寫 traceId,即

LOGGER.info("traceId:{} ", traceId)

暫時只能想到這一點(diǎn)。

MDC 使用


添加攔截器

public class LogInterceptor implements HandlerInterceptor {    @Override    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {        //如果有上層調(diào)用就用上層的ID        String traceId = request.getHeader(Constants.TRACE_ID);        if (traceId == null) {            traceId = TraceIdUtil.getTraceId();        }
MDC.put(Constants.TRACE_ID, traceId); return true; }
@Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { }
@Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { //調(diào)用結(jié)束后刪除 MDC.remove(Constants.TRACE_ID); }}
修改日志格式
<property name="pattern">[TRACEID:%X{traceId}] %d{HH:mm:ss.SSS} %-5level %class{-1}.%M()/%L - %msg%xEx%n</property>

重點(diǎn)是 %X{traceId},traceId 和 MDC 中的鍵名稱一致。


簡單使用就這么容易,但是在有些情況下 traceId 將獲取不到。


MDC 存在的問題


  • 子線程中打印日志丟失 traceId

  • HTTP 調(diào)用丟失 traceId

......丟失traceId的情況,來一個再解決一個,絕不提前優(yōu)化


解決 MDC 存在的問題


子線程日志打印丟失 traceId

子線程在打印日志的過程中 traceId 將丟失,解決方式為重寫線程池。對于直接 new 創(chuàng)建線程的情況不考略,實(shí)際應(yīng)用中應(yīng)該避免這種用法。重寫線程池?zé)o非是對任務(wù)進(jìn)行一次封裝。

線程池封裝類:ThreadPoolExecutorMdcWrapper.java

public class ThreadPoolExecutorMdcWrapper extends ThreadPoolExecutor {    public ThreadPoolExecutorMdcWrapper(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,                                        BlockingQueue<Runnable> workQueue) {        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);    }
public ThreadPoolExecutorMdcWrapper(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory); }
public ThreadPoolExecutorMdcWrapper(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler); }
public ThreadPoolExecutorMdcWrapper(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler); }
@Override public void execute(Runnable task) { super.execute(ThreadMdcUtil.wrap(task, MDC.getCopyOfContextMap())); }
@Override public <T> Future<T> submit(Runnable task, T result) { return super.submit(ThreadMdcUtil.wrap(task, MDC.getCopyOfContextMap()), result); }
@Override public <T> Future<T> submit(Callable<T> task) { return super.submit(ThreadMdcUtil.wrap(task, MDC.getCopyOfContextMap())); }
@Override public Future<?> submit(Runnable task) { return super.submit(ThreadMdcUtil.wrap(task, MDC.getCopyOfContextMap())); }}

說明:

    • 繼承 ThreadPoolExecutor 類,重新執(zhí)行任務(wù)的方法;

    • 通過 ThreadMdcUtil 對任務(wù)進(jìn)行一次包裝

線程 traceId 封裝工具類:ThreadMdcUtil.java

public class ThreadMdcUtil {    public static void setTraceIdIfAbsent() {        if (MDC.get(Constants.TRACE_ID) == null) {            MDC.put(Constants.TRACE_ID, TraceIdUtil.getTraceId());        }    }
public static <T> Callable<T> wrap(final Callable<T> callable, final Map<String, String> context) { return () -> { if (context == null) { MDC.clear(); } else { MDC.setContextMap(context); } setTraceIdIfAbsent(); try { return callable.call(); } finally { MDC.clear(); } }; }
public static Runnable wrap(final Runnable runnable, final Map<String, String> context) { return () -> { if (context == null) { MDC.clear(); } else { MDC.setContextMap(context); } setTraceIdIfAbsent(); try { runnable.run(); } finally { MDC.clear(); } }; }}

說明(以封裝Runnable為例):

  • 判斷當(dāng)前線程對應(yīng) MDC 的 Map 是否存在,存在則設(shè)置;

  • 設(shè)置 MDC 中的 traceId 值,不存在則新生成,針對不是子線程的情況,如果是子線程,MDC 中 traceId 不為 null;

  • 執(zhí)行 run 方法。

代碼等同于以下寫法,會更直觀。

public static Runnable wrap(final Runnable runnable, final Map<String, String> context) {    return new Runnable() {        @Override        public void run() {            if (context == null) {                MDC.clear();            } else {                MDC.setContextMap(context);            }            setTraceIdIfAbsent();            try {                runnable.run();            } finally {                MDC.clear();            }        }    };}

重新返回的是包裝后的 Runnable,在該任務(wù)執(zhí)行之前 runnable.run() 先將主線程的 Map 設(shè)置到當(dāng)前線程中(即 MDC.setContextMap(context)),這樣子線程和主線程 MDC 對應(yīng)的 Map 就是一樣的了。

    • 判斷當(dāng)前線程對應(yīng) MDC 的 Map 是否存在,存在則設(shè)置;

    • 設(shè)置 MDC 中的 traceId 值,不存在則新生成。針對不是子線程的情況,如果是子線程,MDC 中 traceId 不為 null;

    • 執(zhí)行 run 方法。


HTTP 調(diào)用丟失 traceId

在使用 HTTP 調(diào)用第三方服務(wù)接口時 traceId 將丟失,需要對 HTTP 調(diào)用工具進(jìn)行改造。發(fā)送時,在 request header 中添加 traceId,在下層被調(diào)用方添加攔截器獲取 header 中的 traceId 添加到 MDC 中。

HTTP 調(diào)用有多種方式,比較常見的有 HttpClient、OKHttp、RestTemplate,所以只給出這幾種 HTTP 調(diào)用的解決方式。

HttpClient

實(shí)現(xiàn) HttpClient 攔截器

public class HttpClientTraceIdInterceptor implements HttpRequestInterceptor {    @Override    public void process(HttpRequest httpRequest, HttpContext httpContext) throws HttpException, IOException {        String traceId = MDC.get(Constants.TRACE_ID);        //當(dāng)前線程調(diào)用中有traceId,則將該traceId進(jìn)行透傳        if (traceId != null) {            //添加請求體            httpRequest.addHeader(Constants.TRACE_ID, traceId);        }    }}

實(shí)現(xiàn) HttpRequestInterceptor 接口并重寫 process 方法。

如果調(diào)用線程中含有 traceId,則需要將獲取到的 traceId 通過 request 中的 header 向下透傳下去。

為 HttpClient 添加攔截器

private static CloseableHttpClient httpClient = HttpClientBuilder.create()            .addInterceptorFirst(new HttpClientTraceIdInterceptor())            .build();

通過 addInterceptorFirst 方法為 HttpClient 添加攔截器。

OKHttp

實(shí)現(xiàn) OKHttp 攔截器

public class OkHttpTraceIdInterceptor implements Interceptor {    @Override    public Response intercept(Chain chain) throws IOException {        String traceId = MDC.get(Constants.TRACE_ID);        Request request = null;        if (traceId != null) {            //添加請求體            request = chain.request().newBuilder().addHeader(Constants.TRACE_ID, traceId).build();        }        Response originResponse = chain.proceed(request);
return originResponse; }}

實(shí)現(xiàn) Interceptor 攔截器,重寫 interceptor 方法。實(shí)現(xiàn)邏輯和 HttpClient 差不多,如果能夠獲取到當(dāng)前線程的 traceId 則向下透傳。

為 OkHttp 添加攔截器

private static OkHttpClient client = new OkHttpClient.Builder()          .addNetworkInterceptor(new OkHttpTraceIdInterceptor())          .build();

調(diào)用 addNetworkInterceptor 方法添加攔截器。

RestTemplate

實(shí)現(xiàn) RestTemplate 攔截器

public class RestTemplateTraceIdInterceptor implements ClientHttpRequestInterceptor {    @Override    public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {        String traceId = MDC.get(Constants.TRACE_ID);        if (traceId != null) {            httpRequest.getHeaders().add(Constants.TRACE_ID, traceId);        }
return clientHttpRequestExecution.execute(httpRequest, bytes); }}

實(shí)現(xiàn) ClientHttpRequestInterceptor 接口,并重寫 intercept 方法,其余邏輯都是一樣的,這里不做重復(fù)說明。

為 RestTemplate 添加攔截器

restTemplate.setInterceptors(Arrays.asList(new RestTemplateTraceIdInterceptor()));

調(diào)用 setInterceptors 方法添加攔截器。

第三方服務(wù)攔截器

HTTP 調(diào)用第三方服務(wù)接口全流程 traceId 需要第三方服務(wù)配合,第三方服務(wù)需要添加攔截器拿到 request header 中的 traceId 并添加到 MDC 中。

public class LogInterceptor implements HandlerInterceptor {    @Override    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {        //如果有上層調(diào)用就用上層的ID        String traceId = request.getHeader(Constants.TRACE_ID);        if (traceId == null) {            traceId = TraceIdUtils.getTraceId();        }
MDC.put("traceId", traceId); return true; }
@Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { }
@Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { MDC.remove(Constants.TRACE_ID); }}

說明:

  • 先從 request header 中獲取t raceId;

  • 從 request header 中獲取不到 traceId 則說明不是第三方調(diào)用,直接生成一個新的 traceId;

  • 將生成的 traceId 存入 MDC 中。

除了需要添加攔截器之外,還需要在日志格式中添加 traceId 的打印,如下:

 <property name="pattern">[TRACEID:%X{traceId}] %d{HH:mm:ss.SSS} %-5level %class{-1}.%M()/%L - %msg%xEx%n</property>

需要添加 %X{traceId}。

最后附:項(xiàng)目代碼,歡迎 fork 與 star,漲點(diǎn)小星星,卑微乞討。

https://github.com/TiantianUpup/springboot-log/tree/master/springboot-trace

轉(zhuǎn)自:何甜甜在嗎,



END

本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點(diǎn)擊舉報(bào)。
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
誠之和:基于Spring Boot + Dubbo的全鏈路日志追蹤是怎樣的
從 1.5 開始搭建一個微服務(wù)框架——鏈路追蹤 traceId
Handler用法及解析
一個JDK線程池BUG引發(fā)的GC機(jī)制思考
「DUBBO系列」線程池策略詳解
【十二】springboot整合線程池解決高并發(fā)(超詳細(xì),保你理解)
更多類似文章 >>
生活服務(wù)
分享 收藏 導(dǎo)長圖 關(guān)注 下載文章
綁定賬號成功
后續(xù)可登錄賬號暢享VIP特權(quán)!
如果VIP功能使用有故障,
可點(diǎn)擊這里聯(lián)系客服!

聯(lián)系客服