log4j2 與 log4j使用時的幾點小區別
雖然log4j2 目前還是beta版,不過OneCoder已經忍不住要嘗試一下。跟使用log4j 比起來,上手上主要的區別有。
1、依賴的jar包。使用slf4j+log4j2 時,依賴的jar包如下:(gradle配置,Maven對照修改即可)
dependencies{
compile(
"org.apache.logging.log4j:log4j-api:$log4j_version",
"org.apache.logging.log4j:log4j-core:$log4j_version",
"org.apache.logging.log4j:log4j-slf4j-impl:$log4j_version"
)
}
其中,log4j_version=2.0-beta9
2、預設配置檔名字
預設搜尋的配置檔名字變為log4j2或log4j-test開頭的配置檔案,這個變化,讓OneCoder吃了些苦頭。沒注意觀察,還自以為配置檔案還是log4j.xml,結果怎麼都不管用。後來仔細閱讀官方文件才發現問題。log4j2中,支援json和xml兩個格式的配置檔案,配置檔案的搜尋順序為:
1. Log4j will inspect the "log4j.configurationFile" system property and, if set, will attempt to load the configuration using the ConfigurationFactory that matches the file extension.
2. If no system property is set the JSON ConfigurationFactory will look for log4j2-test.json or log4j2-test.jsn in the classpath.
3. If no such file is found the XML ConfigurationFactory will look for log4j2-test.xml in the classpath.
4. If a test file cannot be located the JSON ConfigurationFactory will look for log4j2.json or log4j2.jsn on the classpath.
5. If a JSON file cannot be located the XML ConfigurationFactory will try to locate log4j2.xml on the classpath.
6. If no configuration file could be located the DefaultConfiguration will be used. This will cause logging output to go to the console.
環境變數log4j.configurationFile指定的檔案->log4j2-test.json/log4j2-test.jsn -> log4j2-test.xml -> log4j2.json/log4j2.jsn -> log4j2.xml - > 預設配置DefaultConfiguration
3、配置檔案格式
配置檔案樣例,跟1比起來有所簡化。
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5level %l - %msg%n" />
</Console>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="Console" />
</Root>
</Loggers>
</Configuration>
其他的變化和優勢,您可以在使用中慢慢體會了。