What is getCurrentLoggers's analog in log4j2

天大地大妈咪最大 提交于 2019-12-10 02:32:05

问题


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:


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




回答4:


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.




回答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



来源:https://stackoverflow.com/questions/17511763/what-is-getcurrentloggerss-analog-in-log4j2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!