一、为什么会有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.