Search code examples
log4j2shutdown-hook

Programmatically disabling shutdown hook in log4j 2


It's possible to disable shutdown hooks in log4j2 via configuration:

<Configuration shutdownHook="disable">

Is it possible to do so programmatically?


Solution

  • I know, it's probably outdated but I felt on your question and I was in the same situation. So for people interested, I use this piece of code to stop the shutdown hook programmaticaly :

    final LoggerContextFactory factory = LogManager.getFactory();
    
    if (factory instanceof Log4jContextFactory) {
        LOG.info("register shutdown hook");
        Log4jContextFactory contextFactory = (Log4jContextFactory) factory;
    
        ((DefaultShutdownCallbackRegistry) contextFactory.getShutdownCallbackRegistry()).stop();
    }
    

    and in my own shutdown hook

    LogManager.shutdown();
    

    log4j2: 2.8.2 (but should be available since 2.6)