首页 > 解决方案 > Log4J2 在多个级别上无法在 Spring Boot 上运行

问题描述

我正在尝试在 Spring Boot 应用程序中使用 log4j2,但它在几个级别上都出错了。

这是一个非常简单的 Hello World 应用程序,只是在我在生产代码中尝试之前尝试让事情正常运行。它只是一个简单的 Initializr 生成的 Spring Boot 应用程序,没有添加依赖项。

问题 #1 是我收到以下警告,所以我尝试添加排除项,但到目前为止没有任何效果

SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/C:/Users/vgray/.m2/repository/ch/qos/logback/logback-classic/1.2.3/logback-classic-1.2.3.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/C:/Users/vgray/.m2/repository/org/apache/logging/log4j/log4j-slf4j-impl/2.13.3/log4j-slf4j-impl-2.13.3.jar!/org/slf4j/impl/StaticLoggerBinder.class]

这是pom:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.sample</groupId>
    <artifactId>log4j2</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>log4j2</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</java.version>
        <log4j2.version>2.13.3</log4j2.version>
    </properties>
    <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>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

问题 #2(我假设相关)是我的 src/main/resources 目录中有 log4j2.xml,但它似乎被忽略了。

这是 log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn">
    <Properties>
        <Property name="basePath">E:\dev\log4j2\\logs</Property>
    </Properties>

    <Appenders>
        <RollingFile name="fileLogger" fileName="${basePath}/app-info.log" filePattern="${basePath}/app-info-%d{yyyy-MM-dd}.log">
            <PatternLayout>
                <pattern>[%-5level] %d{MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n</pattern>
            </PatternLayout>
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true" />
            </Policies>
        </RollingFile>

        <Console name="console" target="SYSTEM_OUT">
            <PatternLayout   pattern="[%-5level] %d{MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
        </Console>
    </Appenders>
    <Loggers>
        <Logger name="Log4j2Application" level="debug" additivity="true">
            <appender-ref ref="fileLogger" level="debug" />
        </Logger>
        <Root level="debug" additivity="false">
            <appender-ref ref="console" />
        </Root>
    </Loggers>
</Configuration>

我假设它被忽略了,因为模式应该是 MM-dd ...,但是日志消息的记录方式不同。

这是我的整个 Spring Boot 程序:

package com.vgray.sample.log4j2;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Log4j2Application {

    private static final Logger logger = LogManager.getLogger("Log4j2Application");

    public static void main(String[] args) {
        logger.trace("A TRACE Message");
        logger.debug("A DEBUG Message");
        logger.info("An INFO Message");
        logger.warn("A WARN Message");
        logger.error("An ERROR Message");
        logger.error("Error Message Logged !!!", new NullPointerException("NullError"));
        SpringApplication.run(Log4j2Application.class, args);
    }

}

这是我的整个日志

SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/C:/Users/vgray/.m2/repository/ch/qos/logback/logback-classic/1.2.3/logback-classic-1.2.3.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/C:/Users/vgray/.m2/repository/org/apache/logging/log4j/log4j-slf4j-impl/2.13.3/log4j-slf4j-impl-2.13.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]
21:20:18.355 [main] DEBUG Log4j2Application - A DEBUG Message
21:20:18.358 [main] INFO Log4j2Application - An INFO Message
21:20:18.358 [main] WARN Log4j2Application - A WARN Message
21:20:18.358 [main] ERROR Log4j2Application - An ERROR Message
21:20:18.361 [main] ERROR Log4j2Application - Error Message Logged !!!
java.lang.NullPointerException: NullError
    at com.vgray.sample.log4j2.Log4j2Application.main(Log4j2Application.java:19)
21:20:18.531 [restartedMain] DEBUG Log4j2Application - A DEBUG Message
21:20:18.532 [restartedMain] INFO Log4j2Application - An INFO Message
21:20:18.532 [restartedMain] WARN Log4j2Application - A WARN Message
21:20:18.532 [restartedMain] ERROR Log4j2Application - An ERROR Message
21:20:18.532 [restartedMain] ERROR Log4j2Application - Error Message Logged !!!
java.lang.NullPointerException: NullError
    at com.vgray.sample.log4j2.Log4j2Application.main(Log4j2Application.java:19)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.4.2)

2021-02-28 21:20:19.087  INFO 69604 --- [  restartedMain] c.v.sample.log4j2.Log4j2Application      : Starting Log4j2Application using Java 11.0.3 on DESKTOP-AM6DIPA with PID 69604 (E:\dev\log4j2\target\classes started by vgray in e:\dev\log4j2)
2021-02-28 21:20:19.089  INFO 69604 --- [  restartedMain] c.v.sample.log4j2.Log4j2Application      : No active profile set, falling back to default profiles: default
2021-02-28 21:20:19.174  INFO 69604 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2021-02-28 21:20:19.174  INFO 69604 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2021-02-28 21:20:20.352  INFO 69604 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2021-02-28 21:20:20.364  INFO 69604 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2021-02-28 21:20:20.364  INFO 69604 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.41]
2021-02-28 21:20:20.451  INFO 69604 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2021-02-28 21:20:20.451  INFO 69604 --- [  restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1275 ms
2021-02-28 21:20:20.657  INFO 69604 --- [  restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2021-02-28 21:20:20.829  INFO 69604 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2021-02-28 21:20:20.862  INFO 69604 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2021-02-28 21:20:20.876  INFO 69604 --- [  restartedMain] c.v.sample.log4j2.Log4j2Application      : Started Log4j2Application in 2.33 seconds (JVM running for 3.718)

标签: spring-bootlog4j2

解决方案


我认为您的两个问题都会引起,因为您没有排除spring-boot-starter-parent您作为父依赖项包含的日志记录依赖项。您需要将其从入门父级中排除,例如:

   <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

您的 pom.xml 将其排除在外spring-boot-starter


推荐阅读