首先在 SpringBoot 中集成log4j2
还是比较容易的,只需要在 maven 的 pom 文件中修改一下 logging 的依赖然后在resources
中添加log4j2
相关的配置文件就可以了。
我当时使用的是log4j2.yml
格式的配置文件,所以就在maven
的pom.xml
文件中做了如下的修改:
<dependencies>
...
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--添加log4j2依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<!-- 使用log4j2.yml文件格式来配置,需要引入如下的包 -->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
</dependency>
...
</dependencies>
这个在我当时的项目中是正确运行的。
我后来又创建了一个新的项目,也想用log4j2
,就直接复制了上一个项目中配置了,但是在运行的时候发现怎么也加载不了log4j2
的配置文件,总是提示ERROR StatusLogger No Log4j 2 configuration file found. Using default configuration (logging only errors to the console), or user programmatically provided ...
,但是log4j2
的配置文件的确是存在的。
在这样的情况下,日志是无论如何都不会打印出来的,没办法只能加上log4j2.debug
属性进行调试,在控制台的日志中我发现了这样一条日志WARN StatusLogger Found configuration file log4j2.yml for inactive ConfigurationFactory org.apache.logging.log4j.core.config.yaml.YamlConfigurationFactory
,大体就是YamlConfigurationFactory
不是激活状态,就试着全局搜索这句话,找到了如下的代码,
if (source !=null ){
if (!factory.isActive()){
LOGGER.warn("Found configuration file {} for inactive ConfigurationFactory {}", configName, factory.getClass().getName());
}
return factory.getConfiguration(loggerContext, source);
}
很明显这里的factory
就是YamlConfigurationFactory
,很容易就能找到这个isActive
是怎么实现的,这里找到了如下的代码:
private static final String[] dependencies = new String[] {
"com.fasterxml.jackson.databind.ObjectMapper",
"com.fasterxml.jackson.databind.JsonNode",
"com.fasterxml.jackson.core.JsonParser",
"com.fasterxml.jackson.dataformat.yaml.YAMLFactory"
};
public YamlConfigurationFactory() {
for (final String dependency : dependencies) {
if (!Loader.isClassAvailable(dependency)) {
LOGGER.debug("Missing dependencies for Yaml support, ConfigurationFactory {} is inactive", getClass().getName());
isActive = false;
return;
}
}
isActive = true;
}
从代码中可以看出,需要dependencies
这里面的这几个类都在类路径上才能激活,再检查一下项目就发现项目中少了jackson-databind
的依赖,这里在pom.xml
文件中加上jackson-databind
依赖就可以解决问题。
对比两次使用经历发现了,在第一个项目中,我添加了spring-boot-starter-web
依赖,添加之后已经引入了jackson-databind
依赖,所以在第一个项目中不会出现问题,第二个项目中由于没有jackson-databind
依赖,所以导致了不能成功加载log4j2.yml
配置文件。