Spring应用程序启动前的Spring启动设置日志记录

问题描述 投票:2回答:3

我有一个项目,我需要在启动SpringApplication之前使用日志记录机制。我怎样才能做到这一点?

我试图设置我自己的日志记录机制(LogManager.getLogManager()。readConfiguration()),但是当spring应用程序启动时它被覆盖。

基本上我想在任何地方使用相同的日志记录机制。

java spring spring-boot
3个回答
2
投票

Spring Boot使用LoggingApplicationListener为您的应用程序配置日志记录。这个监听器是SpringApplication的默认监听器之一。要使用您自己已配置的日志记录系统,您需要配置SpringApplication,使其没有此侦听器。例如,要删除不需要的侦听器,同时保留所有其他默认侦听器:

@SpringBootApplication
public class CustomLoggingApplication {

    public static void main(String[] args) {        
        SpringApplication application = 
                new SpringApplication(CustomLoggingApplication.class);

        Collection<ApplicationListener<?>> listeners = 
                new ArrayList<ApplicationListener<?>>();
        for (ApplicationListener<?> listener: application.getListeners()) {
            if (!(listener instanceof LoggingApplicationListener)) {
                listeners.add(listener);
            }
        }
        application.setListeners(listeners);

        application.run(args);
    }

}

0
投票

您可以在web.xml中配置Log4j侦听器,而不是spring-context.xml

<context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>/WEB-INF/classes/log4j.properties</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>

所以它在Spring开始之前就已经开始了。


0
投票

我设法通过从我的项目中删除“spring-boot-starter-logging”依赖项并添加'org.slf4j:slf4j-jdk14:1.7.5'和'commons-logging:commons-logging:1.1.1'来解决我的问题。 。

我使用gradle所以在我的情况下我通过以下方式实现:

compile("org.springframework.boot:spring-boot-starter-web") {
    exclude module: "spring-boot-starter-logging"
}
compile("org.springframework.boot:spring-boot-starter-actuator") {
    exclude module: "spring-boot-starter-logging"
}

compile('org.slf4j:slf4j-jdk14:1.7.5')
compile('commons-logging:commons-logging:1.1.1')

删除LoggingApplicationListener和logback.xml没有用。

© www.soinside.com 2019 - 2024. All rights reserved.