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

3

7

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)

Adelina answered 19/8, 2015 at 16:50 Comment(0)
L
11

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) { .... }

}
Leghorn answered 20/8, 2015 at 5:48 Comment(0)
L
7

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

}
Levitt answered 6/7, 2018 at 7:14 Comment(0)
T
6

You can combine EventListener with ApplicationReadyEvent and ContextStoppedEvent.

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

Note: Answer provided by Stephane Nicoll does contain the same (correct) information, but I wanted to provide an valid Java example.

Tricuspid answered 15/2, 2017 at 12:57 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.