How to log within shutdown hooks with Log4j2?

前端 未结 2 1719
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-01 14:26

Log4j2 also uses shutdown hooks to end it\'s services. But of course I want to log throughout the whole lifecycle of my application - shutdown included. With Log4j this was

2条回答
  •  不知归路
    2020-12-01 14:55

    As of 2.0-beta9 this is now configurable in xml

    
    

    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

提交回复
热议问题