MDC 簡介
MDC ( Mapped Diagnostic Contexts ),它是一個線程安全的存放診斷日志的容器昆著。
Logback設(shè)計(jì)的一個目標(biāo)之一是對分布式應(yīng)用系統(tǒng)的審計(jì)和調(diào)試本砰。在現(xiàn)在的分布式系統(tǒng)中坏瘩,需要同時處理很多的請求介牙。如何來很好的區(qū)分日志到底是那個請求輸出的呢银受?我們可以為每一個請求生一個logger圈膏,但是這樣子最產(chǎn)生大量的資源浪費(fèi)塔猾,并且隨著請求的增多這種方式會將服務(wù)器資源消耗殆盡,所以這種方式并不推薦本辐。
一種更加輕量級的實(shí)現(xiàn)是使用MDC機(jī)制桥帆,在處理請求前將請求的唯一標(biāo)示放到MDC容器中如sessionId,這個唯一標(biāo)示會隨著日志一起輸出慎皱,以此來區(qū)分該條日志是屬于那個請求的老虫。并在請求處理完成之后清除MDC容器。
下面是MDC對外提供的方法茫多,也可以通過MDC javadocs查看所有方法祈匙。
package org.slf4j;
public class MDC {
// 將一個K-V的鍵值對放到容器,其實(shí)是放到當(dāng)前線程的ThreadLocalMap中
public static void put(String key, String val);
// 根據(jù)key在當(dāng)前線程的MDC容器中獲取對應(yīng)的值
public static String get(String key);
// 根據(jù)key移除容器中的值
public static void remove(String key);
// 清空當(dāng)前線程的MDC容器
public static void clear();
}
簡單的例子
Example 7.1: Basic MDC usage ( logback-examples/src/main/java/chapters/mdc/SimpleMDC.java)
package com.xiaolyuh;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
public class SimpleMDC {
public static void main(String[] args) throws Exception {
// You can put values in the MDC at any time. Before anything else
// we put the first name
MDC.put("first", "Dorothy");
Logger logger = LoggerFactory.getLogger(SimpleMDC.class);
// We now put the last name
MDC.put("last", "Parker");
// The most beautiful two words in the English language according
// to Dorothy Parker:
logger.info("Check enclosed.");
logger.debug("The most beautiful two words in English.");
MDC.put("first", "Richard");
MDC.put("last", "Nixon");
logger.info("I am not a crook.");
logger.info("Attributed to the former US president. 17 Nov 1973.");
}
}
Logback配置:
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<layout>
<Pattern>%X{first} %X{last} - %m%n</Pattern>
</layout>
</appender>
輸出日志:
Dorothy Parker - Check enclosed.
Dorothy Parker - The most beautiful two words in English.
Richard Nixon - I am not a crook.
Richard Nixon - Attributed to the former US president. 17 Nov 1973.
- 在日志模板logback.xml 中天揖,使用 %X{ }來占位夺欲,替換到對應(yīng)的 MDC 中 key 的值。同樣今膊,logback.xml配置文件支持了多種格式的日志輸出些阅,比如%highlight、%d等等斑唬,這些標(biāo)志市埋,在PatternLayout.java中維護(hù)黎泣。
- MDC的容器中的key可以多次賦值,最后一次的賦值會覆蓋上一次的值缤谎。
PatternLayout :
public class PatternLayout extends PatternLayoutBase<ILoggingEvent> {
public static final Map<String, String> defaultConverterMap = new HashMap<String, String>();
public static final String HEADER_PREFIX = "#logback.classic pattern: ";
static {
defaultConverterMap.putAll(Parser.DEFAULT_COMPOSITE_CONVERTER_MAP);
// 按照{(diào)}配置輸出時間
defaultConverterMap.put("d", DateConverter.class.getName());
defaultConverterMap.put("date", DateConverter.class.getName());
// 輸出應(yīng)用啟動到日志時間觸發(fā)時候的毫秒數(shù)
defaultConverterMap.put("r", RelativeTimeConverter.class.getName());
defaultConverterMap.put("relative", RelativeTimeConverter.class.getName());
// 輸出日志級別的信息
defaultConverterMap.put("level", LevelConverter.class.getName());
defaultConverterMap.put("le", LevelConverter.class.getName());
defaultConverterMap.put("p", LevelConverter.class.getName());
// 輸出產(chǎn)生日志事件的線程名
defaultConverterMap.put("t", ThreadConverter.class.getName());
defaultConverterMap.put("thread", ThreadConverter.class.getName());
// 輸出產(chǎn)生log事件的原點(diǎn)的日志名=我們創(chuàng)建logger的時候設(shè)置的
defaultConverterMap.put("lo", LoggerConverter.class.getName());
defaultConverterMap.put("logger", LoggerConverter.class.getName());
defaultConverterMap.put("c", LoggerConverter.class.getName());
// 輸出 提供日志事件的對應(yīng)的應(yīng)用信息
defaultConverterMap.put("m", MessageConverter.class.getName());
defaultConverterMap.put("msg", MessageConverter.class.getName());
defaultConverterMap.put("message", MessageConverter.class.getName());
// 輸出調(diào)用方發(fā)布日志事件的完整類名
defaultConverterMap.put("C", ClassOfCallerConverter.class.getName());
defaultConverterMap.put("class", ClassOfCallerConverter.class.getName());
// 輸出發(fā)布日志請求的方法名
defaultConverterMap.put("M", MethodOfCallerConverter.class.getName());
defaultConverterMap.put("method", MethodOfCallerConverter.class.getName());
// 輸出log請求的行數(shù)
defaultConverterMap.put("L", LineOfCallerConverter.class.getName());
defaultConverterMap.put("line", LineOfCallerConverter.class.getName());
// 輸出發(fā)布日志請求的java源碼的文件名
defaultConverterMap.put("F", FileOfCallerConverter.class.getName());
defaultConverterMap.put("file", FileOfCallerConverter.class.getName());
// 輸出和發(fā)布日志事件關(guān)聯(lián)的線程的MDC
defaultConverterMap.put("X", MDCConverter.class.getName());
defaultConverterMap.put("mdc", MDCConverter.class.getName());
// 輸出和日志事件關(guān)聯(lián)的異常的堆棧信息
defaultConverterMap.put("ex", ThrowableProxyConverter.class.getName());
defaultConverterMap.put("exception", ThrowableProxyConverter.class
.getName());
defaultConverterMap.put("rEx", RootCauseFirstThrowableProxyConverter.class.getName());
defaultConverterMap.put("rootException", RootCauseFirstThrowableProxyConverter.class
.getName());
defaultConverterMap.put("throwable", ThrowableProxyConverter.class
.getName());
// 和上面一樣抒倚,此外增加類的包信息
defaultConverterMap.put("xEx", ExtendedThrowableProxyConverter.class.getName());
defaultConverterMap.put("xException", ExtendedThrowableProxyConverter.class
.getName());
defaultConverterMap.put("xThrowable", ExtendedThrowableProxyConverter.class
.getName());
// 當(dāng)我們想不輸出異常信息時,使用這個坷澡。其假裝處理異常托呕,其實(shí)無任何輸出
defaultConverterMap.put("nopex", NopThrowableInformationConverter.class
.getName());
defaultConverterMap.put("nopexception",
NopThrowableInformationConverter.class.getName());
// 輸出在類附加到日志上的上下文名字.
defaultConverterMap.put("cn", ContextNameConverter.class.getName());
defaultConverterMap.put("contextName", ContextNameConverter.class.getName());
// 輸出產(chǎn)生日志事件的調(diào)用者的位置信息
defaultConverterMap.put("caller", CallerDataConverter.class.getName());
// 輸出和日志請求關(guān)聯(lián)的marker
defaultConverterMap.put("marker", MarkerConverter.class.getName());
// 輸出屬性對應(yīng)的值,一般為System.properties中的屬性
defaultConverterMap.put("property", PropertyConverter.class.getName());
// 輸出依賴系統(tǒng)的行分隔符
defaultConverterMap.put("n", LineSeparatorConverter.class.getName());
// 相關(guān)的顏色格式設(shè)置
defaultConverterMap.put("black", BlackCompositeConverter.class.getName());
defaultConverterMap.put("red", RedCompositeConverter.class.getName());
defaultConverterMap.put("green", GreenCompositeConverter.class.getName());
defaultConverterMap.put("yellow", YellowCompositeConverter.class.getName());
defaultConverterMap.put("blue", BlueCompositeConverter.class.getName());
defaultConverterMap.put("magenta", MagentaCompositeConverter.class.getName());
defaultConverterMap.put("cyan", CyanCompositeConverter.class.getName());
defaultConverterMap.put("white", WhiteCompositeConverter.class.getName());
defaultConverterMap.put("gray", GrayCompositeConverter.class.getName());
defaultConverterMap.put("boldRed", BoldRedCompositeConverter.class.getName());
defaultConverterMap.put("boldGreen", BoldGreenCompositeConverter.class.getName());
defaultConverterMap.put("boldYellow", BoldYellowCompositeConverter.class.getName());
defaultConverterMap.put("boldBlue", BoldBlueCompositeConverter.class.getName());
defaultConverterMap.put("boldMagenta", BoldMagentaCompositeConverter.class.getName());
defaultConverterMap.put("boldCyan", BoldCyanCompositeConverter.class.getName());
defaultConverterMap.put("boldWhite", BoldWhiteCompositeConverter.class.getName());
defaultConverterMap.put("highlight", HighlightingCompositeConverter.class.getName());
}
}
Notes:日志模板配置频敛,使用 %為前綴讓解析器識別特殊輸出模式项郊,然后以{}后綴結(jié)尾,內(nèi)部指定相應(yīng)的參數(shù)設(shè)置姻政。
使用切面
在處理請求前將請求的唯一標(biāo)示放到MDC容器中如sessionId呆抑,這個唯一標(biāo)示會隨著日志一起輸出,以此來區(qū)分該條日志是屬于那個請求的汁展。這個我們可以使用Advanced來實(shí)現(xiàn)鹊碍,可以使用filter,interceptor等食绿。
Interceptor
可以參考篇文章Logback 快速定位用戶在一次請求中的所有日志侈咕。
MDCInsertingServletFilter
這是Logback提供的一個filter,他會將一些請求信息放到MDC容器中器紧,這個filter最好放到配置編碼的filter之后耀销。以下是詳細(xì)的key:
MDC key | MDC value |
---|---|
req.remoteHost | as returned by the getRemoteHost() method |
req.xForwardedFor | value of the "X-Forwarded-For" header |
req.method | as returned by getMethod() method |
req.requestURI | as returned by getRequestURI() method |
req.requestURL | as returned by getRequestURL() method |
req.queryString | as returned by getQueryString() method |
req.userAgent | value of the "User-Agent" header |
使用配置:需要保證filter在需要使用的到該MDC的其他filter之前。
<filter>
<filter-name>MDCInsertingServletFilter</filter-name>
<filter-class>
ch.qos.logback.classic.helpers.MDCInsertingServletFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>MDCInsertingServletFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
應(yīng)用key:
%X{req.remoteHost} %X{req.requestURI}%n%d - %m%n
管理每個線程的MDC容器
我們在主線程上铲汪,新起一個子線程熊尉,并由 java.util.concurrent.Executors來執(zhí)行它時,在早期的版本中子線程可以直接自動繼承父線程的MDC容器中的內(nèi)容掌腰,因?yàn)镸DC在早期版本中使用的是InheritableThreadLocal來作為底層實(shí)現(xiàn)狰住。但是由于性能問題被取消了,最后還是使用的是ThreadLocal來作為底層實(shí)現(xiàn)齿梁。這樣子線程就不能直接繼承父線程的MDC容器催植。
所以,Logback官方建議我們在父線程新建子線程之前調(diào)用MDC.getCopyOfContextMap()方法將MDC內(nèi)容取出來傳給子線程勺择,子線程在執(zhí)行操作前先調(diào)用MDC.setContextMap()方法將父線程的MDC內(nèi)容設(shè)置到子線程创南。
Slf4j MDC實(shí)現(xiàn)原理
Slf4j 的實(shí)現(xiàn)原則就是調(diào)用底層具體實(shí)現(xiàn)類,比如logback,logging等包省核;而不會去實(shí)現(xiàn)具體的輸出打印等操作稿辙。這里使用了裝飾者模式,看源碼就能看出來,所有的方法都是在對mdcAdapter 這個屬性進(jìn)行操作组贺。所以實(shí)現(xiàn)核心是MDCAdapter類肄鸽。
MDCAdapter
MDCAdapter只是定義了一個接口煌贴,具體實(shí)現(xiàn)由子類完成,源碼如下:
public interface MDCAdapter {
public void put(String key, String val);
public String get(String key);
public void remove(String key);
public void clear();
public Map<String, String> getCopyOfContextMap();
public void setContextMap(Map<String, String> contextMap);
}
它有三個實(shí)現(xiàn)類塞耕,BasicMDCAdapter、LogbackMDCAdapter,NOPMDCAdapter萌壳。Logback使用的是LogbackMDCAdapter。
LogbackMDCAdapter
package ch.qos.logback.classic.util;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.slf4j.spi.MDCAdapter;
public class LogbackMDCAdapter implements MDCAdapter {
final ThreadLocal<Map<String, String>> copyOnThreadLocal = new ThreadLocal<Map<String, String>>();
private static final int WRITE_OPERATION = 1;
private static final int MAP_COPY_OPERATION = 2;
// keeps track of the last operation performed
final ThreadLocal<Integer> lastOperation = new ThreadLocal<Integer>();
private Integer getAndSetLastOperation(int op) {
Integer lastOp = lastOperation.get();
lastOperation.set(op);
return lastOp;
}
private boolean wasLastOpReadOrNull(Integer lastOp) {
return lastOp == null || lastOp.intValue() == MAP_COPY_OPERATION;
}
private Map<String, String> duplicateAndInsertNewMap(Map<String, String> oldMap) {
Map<String, String> newMap = Collections.synchronizedMap(new HashMap<String, String>());
if (oldMap != null) {
// we don't want the parent thread modifying oldMap while we are
// iterating over it
synchronized (oldMap) {
newMap.putAll(oldMap);
}
}
copyOnThreadLocal.set(newMap);
return newMap;
}
/**
* Put a context value (the <code>val</code> parameter) as identified with the
* <code>key</code> parameter into the current thread's context map. Note that
* contrary to log4j, the <code>val</code> parameter can be null.
* <p/>
* <p/>
* If the current thread does not have a context map it is created as a side
* effect of this call.
*
* @throws IllegalArgumentException in case the "key" parameter is null
*/
public void put(String key, String val) throws IllegalArgumentException {
if (key == null) {
throw new IllegalArgumentException("key cannot be null");
}
Map<String, String> oldMap = copyOnThreadLocal.get();
Integer lastOp = getAndSetLastOperation(WRITE_OPERATION);
if (wasLastOpReadOrNull(lastOp) || oldMap == null) {
Map<String, String> newMap = duplicateAndInsertNewMap(oldMap);
newMap.put(key, val);
} else {
oldMap.put(key, val);
}
}
/**
* Remove the the context identified by the <code>key</code> parameter.
* <p/>
*/
public void remove(String key) {
if (key == null) {
return;
}
Map<String, String> oldMap = copyOnThreadLocal.get();
if (oldMap == null)
return;
Integer lastOp = getAndSetLastOperation(WRITE_OPERATION);
if (wasLastOpReadOrNull(lastOp)) {
Map<String, String> newMap = duplicateAndInsertNewMap(oldMap);
newMap.remove(key);
} else {
oldMap.remove(key);
}
}
/**
* Clear all entries in the MDC.
*/
public void clear() {
lastOperation.set(WRITE_OPERATION);
copyOnThreadLocal.remove();
}
/**
* Get the context identified by the <code>key</code> parameter.
* <p/>
*/
public String get(String key) {
final Map<String, String> map = copyOnThreadLocal.get();
if ((map != null) && (key != null)) {
return map.get(key);
} else {
return null;
}
}
/**
* Get the current thread's MDC as a map. This method is intended to be used
* internally.
*/
public Map<String, String> getPropertyMap() {
lastOperation.set(MAP_COPY_OPERATION);
return copyOnThreadLocal.get();
}
/**
* Returns the keys in the MDC as a {@link Set}. The returned value can be
* null.
*/
public Set<String> getKeys() {
Map<String, String> map = getPropertyMap();
if (map != null) {
return map.keySet();
} else {
return null;
}
}
/**
* Return a copy of the current thread's context map. Returned value may be
* null.
*/
public Map<String, String> getCopyOfContextMap() {
Map<String, String> hashMap = copyOnThreadLocal.get();
if (hashMap == null) {
return null;
} else {
return new HashMap<String, String>(hashMap);
}
}
public void setContextMap(Map<String, String> contextMap) {
lastOperation.set(WRITE_OPERATION);
Map<String, String> newMap = Collections.synchronizedMap(new HashMap<String, String>());
newMap.putAll(contextMap);
// the newMap replaces the old one for serialisation's sake
copyOnThreadLocal.set(newMap);
}
}
final ThreadLocal<Integer> lastOperation = new ThreadLocal<Integer>();
通過這段代碼日月,我們可以看到底層最終是使用的是ThreadLocal來做實(shí)現(xiàn)袱瓮。