每当Spring Boot应用程序即将启动时,我都会尝试进行一些日志记录。
目前我有一个实现ApplicationEnvironmentPreparedEvent
的类,我在SpringBootApplication
的主函数中将其注册为监听器。
Application.java:
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
private static final Logger appLogger = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) {
System.out.println("INIT");
appLogger.info("Initializing");
SpringApplication sa = new SpringApplication();
sa.addListeners(new InitializationLogger());
sa.setSources(new HashSet<>(Collections.singletonList(Application.class)));
sa.run(args);
appLogger.info("--Application Started--");
}
}
InitializationLogger.java
public class InitializationLogger implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {
private static final Logger appLogger = LoggerFactory.getLogger(InitializationLogger.class);
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
System.out.println(event.getClass());
appLogger.info(this.getClass().getName());
}
}
问题是每当我通过Intellij的SpringBoot运行程序或命令行作为胖jar运行应用程序时,它运行得很好,但是当我将它部署到外部Tomcat时,这些日志不会显示(所有其他应用程序)日志工作正常)。
我该怎么做?
答案 0 :(得分:2)
我该怎么做?
覆盖SpringBootServletInitializer.configure,例如:
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
private static final Logger appLogger = LoggerFactory.getLogger(Application.class);
// for JAR deploy:
public static void main(String[] args) {
SpringApplicationBuilder builder = configureSpringBuilder(new SpringApplicationBuilder());
builder.application().run(args);
appLogger.info("--Application Started--");
}
// for WAR deploy:
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return super.configure(configureSpringBuilder(builder));
}
// Common:
private static SpringApplicationBuilder configureSpringBuilder(SpringApplicationBuilder builder) {
System.out.println("INIT");
appLogger.info("Initializing");
builder.application().addListeners(new InitializationLogger());
builder.application().setSources(new HashSet<>(Collections.singletonList(Application.class)));
return builder;
}
}
配置应用程序要么覆盖configure(SpringApplicationBuilder)方法(...)
要将应用程序设置为servlet,我们使用SpringBootServletInitializer扩展主类,并使用SpringApplicationBuilder覆盖configure方法。
因此修改您的应用程序入口点类(...)