本文通過項目中的日誌配置問題,引出並總結一下spring boot 2.1.x 中 log4j2 的配置
現象
在服務器上調試項目的時候,發現日誌文件生成的路徑有問題,總是找不到日誌位置,後來測試發現每次都在當前目錄下生成 log/xxx.log
查看項目配置如下:
logging.level.com.xxx.yyy=INFO
logging.file=log/xxx.log
在resource目錄下,有log4j.properties(記住這個文件名稱),內容如下
解決(測試基於spring boot 2.1.5)
1、因爲對此配置不熟悉,直接修改了配置文件中的appender.File值爲絕對路徑,後經測試根本不生效
2、修改spring boot 配置文件中的logging.file爲絕對路徑,發現配置生效
所以其實是log4j的配置文件根本就沒有被加載
3、查看spring boot 官方文檔,可以看到如下說明
支持如上幾種log system以及各自的自動加載的配置文件名稱,唯獨沒有看到 .properties 後綴的支持,覺得不應該
4、只能通過源碼來找答案了
AbstractLoggingSystem
@Override
public void initialize(LoggingInitializationContext initializationContext,
String configLocation, LogFile logFile) {
// 如果指定了log配置文件路徑(logging.config)
if (StringUtils.hasLength(configLocation)) {
// 指定了自定義配置的處理方法
initializeWithSpecificConfig(initializationContext, configLocation, logFile);
return;
}
// 未指定則加載默認配置
initializeWithConventions(initializationContext, logFile);
}
看到這裏的initialize方法和剛纔的官方文檔說明,想到大概是properties需要顯示的通過logging.config來指定,加上後測試,發現依然沒用,只能繼續往下看源碼
通過initializeWithSpecificConfig方法我們一路找下去,可以找到Log4J2LoggingSystem的loadConfiguration方法
protected void loadConfiguration(String location, LogFile logFile) {
Assert.notNull(location, "Location must not be null");
try {
LoggerContext ctx = getLoggerContext();
URL url = ResourceUtils.getURL(location);
ConfigurationSource source = getConfigurationSource(url);
// 通過對應的配置工廠加載配置
ctx.start(ConfigurationFactory.getInstance().getConfiguration(ctx, source));
}
catch (Exception ex) {
throw new IllegalStateException(
"Could not initialize Log4J2 logging from " + location, ex);
}
}
看到這裏又產生了疑惑,如下圖,除了官方文檔提到的那些格式,還有PropertiesConfigurationFactory,說明properties一定是可以被解析的,debug發現的確進入到這裏,也解析了配置文件,但是結果依然是沒有生效
爲了測試是否是環境問題,將配置文件修改爲官方推薦的log4j2.xml,發現此配置生效,說明問題還是出在properties文件中
不得不說,解決問題果然還是得靠官網,通過查閱log4j2官網發現,項目這裏的配置犯了很低級的錯誤,我們依賴的是log4j2,而properties文件裏還是log4j 1.x的語法,從log4j2官方copy如下配置
status = error
dest = err
name = PropertiesConfig
property.filename = target/rolling/rollingtest.log
filter.threshold.type = ThresholdFilter
filter.threshold.level = debug
appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %m%n
appender.console.filter.threshold.type = ThresholdFilter
appender.console.filter.threshold.level = error
appender.rolling.type = RollingFile
appender.rolling.name = RollingFile
appender.rolling.fileName = ${filename}
appender.rolling.filePattern = target/rolling2/test1-%d{MM-dd-yy-HH-mm-ss}-%i.log.gz
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = %d %p %C{1.} [%t] %m%n
appender.rolling.policies.type = Policies
appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling.policies.time.interval = 2
appender.rolling.policies.time.modulate = true
appender.rolling.policies.size.type = SizeBasedTriggeringPolicy
appender.rolling.policies.size.size=100MB
appender.rolling.strategy.type = DefaultRolloverStrategy
appender.rolling.strategy.max = 5
logger.rolling.name = com.example.my.app
logger.rolling.level = debug
logger.rolling.additivity = false
logger.rolling.appenderRef.rolling.ref = RollingFile
rootLogger.level = info
rootLogger.appenderRef.stdout.ref = STDOUT
果不其然,配置生效了
可是現在還有一個疑問就是,爲什麼spring boot官網沒有說明properties配置文件的默認命名格式,還是說必須得用logging.config指定
繼續看源碼,還有一條分支沒有看,不顯示指定配置文件的情況
private void initializeWithConventions(
LoggingInitializationContext initializationContext, LogFile logFile) {
String config = getSelfInitializationConfig();
if (config != null && logFile == null) {
// self initialization has occurred, reinitialize in case of property changes
reinitialize(initializationContext);
return;
}
if (config == null) {
config = getSpringInitializationConfig();
}
if (config != null) {
loadConfiguration(initializationContext, config, logFile);
return;
}
loadDefaults(initializationContext, logFile);
}
先通過getSelfInitializationConfig方法找到log4j2對應的初始化配置方法
private String[] getCurrentlySupportedConfigLocations() {
List<String> supportedConfigLocations = new ArrayList<>();
supportedConfigLocations.add("log4j2.properties");
if (isClassAvailable("com.fasterxml.jackson.dataformat.yaml.YAMLParser")) {
Collections.addAll(supportedConfigLocations, "log4j2.yaml", "log4j2.yml");
}
if (isClassAvailable("com.fasterxml.jackson.databind.ObjectMapper")) {
Collections.addAll(supportedConfigLocations, "log4j2.json", "log4j2.jsn");
}
supportedConfigLocations.add("log4j2.xml");
return StringUtils.toStringArray(supportedConfigLocations);
}
看到這裏上面的疑惑也就解決了,因爲項目的配置文件名稱不符合初始化配置,應當改爲log4j2.properties
如果classpath中沒有上述命名格式的配置文件,則獲取-spring.命名標識的配置文件
protected String[] getSpringConfigLocations() {
String[] locations = getStandardConfigLocations();
for (int i = 0; i < locations.length; i++) {
String extension = StringUtils.getFilenameExtension(locations[i]);
locations[i] = locations[i].substring(0,
locations[i].length() - extension.length() - 1) + "-spring."
+ extension;
}
return locations;
}
如果也沒有找到,就加載默認配置
@Override
protected void loadDefaults(LoggingInitializationContext initializationContext,
LogFile logFile) {
if (logFile != null) {
loadConfiguration(getPackagedConfigFile("log4j2-file.xml"), logFile);
}
else {
loadConfiguration(getPackagedConfigFile("log4j2.xml"), logFile);
}
}
總結
1、去掉logback的依賴,引入spring-boot-starter-log4j2,官方文檔有這裏就不再贅述
2、新建log4j2.properties(當然可以是支持的其他後綴文件),如果想要spring boot 自動識別配置文件,記得文件名要是log4j2
所以,解決問題最有效的方式,還是得通過官網和源碼