Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I configure startup and shutdown logs for Spring Boot applications?

For the ability to verify the startup and shutdown of our Spring Boot applications we want to configure a startup.log and shutdown.log capturing events that bootstrap and shutdown the application.

For startup everything up to:

Root WebApplicationContext: initialization completed in {x} ms

And for shutdown everything from:

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

to the end.

Is this something that is container specific? (Tomcat vs Jetty vs Undertow)

like image 489
Anthony Ikeda Avatar asked Dec 09 '22 01:12

Anthony Ikeda


2 Answers

We use @PostConstruct and @PreDestroy to log startup and shutdown:

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

}
like image 42
Michael Avatar answered May 16 '23 09:05

Michael


You can create an event listener that watches for ApplicationReadyEvent and ContextStoppedEvent and log whatever you want.

@Service
public class Foo {

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

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

}
like image 145
Stephane Nicoll Avatar answered May 16 '23 08:05

Stephane Nicoll