寫在前面
通過本文將了解到什么是MDC、MDC應(yīng)用中存在的問題、如何解決存在的問題
基于 Spring Boot + MyBatis Plus + Vue & Element 實(shí)現(xiàn)的后臺管理系統(tǒng) + 用戶小程序,支持 RBAC 動態(tài)權(quán)限、多租戶、數(shù)據(jù)權(quán)限、工作流、三方登錄、支付、短信、商城等功能
MDC介紹
簡介:
MDC(Mapped Diagnostic Context,映射調(diào)試上下文)是 log4j 、logback及l(fā)og4j2 提供的一種方便在多線程條件下記錄日志的功能。MDC 可以看成是一個(gè)與當(dāng)前線程綁定的哈希表 ,可以往其中添加鍵值對。MDC 中包含的內(nèi)容可以被同一線程中執(zhí)行的代碼所訪問 。
當(dāng)前線程的子線程會繼承其父線程中的 MDC 的內(nèi)容。當(dāng)需要記錄日志時(shí),只需要從 MDC 中獲取所需的信息即可。MDC 的內(nèi)容則由程序在適當(dāng)?shù)臅r(shí)候保存進(jìn)去。對于一個(gè) 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)
暫時(shí)只能想到這一點(diǎn)
基于 Spring Cloud Alibaba + Gateway + Nacos + RocketMQ + Vue & Element 實(shí)現(xiàn)的后臺管理系統(tǒng) + 用戶小程序,支持 RBAC 動態(tài)權(quán)限、多租戶、數(shù)據(jù)權(quán)限、工作流、三方登錄、支付、短信、商城等功能
MDC使用
添加攔截器
publicclassLogInterceptorimplementsHandlerInterceptor{
@Override
publicbooleanpreHandle(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler)throwsException{
//如果有上層調(diào)用就用上層的ID
StringtraceId=request.getHeader(Constants.TRACE_ID);
if(traceId==null){
traceId=TraceIdUtil.getTraceId();
}
MDC.put(Constants.TRACE_ID,traceId);
returntrue;
}
@Override
publicvoidpostHandle(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler,ModelAndViewmodelAndView)
throwsException{
}
@Override
publicvoidafterCompletion(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler,Exceptionex)
throwsException{
//調(diào)用結(jié)束后刪除
MDC.remove(Constants.TRACE_ID);
}
}
修改日志格式
[TRACEID:%X{traceId}]%d{HHss.SSS}%-5level%class{-1}.%M()/%L-%msg%xEx%n
重點(diǎn)是%X{traceId},traceId和MDC中的鍵名稱一致
簡單使用就這么容易,但是在有些情況下traceId將獲取不到
MDC 存在的問題
子線程中打印日志丟失traceId
HTTP調(diào)用丟失traceId
......丟失traceId的情況,來一個(gè)再解決一個(gè),絕不提前優(yōu)化
解決MDC存在的問題
子線程日志打印丟失traceId
子線程在打印日志的過程中traceId將丟失,解決方式為重寫線程池,對于直接new創(chuàng)建線程的情況不考略【實(shí)際應(yīng)用中應(yīng)該避免這種用法】,重寫線程池?zé)o非是對任務(wù)進(jìn)行一次封裝
線程池封裝類:ThreadPoolExecutorMdcWrapper.java
publicclassThreadPoolExecutorMdcWrapperextendsThreadPoolExecutor{
publicThreadPoolExecutorMdcWrapper(intcorePoolSize,intmaximumPoolSize,longkeepAliveTime,TimeUnitunit,
BlockingQueueworkQueue){
super(corePoolSize,maximumPoolSize,keepAliveTime,unit,workQueue);
}
publicThreadPoolExecutorMdcWrapper(intcorePoolSize,intmaximumPoolSize,longkeepAliveTime,TimeUnitunit,
BlockingQueueworkQueue,ThreadFactorythreadFactory){
super(corePoolSize,maximumPoolSize,keepAliveTime,unit,workQueue,threadFactory);
}
publicThreadPoolExecutorMdcWrapper(intcorePoolSize,intmaximumPoolSize,longkeepAliveTime,TimeUnitunit,
BlockingQueueworkQueue,RejectedExecutionHandlerhandler){
super(corePoolSize,maximumPoolSize,keepAliveTime,unit,workQueue,handler);
}
publicThreadPoolExecutorMdcWrapper(intcorePoolSize,intmaximumPoolSize,longkeepAliveTime,TimeUnitunit,
BlockingQueueworkQueue,ThreadFactorythreadFactory,
RejectedExecutionHandlerhandler){
super(corePoolSize,maximumPoolSize,keepAliveTime,unit,workQueue,threadFactory,handler);
}
@Override
publicvoidexecute(Runnabletask){
super.execute(ThreadMdcUtil.wrap(task,MDC.getCopyOfContextMap()));
}
@Override
publicFuturesubmit(Runnabletask,Tresult){
returnsuper.submit(ThreadMdcUtil.wrap(task,MDC.getCopyOfContextMap()),result);
}
@Override
publicFuturesubmit(Callabletask){
returnsuper.submit(ThreadMdcUtil.wrap(task,MDC.getCopyOfContextMap()));
}
@Override
publicFuture>submit(Runnabletask){
returnsuper.submit(ThreadMdcUtil.wrap(task,MDC.getCopyOfContextMap()));
}
}
說明:
繼承ThreadPoolExecutor類,重新執(zhí)行任務(wù)的方法
通過ThreadMdcUtil對任務(wù)進(jìn)行一次包裝
線程traceId封裝工具類:ThreadMdcUtil.java
publicclassThreadMdcUtil{
publicstaticvoidsetTraceIdIfAbsent(){
if(MDC.get(Constants.TRACE_ID)==null){
MDC.put(Constants.TRACE_ID,TraceIdUtil.getTraceId());
}
}
publicstaticCallablewrap(finalCallablecallable,finalMapcontext){
return()->{
if(context==null){
MDC.clear();
}else{
MDC.setContextMap(context);
}
setTraceIdIfAbsent();
try{
returncallable.call();
}finally{
MDC.clear();
}
};
}
publicstaticRunnablewrap(finalRunnablerunnable,finalMapcontext){
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方法
代碼等同于以下寫法,會更直觀
publicstaticRunnablewrap(finalRunnablerunnable,finalMapcontext){ returnnewRunnable(){ @Override publicvoidrun(){ 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ù)接口時(shí)traceId將丟失,需要對HTTP調(diào)用工具進(jìn)行改造,在發(fā)送時(shí)在request header中添加traceId,在下層被調(diào)用方添加攔截器獲取header中的traceId添加到MDC中
HTTP調(diào)用有多種方式,比較常見的有HttpClient、OKHttp、RestTemplate,所以只給出這幾種HTTP調(diào)用的解決方式
HttpClient:
實(shí)現(xiàn)HttpClient攔截器
publicclassHttpClientTraceIdInterceptorimplementsHttpRequestInterceptor{
@Override
publicvoidprocess(HttpRequesthttpRequest,HttpContexthttpContext)throwsHttpException,IOException{
StringtraceId=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添加攔截器
privatestaticCloseableHttpClienthttpClient=HttpClientBuilder.create() .addInterceptorFirst(newHttpClientTraceIdInterceptor()) .build();
通過addInterceptorFirst方法為HttpClient添加攔截器
OKHttp:
實(shí)現(xiàn)OKHttp攔截器
publicclassOkHttpTraceIdInterceptorimplementsInterceptor{
@Override
publicResponseintercept(Chainchain)throwsIOException{
StringtraceId=MDC.get(Constants.TRACE_ID);
Requestrequest=null;
if(traceId!=null){
//添加請求體
request=chain.request().newBuilder().addHeader(Constants.TRACE_ID,traceId).build();
}
ResponseoriginResponse=chain.proceed(request);
returnoriginResponse;
}
}
實(shí)現(xiàn)Interceptor攔截器,重寫interceptor方法,實(shí)現(xiàn)邏輯和HttpClient差不多,如果能夠獲取到當(dāng)前線程的traceId則向下透傳
為OkHttp添加攔截器
privatestaticOkHttpClientclient=newOkHttpClient.Builder() .addNetworkInterceptor(newOkHttpTraceIdInterceptor()) .build();
調(diào)用addNetworkInterceptor方法添加攔截器
RestTemplate:
實(shí)現(xiàn)RestTemplate攔截器
publicclassRestTemplateTraceIdInterceptorimplementsClientHttpRequestInterceptor{
@Override
publicClientHttpResponseintercept(HttpRequesthttpRequest,byte[]bytes,ClientHttpRequestExecutionclientHttpRequestExecution)throwsIOException{
StringtraceId=MDC.get(Constants.TRACE_ID);
if(traceId!=null){
httpRequest.getHeaders().add(Constants.TRACE_ID,traceId);
}
returnclientHttpRequestExecution.execute(httpRequest,bytes);
}
}
實(shí)現(xiàn)ClientHttpRequestInterceptor接口,并重寫intercept方法,其余邏輯都是一樣的不重復(fù)說明
為RestTemplate添加攔截器
restTemplate.setInterceptors(Arrays.asList(newRestTemplateTraceIdInterceptor()));
調(diào)用setInterceptors方法添加攔截器
第三方服務(wù)攔截器:
HTTP調(diào)用第三方服務(wù)接口全流程traceId需要第三方服務(wù)配合,第三方服務(wù)需要添加攔截器拿到request header中的traceId并添加到MDC中
publicclassLogInterceptorimplementsHandlerInterceptor{
@Override
publicbooleanpreHandle(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler)throwsException{
//如果有上層調(diào)用就用上層的ID
StringtraceId=request.getHeader(Constants.TRACE_ID);
if(traceId==null){
traceId=TraceIdUtils.getTraceId();
}
MDC.put("traceId",traceId);
returntrue;
}
@Override
publicvoidpostHandle(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler,ModelAndViewmodelAndView)
throwsException{
}
@Override
publicvoidafterCompletion(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler,Exceptionex)
throwsException{
MDC.remove(Constants.TRACE_ID);
}
}
說明:
先從request header中獲取traceId
從request header中獲取不到traceId則說明不是第三方調(diào)用,直接生成一個(gè)新的traceId
將生成的traceId存入MDC中
除了需要添加攔截器之外,還需要在日志格式中添加traceId的打印,如下:
[TRACEID:%X{traceId}]%d{HHss.SSS}%-5level%class{-1}.%M()/%L-%msg%xEx%n
需要添加%X{traceId}
審核編輯:湯梓紅
-
spring
+關(guān)注
關(guān)注
0文章
341瀏覽量
15762 -
日志
+關(guān)注
關(guān)注
0文章
145瀏覽量
11025 -
Boot
+關(guān)注
關(guān)注
0文章
154瀏覽量
37466 -
線程
+關(guān)注
關(guān)注
0文章
508瀏覽量
20748 -
SpringBoot
+關(guān)注
關(guān)注
0文章
177瀏覽量
624
原文標(biāo)題:SpringBoot + MDC 實(shí)現(xiàn)全鏈路調(diào)用日志跟蹤
文章出處:【微信號:芋道源碼,微信公眾號:芋道源碼】歡迎添加關(guān)注!文章轉(zhuǎn)載請注明出處。
發(fā)布評論請先 登錄
2017雙11技術(shù)揭秘—雙十一海量數(shù)據(jù)下EagleEye的使命和挑戰(zhàn)
全鏈路壓測一招搞定,阿里云性能測試鉑金版發(fā)布
API信息全掌控,方便你的日志管理——阿里云推出API網(wǎng)關(guān)打通日志服務(wù)
基于分布式調(diào)用鏈監(jiān)控技術(shù)的全息排查功能
2021 OPPO開發(fā)者大會:全鏈路運(yùn)營
MDC300F UART 下發(fā)配置 日志調(diào)試
手動實(shí)現(xiàn)SpringBoot日志鏈路追蹤
微服務(wù)循環(huán)依賴調(diào)用引發(fā)的血案
鏈路追蹤系統(tǒng)SkyWalking的原理
SpringBoot+Vue實(shí)現(xiàn)網(wǎng)頁版人臉登錄、人臉識別案例解析
SpringBoot+Vue實(shí)現(xiàn)網(wǎng)頁版人臉登錄、人臉識別
Spring Boot如何實(shí)現(xiàn)日志鏈路追蹤

SpringBoot+MDC實(shí)現(xiàn)全鏈路調(diào)用日志跟蹤
評論