How to log within shutdown hooks with Log4j2?

As of 2.0-beta9 this is now configurable in xml

<configuration ... shutdownHook="disable">

Considering its now disabled, I guess I need to manually shutdown the logging system at the end of my shutdown hook. However I couldn’t find a means thorough the external interface, only in the internal api

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.config.Configurator;
import org.apache.logging.log4j.core.LoggerContext;
...

public static void main(String[] args) {
    final AnnotationConfigApplicationContext springContext = new AnnotationConfigApplicationContext(AppConfig.class)

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            //shutdown application
            LOG.info("Shutting down spring context");
            springContext.close();

            //shutdown log4j2
            if( LogManager.getContext() instanceof LoggerContext ) {
                logger.info("Shutting down log4j2");
                Configurator.shutdown((LoggerContext)LogManager.getContext());
            } else
                logger.warn("Unable to shutdown log4j2");
        }
    });

    //more application initialization
}

Update:

There is LogManager.shutdown() method since log4j version 2.6

Leave a Comment