我有一个项目,我需要在启动SpringApplication之前使用日志记录机制。我怎样才能做到这一点?
我尝试设置自己的日志记录机制(LogManager.getLogManager()。readConfiguration()),但是当spring应用程序启动时它会被覆盖。
基本上我想在任何地方使用相同的日志记录机制。
答案 0 :(得分: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);
}
}
答案 1 :(得分: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开始之前就已经开始了。
答案 2 :(得分:0)
我设法通过删除&#34; spring-boot-starter-logging&#34;来解决我的问题。从我的项目中依赖并添加&#39; org.slf4j:slf4j-jdk14:1.7.5&#39;和&#39; commons-logging:commons-logging:1.1.1&#39;。
我使用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没有用。