Java – how to use log4j2 login to close the hook?

Log4j2 also uses the close hook to end its service But, of course, I want to document the entire life cycle of my application - including shutdown There is no problem using log4j It seems impossible now. My application is still processing logging Does anyone have hope for me?

Best wishes, Martin

Solution

Starting with 2.0-beta 9, it can now be configured in XML

<configuration ... shutdownHook="disable">

Considering that it has been disabled now, I think I need to manually turn off the logging system at the end of my shutdown hook However, I can't find a thorough 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
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>