首先在 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
不是激活状态,就试着全局搜索这句话,找到了如下的代码,