在 Spring 引导应用程序中使用 log4j2 记录

Logging with log4j2 in Spring Boot app

我正在努力学习Spring引导。但是我完全搞砸了记录器的依赖关系。 我有一个简单的 pom:

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- Logging -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId>
            <version>2.3</version>
        </dependency>
    </dependencies>

我在 ..src\main\resources\

中创建了 log4j2.xml

我用这样的方式登录:

private static final Logger LOG = LoggerFactory.getLogger(MyClass.class);
LOG.error("ERRRRRRR!!!!");

但是当应用程序启动时我看到:

SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/Users/me/.m2/repository/ch/qos/logback/logback-classic/1.1.3/logback-classic-1.1.3.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Users/me/.m2/repository/org/apache/logging/log4j/log4j-slf4j-impl/2.3/log4j-slf4j-impl-2.3.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [ch.qos.logback.classic.util.ContextSelectorStaticBinder]

当然 log4j2 及其配置不起作用。

我知道,这是一个很受欢迎的问题。我用谷歌搜索了很多答案,但没有一个对我有用。

您的类路径中有多个 SLF4J 绑定。

  • Logback classic,默认包含在spring boot
  • 您要使用的 Log4j。

你需要在类路径中有一个,通过使用 maven 依赖排除。

您必须排除与 spring-boot-starter-batch 捆绑在一起的 logback,并将其替换为 spring-boot-starter-log4j2。查看 documentation 日志记录和 Spring 启动。

这个 pom 配置很适合我。

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-batch</artifactId>
        <version>${spring.boot.version}</version>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j2</artifactId>
        <version>${spring.boot.version}</version>
    </dependency>