How to restart log4j2 after call LogManager.shutdo

2019-05-11 08:07发布

问题:

I have a method to reconfig log4j2 like this:

LogManager.shutdown(); // SHUTDOWN log4j2
    InputStream in = getClass().getResourceAsStream("/my2ndLog4j2.xml");
    ConfigurationSource source = new ConfigurationSource(in);
    Configurator.initialize(null, source);
    LoggerContext context = (LoggerContext) LogManager.getContext(false);
    context.reconfigure();
    context.start(); // NOT WORK, no log appear anymore...

So I can reconfig log4j2 between production log config and development config at runtime, but when I call LogManager.shutdown(), it really SHUTDOWN forever, never get back, context.start() is not work, infact I do this in log4j1.x for long time, in log4j1.x, use:

org.apache.log4j.PropertyConfigurator.configure(cfgPath);

then it get back, but how log4j2?

回答1:

If you want to change log4j2 configuration file at runtime, then below code is sufficient to do so -

Configurator.initialize(null, "my2ndLog4j2.properties");

There is no need to shutdown LogManager and then starting it again.



标签: log4j2