What is getCurrentLoggers's analog in log4j2

2019-04-25 11:50发布

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

6条回答
老娘就宠你
2楼-- · 2019-04-25 12:33

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();
查看更多
Anthone
3楼-- · 2019-04-25 12:36

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.

查看更多
祖国的老花朵
4楼-- · 2019-04-25 12:38
LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
Collection<? extends Logger> loggers = ctx.getLoggers();
查看更多
兄弟一词,经得起流年.
5楼-- · 2019-04-25 12:42

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

查看更多
我想做一个坏孩纸
6楼-- · 2019-04-25 12:54

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.

查看更多
聊天终结者
7楼-- · 2019-04-25 12:57

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

查看更多
登录 后发表回答