一、爲什麼會有MDC(MappedDiagnosticContext)?
審計和調試分佈式應用是logback的設計目標之一,在多線程環境中,不同的線程會處理不同的客戶端,爲了區分不同客戶端日誌輸出,一種輕量級但不可取的做法是爲每個實例化一個新的、完全分離日誌記錄器,這種方法會產生很多的日誌記錄器而且難以管理。
更輕量級的做法是唯一標記每個來自客戶端的日誌請求,爲了唯一標記每個請求,用戶把上下文信息放置到MDC中,MDC類的核心方法如下,完整方法參考MDC javadocs。
package org.slf4j;
public class MDC {
//Put a context value as identified by key
//into the current thread's context map.
public static void put(String key, String val);
//Get the context identified by the key parameter.
public static String get(String key);
//Remove the context identified by the key parameter.
public static void remove(String key);
//Clear all entries in the MDC.
public static void clear();
}
1、基本MDC的使用
package chapters.mdc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import ch.qos.logback.classic.PatternLayout;
import ch.qos.logback.core.ConsoleAppender;
public class SimpleMDC {
static public 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>
注意:通過%X轉換詞可以獲取MDC設置的變量值。
日誌輸出如下:
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.