spring boot 2.1.x log4j2 配置

本文通过项目中的日志配置问题,引出并总结一下spring boot 2.1.x 中 log4j2 的配置

现象

在服务器上调试项目的时候,发现日志文件生成的路径有问题,总是找不到日志位置,后来测试发现每次都在当前目录下生成 log/xxx.log
查看项目配置如下:

logging.level.com.xxx.yyy=INFO
logging.file=log/xxx.log

在resource目录下,有log4j.properties(记住这个文件名称),内容如下
log4j官网图片

解决(测试基于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);
	}
}

spring boot log4j2 默认配置文件

总结

1、去掉logback的依赖,引入spring-boot-starter-log4j2,官方文档有这里就不再赘述
2、新建log4j2.properties(当然可以是支持的其他后缀文件),如果想要spring boot 自动识别配置文件,记得文件名要是log4j2

所以,解决问题最有效的方式,还是得通过官网和源码

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章