在Maven项目中我们常用logback作为log记录工具,在一次项目更新新模块的开发中log输出的格式以及配置忽然不一样了,经检查发现依赖的jar中存在logback.xml文件。
解决历程:一开始采用的方案为pom文件依赖进行排除但未起作用,后将原目录中的logback-spring.xml更名为logback.xml后问题解决
分析:那么我们就去看看日志系统是如何查找并解析日志配置文件的,SpringBoot中是使用LoggingApplicationListener这个类来进行日志系统的初始化的。LoggingApplicationListener实现了ApplicationListener接口,那么我们通过时序图看LoggingApplicationListener的onApplicationEvent方法做了啥:
代码(8)查找标准日志配置文件,什么是标准那,那么就看代码(9)的代码:
@Override
protected String[] getStandardConfigLocations() {
return new String[] { "logback-test.groovy", "logback-test.xml", "logback.groovy", "logback.xml" };
}
像 “logback-test.groovy”, “logback-test.xml”, “logback.groovy”,“logback.xml” 这些是标准的。
那么具体怎么查找那,要看代码(10):
private String findConfig(String[] locations) {
for (String location : locations) {
ClassPathResource resource = new ClassPathResource(location,
this.classLoader);
if (resource.exists()) {
return "classpath:" + location;
}
}
return null;
}
可知使用ClassPathResource类去查找,下面看ClassPathResource的exists方法:
public boolean exists() {
return (resolveURL() != null);
}
protected URL resolveURL() {
if (this.clazz != null) {
return this.clazz.getResource(this.path);
}
else if (this.classLoader != null) {
return this.classLoader.getResource(this.path);
}
else {
return ClassLoader.getSystemResource(this.path);
}
}
可知是使用 this.classLoader.getResource(this.path); 去查找这里classLoader为AppClassloader。
如果代码(8)没有查找到配置,则执行点(12),代码12逻辑和代码(8)类似只是查找文件名字不一样,下面看下:
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;
}
可知是在getStandardConfigLocations的文件名上拼接spring,拼接后的文件名为:
“` “logback-test-spring.groovy”, “logback-test-spring.xml”, “logback-spring.groovy”,”logback-spring.xml” “
综上所述SpringBoot首先去查找标准的日志配置文件,如果找不到在去找拼接Spring的配置的文件。
那么上面我们说了应用中是引入了一个含有logback.xml的jar包,而这个jar包也是使用appclassloader加载的,所以在执行步骤(8)的时候找到了jar包里面的logback.xml,所以就不会再去执行步骤(12)来找我们自定义的logback-spring.xml了。
方案一,修改我们的配置文件为logback.xml,这样在步骤(8)的时候会首先查找logback.xml,应该是可以找到的。
方案二、避免二方包里面含有logback.xml,这种情况下,无论我们自己的配置是logback-spring.xml还是logback.xml都不会有问题。



