What is getCurrentLoggers's analog in log4j2

2019-04-25 12:48发布

问题:

How can i get all loggers used used in log4j2? In log4j i could use getCurrentLoggers like described here: Number of loggers used

回答1:

looks like i've found the way:

File configFile = new File("c:\\my_path\\log4j2.xml");
LoggerContext loggerContext = Configurator.initialize("my_config", null, configFile.toURI());
Configuration configuration = loggerContext.getConfiguration();
Collection<LoggerConfig> loggerConfigs = configuration.getLoggers().values();


回答2:

YuriR's answer is incomplete in that it does not point that LoggerConfig objects are returned, not Logger. This is the fundamental difference between Log4j1 and Log4j2 - Loggers cannot be dirrectly manipulated in Log4j2. See Log4j2 Architecture for details.



回答3:

If you are running in a web app, you may have multiple LoggerContexts. Please take a look at how LoggerConfigs are exposed via JMX in the org.apache.logging.log4j.core.jmx.Server class.



回答4:

get all loggers used in log4j2:

LoggerContext logContext = (LoggerContext) LogManager
                .getContext(false);
Map<String, LoggerConfig> map = logContext.getConfiguration()
                .getLoggers();

Attention:

use org.apache.logging.log4j.core.LoggerContext

not org.apache.logging.log4j.spi.LoggerContext



回答5:

LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
Collection<? extends Logger> loggers = ctx.getLoggers();


回答6:

It's important to note that LoggerConfig objects are being returned by getLoggers() and NOT the loggers themselves. As vacant78 pointed out, this is only good for setting the configuration for loggers that have yet to be instantiated. If you already have a bunch of loggers already instantiated, changing the configuration using this method does no good.

For example, to change the level of logging at runtime, refer to this link, which utilizes an undocumented API within Apache (no surprise there) that will change all your currently instantiated logger levels: Programmatically change log level in Log4j2