首先在SpringBoot中集成log4j2还是比较容易的,只需要在maven的pom文件中修改一下logging的依赖然后在resources中添加log4j2相关的配置文件就可以了。 我当时使用的是log4j2.yml格式的配置文件,所以就在mavenpom.xml文件中做了如下的修改:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<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不是激活状态,就试着全局搜索这句话,找到了如下的代码,

1
2
3
4
5
6
    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是怎么实现的,这里找到了如下的代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
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配置文件。