Spring Boot未搜索log4j2配置文件。

4
我正在尝试在Spring Boot 2.2.1中使用Apache Log4j 2.12.1,但运行时没有任何关于缺少log4j 2配置文件的警告。以下是用于记录日志的代码(简单的测试类以测试它是否可行):
package com.example.Log4jdemoSpringboot;

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 Log4jDemoSpringBootApplication {

    static Logger logger = LogManager.getLogger(Log4jDemoSpringBootApplication.class);
    public static void main(String[] args) {
        SpringApplication.run(Log4jDemoSpringBootApplication.class, args);
        logger.info("info");
        logger.warn("warn");
        logger.error("error");
        logger.debug("debug");
        logger.fatal("fatal");
    }

}

以下是输出结果:

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

2019-11-18 12:19:20.844  INFO 13136 --- [           main] c.e.L.Log4jDemoSpringBootApplication     : Starting Log4jDemoSpringBootApplication on Gurpreet-PC with PID 13136 (C:\Development\eclipse-workspace\Log4j-demo-Spring-boot\target\classes started by Gurpreet in C:\Development\eclipse-workspace\Log4j-demo-Spring-boot)
2019-11-18 12:19:20.872  INFO 13136 --- [           main] c.e.L.Log4jDemoSpringBootApplication     : No active profile set, falling back to default profiles: default
2019-11-18 12:19:26.946  INFO 13136 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-11-18 12:19:27.009  INFO 13136 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-11-18 12:19:27.011  INFO 13136 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.27]
2019-11-18 12:19:27.442  INFO 13136 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-11-18 12:19:27.444  INFO 13136 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 6320 ms
2019-11-18 12:19:28.213  INFO 13136 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-11-18 12:19:28.925  INFO 13136 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-11-18 12:19:28.937  INFO 13136 --- [           main] c.e.L.Log4jDemoSpringBootApplication     : Started Log4jDemoSpringBootApplication in 10.398 seconds (JVM running for 13.269)
2019-11-18 12:19:28.945  INFO 13136 --- [           main] c.e.L.Log4jDemoSpringBootApplication     : info
2019-11-18 12:19:28.949  WARN 13136 --- [           main] c.e.L.Log4jDemoSpringBootApplication     : warn
2019-11-18 12:19:28.952 ERROR 13136 --- [           main] c.e.L.Log4jDemoSpringBootApplication     : error
2019-11-18 12:19:28.953 ERROR 13136 --- [           main] c.e.L.Log4jDemoSpringBootApplication     : fatal

然而,如果我将相同的配置用于简单的Java项目,它可以正常工作。

1
你的意思是它没有提醒缺少 log4j 文件?从日志中我可以看到你的项目运行得很好。 - Adya
我认为不需要log4j配置文件。如果您希望提供自定义记录器级别和其他配置,则需要配置文件。如果您不想使用配置文件,Spring Boot会处理所有事情。只需添加依赖项即可开始。 - Harsh Mishra
@Adya - 在日志中,我们可以看到它将致命消息记录为错误,并忽略了调试消息。因此,它没有按预期工作。这可以通过配置文件进行修复,但Spring完全忽略了配置文件的存在或缺失。 - Gurpreet Singh
@HarshMishra - 是的,我想要自定义的日志级别,并将日志写入文件。但是Spring完全忽略了配置文件的存在或不存在。如果我在简单的Java项目中使用它,我可以将日志写入文件并更改日志级别。 - Gurpreet Singh
4个回答

8
我遇到了一个问题,Spring Boot 没有搜索到配置的 XML 文件。 我在 application.properties 文件中添加了以下行(log4j2.xml 在 src/main/resources 目录下)。
logging.config=classpath:log4j2.xml

7

分享一下我的经验,我也遇到了log4j2配置方面的问题。以下是我得出的解决方案。

  1. 运行命令: mvn dependency:tree 此命令将告诉您在您的配置文件之前加载了哪些依赖项。

  2. 在pom.xml中添加对于在您的日志依赖项之前加载的依赖项的排除(exclusions),添加以下任意一个选项,我的使用选项a可以正常工作。

a-

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

b-

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
        </exclusion>
        <exclusion>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
        </exclusion>
    </exclusions>
</dependency>

这样一切都正常工作了,我的log4j2.xml配置成功加载。请确保配置文件在类路径中。


3
希望这是您要找的内容。 这是我在Spring boot日志记录中使用的东西。 在application.properties文件中。
#logging.level.root=WARN
logging.level.org.springframework=DEBUG
logging.level.com.appicantion.name=DEBUG

#output to a temp_folder/file
logging.file=${java.io.tmpdir}/application.log

# Logging pattern for the console
logging.pattern.console= %d{yyyy-MM-dd HH:mm:ss} - %msg%n

# Logging pattern for file
logging.pattern.file= %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%

你的回答:在log4j2中,将log4j2.xml添加到src/main/resources文件夹中。
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="30">
    <Properties>
        <Property name="LOG_PATTERN">%d{yyyy-MM-dd'T'HH:mm:ss.SSSZ} %p %m%n</Property>
        <Property name="APP_LOG_ROOT">c:/temp</Property>
    </Properties>
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT" follow="true">
            <PatternLayout pattern="${LOG_PATTERN}" />
        </Console>

        <RollingFile name="appLog"
            fileName="${APP_LOG_ROOT}/SpringBoot2App/application.log"
            filePattern="${APP_LOG_ROOT}/SpringBoot2App/application-%d{yyyy-MM-dd}-%i.log">
            <PatternLayout pattern="${LOG_PATTERN}" />
            <Policies>
                <SizeBasedTriggeringPolicy size="19500KB" />
            </Policies>
            <DefaultRolloverStrategy max="1" />
        </RollingFile>

    </Appenders>
    <Loggers>

        <Logger name="com.application.app" additivity="false">
            <AppenderRef ref="appLog" />
            <AppenderRef ref="Console" />
        </Logger>

        <Root level="debug">
            <AppenderRef ref="Console" />
        </Root>
    </Loggers>
</Configuration>

https://howtodoinjava.com/spring-boot2/logging/spring-boot-log4j2-config/


谢谢 :) 它给了我足够的提示,让我知道我错在哪里。然而,事情仍然没有按照应该的方式工作,但现在我知道要寻找什么了。 - Gurpreet Singh
Log4j2修复了我所有的问题。非常感谢。 - Gurpreet Singh

0
这个问题也真的让我很困扰,但解决方案已经很接近了: Spring默认使用Logback,如果想要使用Log4J2或者其他日志记录器,首先需要在Maven中将Logback从Spring库中排除,并将"log4J2.xml"配置文件添加到资源文件夹中。 你可以在这里找到第5步的说明 - https://www.baeldung.com/spring-boot-logging

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接