我可以为Spring Boot应用程序配置启动和关闭日志吗?

7
为了验证我们的Spring Boot应用程序的启动和关闭能力,我们希望配置一个startup.log和shutdown.log,以捕获引导和关闭应用程序的事件。
启动时,我们需要记录以下所有内容:
Root WebApplicationContext: initialization completed in {x} ms

关机时需要关闭所有内容:

Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@53bd8fca: startup date [Wed Aug 19 09:47:10 PDT 2015]; root of context hierarchy

到最后。

这是特定于容器的吗?(Tomcat vs Jetty vs Undertow)

3个回答

11

您可以创建一个事件监听器,用于观察 ApplicationReadyEventContextStoppedEvent 并记录您想要的任何内容。

@Service
public class Foo {

    @EventListener
    public void onStartup(ApplicationReadyEvent event) { ... }

    @EventListener
    public void onShutdown(ContextStoppedEvent event) { .... }

}

7
我们使用@PostConstruct@PreDestroy来记录启动和关闭日志:
package hello;

import java.util.Arrays;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    @PostConstruct
    public void startupApplication() {
        // log startup
    }

    @PreDestroy
    public void shutdownApplication() {
        // log shutdown
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

6
你可以将EventListenerApplicationReadyEventContextStoppedEvent相结合。
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.ContextStoppedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component
class StartupShutdownEventListener {

  @EventListener
  void onStartup(ApplicationReadyEvent event) {
    // do sth
  }

  @EventListener
  void onShutdown(ContextStoppedEvent event) {
    // do sth
  }
}

注意:Stephane Nicoll提供的答案包含相同(正确)的信息,但我想提供一个有效的Java示例。


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