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

Spring boot setup logging before spring application starts

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

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

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

您可以在 web.xml 而不是 spring-context.xml

中配置 Log4j 侦听器
<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 开始之前就已经启动了。

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);
    }

}

我设法通过从我的项目中删除 "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 无效。