1總結
1.1 log4j2本身是支持log4j2.properties配置的,只是log4j2.properties的配置格式完成不同於1版本,或者說沒有向前兼容。
2 slf4j+log4j2組合
slf4j+log4j2的啓動入口是org.slf4j.LoggerFactory.getLogger(XXX.class) 一旦調這個方法,就開始啓動初始化,如果不調,即便項目中有對應的架包,也不執行初始化。
ClassLoader.getResources("org/slf4j/impl/StaticLoggerBinder.class")去尋找日誌實現類。
3 log4j2配置相關
org.apache.logging.log4j.core.impl.Log4jContextFactory的getContext方法讀取配置文件
由org.apache.logging.log4j.core.config.ConfigurationFactory處理參數配置
讀了配置文件的優先順序 proerties -> yaml -> json -> xml
[class org.apache.logging.log4j.core.config.properties.PropertiesConfigurationFactory,
class org.apache.logging.log4j.core.config.yaml.YamlConfigurationFactory,
class org.apache.logging.log4j.core.config.json.JsonConfigurationFactory,
class org.apache.logging.log4j.core.config.xml.XmlConfigurationFactory]
讀取xml配置文件的終級類是org.apache.logging.log4j.core.config.xml.XmlCon
Figuration
Xml配置文件根屬性有status、dest、shutdownHook、shutdownTimeout、verbose、packages、name、strict、schema、monitorInterval、advertiser。這些屬性定義在
org.apache.logging.log4j.core.config.xml.XmlConfiguration.XmlConfiguration(LoggerContext, ConfigurationSource)第100行左右
屬性 |
作用 |
dest |
可以指定一個文件,這個文件會打印log4j2啓動時顯示的一個日誌(同時status="trace"),幫助排查原因。 |
shutdownHook |
是否開啓關閉監聽。disable是關閉 |
shutdownTimeout |
關閉的超時時間 |
packages |
指定包下面的插件也加入到log4j中 |
monitorInterval |
定時掃描配置文件的時間間隔 |
advertiser |
定時器的名字,隨便取比如,abc |
所有的配置組件都有實現@PluginFactory的方法,框架通過這個方法,傳入參數,通過反射機制完成組件實例化。
元素 |
對應類 |
Logger |
org.apache.logging.log4j.core.config.LoggerConfig.createLogger(boolean, Level, String, String, AppenderRef[], Property[], Configuration, Filter) |
appender |
org.apache.logging.log4j.core.appender.RollingFileAppender.Builder.build() |
layout |
org.apache.logging.log4j.core.layout.PatternLayout.Builder.build() |
AppenderRef |
org.apache.logging.log4j.core.config.AppenderRef.createAppenderRef(String, Level, Filter) |
RollingFile |
org.apache.logging.log4j.core.appender.RollingFileAppender.Builder.build() |
property |
org.apache.logging.log4j.core.config.Property.createProperty(String, String) |
RootLogger |
org.apache.logging.log4j.core.config.LoggerConfig.RootLogger.createLogger(String, Level, String, AppenderRef[], Property[], Configuration, Filter) |
Logger像一個收集器。Append像一個分發器。Logger和Append是一個多對多的關係(多數情況下是用的是一對一的簡單場景)
6 名詞解析
DefaultRolloverStrategy(默認): 有一個主文件,觸發拆分事件後,主文件改名,然後繼續新建主文件寫入。
DirectWriteRolloverStrategy: 沒有主文件,直接在分文件上寫。
5 配置樣例
5.1 所有日誌走console, 部分日誌走A1, 如果不想走console,就additivity=false