参考原文: https://www.jianshu.com/p/1dea7479eb07
MDC 简介
MDC (org.slf4j.MDC)( Mapped Diagnostic Contexts ),它是一个线程安全的存放诊断日志的容器。SLF4J的MDC实质上就是一个Map。通常实现SLF4J的日志系统支持MDC,即表明该日志系统负责维护这个Map。应用就可以依赖于日志系统,直接存取key/value对到该Map中。
2. 源码关键分析
2.1 org.slf4j.MDC
2.2 org.slf4j.spi.MDCAdapter
private static MDCAdapter bwCompatibleGetMDCAdapterFromBinder() throws NoClassDefFoundError {
try {
return StaticMDCBinder.getSingleton().getMDCA();
} catch (NoSuchMethodError var1) {
return StaticMDCBinder.SINGLETON.getMDCA();
}
}
2.3 格式转换器基础类,org.apache.logging.log4j.core.pattern.LogEventPatternConverter
2.3.1 mdc展位符格式'%X{}', 实现类: org.apache.logging.log4j.core.pattern.MdcPatternConverter
2.3.2 org.apache.logging.log4j.core.pattern.MessagePatternConverter
2.3.3 org.apache.logging.log4j.core.pattern.MethodLocationPatternConverter
2.3.4 时间占位符格式'%date{yyyy-MM-dd HH:mm:ss.SSS}',实现类: org.apache.logging.log4j.core.pattern.DatePatternConverter
2.3.5 org.apache.logging.log4j.core.pattern.LineSeparatorPatternConverter
2.3.6 org.apache.logging.log4j.core.pattern.ThreadNamePatternConverter
3. message处理分析
3.1 message处理类,org.apache.logging.log4j.message.Message
public interface Message extends Serializable {
String getFormattedMessage();
String getFormat();
Object[] getParameters();
Throwable getThrowable();
}
3.2 messageFactory消息处理类
默认是org.apache.logging.log4j.message.ParameterizedMessageFactory。也可以自定义处理类继承org.apache.logging.log4j.message.AbstractMessageFactory
3.2.1 自定义处理类。这样可以对原始数据做一些自定义的加工处理。比如脱敏,加密等等,在classpath下新增文件log4j2.component.properties
log4j2.messageFactory=org.apache.logging.log4j.message.ParameterizedMessageFactory
4. log4j plugin插件分析
plugin加载流程图如下
org.apache.logging.log4j.core.LoggerContext#start()
org.apache.logging.log4j.core.LoggerContext#reconfigure()
org.apache.logging.log4j.core.LoggerContext#setConfiguration
org.apache.logging.log4j.core.config.AbstractConfiguration#start
org.apache.logging.log4j.core.config.AbstractConfiguration#initialize
org.apache.logging.log4j.core.config.AbstractConfiguration#doConfigure
org.apache.logging.log4j.core.config.AbstractConfiguration#createConfiguration
org.apache.logging.log4j.core.config.AbstractConfiguration#createPluginObject
org.apache.logging.log4j.core.config.plugins.util.PluginBuilder#build
4.1 properties插件
4.1.1 org.apache.logging.log4j.core.config.PropertiesPlugin
4.1.2 org.apache.logging.log4j.core.config.Property
4.2 filter插件
4.2.1 org.apache.logging.log4j.core.filter.CompositeFilter
4.2.2 org.apache.logging.log4j.core.filter.LevelRangeFilter