What is getCurrentLoggers analogue in log4j2

How can I use all loggers used in log4j2? In log4j, I could use getCurrentLoggers as described here: Number of logs used

+7
java logging configuration log4j log4j2
source share
6 answers

it looks like i found a 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(); 
+4
source share

If you are running a web application, you may have multiple LoggerContext s. See how LoggerConfig exposed through JMX in the class org.apache.logging.log4j.core.jmx.Server .

+2
source share

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

+2
source share

YuriR's answer is incomplete because it does not indicate that LoggerConfig objects are returned , not Logger . This is the fundamental difference between Log4j1 and Log4j2. Loggers cannot be processed correctly in Log4j2. See Log4j2 Architecture for more details .

+2
source share
 LoggerContext ctx = (LoggerContext) LogManager.getContext(false); Collection<? extends Logger> loggers = ctx.getLoggers(); 
0
source share

It is important to note that LoggerConfig objects are returned by getLoggers () and NOT by the registrars themselves. As vacant78 noted, this is only useful for configuring logs that have not yet been created. If you already have a bunch of logs that have already been created, changing the configuration using this method is not useful.

For example, to change the logging level at runtime, refer to this link, which uses the undocumented API in Apache (unsurprisingly), which will change all your currently created logging levels: Programmatically change the log level in Log4j2

0
source share

All Articles