I'm working on a very large java application with log4j, and I was wondering if there is a way to extract in runtime the number of active loggers? Or what are the existing loggers in the application? My end goal is to get a list of all loggers and change their level in runtime. Thank you.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
You could try something like:
Enumeration allLoggers = Logger.getRootLogger()
.getLoggerRepository()
.getCurrentLoggers();
Then iterate over allLoggers.
回答2:
to get the loggers use one of these
Logger rootLogger = LogManager.getRootLogger(); //To get the Root Logger
Enumeration e = LogManager.getCurrentLoggers(); //To get an enumerated list of loggers
rootLogger.getName(); //To get the logger by name
rootLogger.getEffectiveLevel().toString(); //To get the effective level of the current logger
logger.getParent(); //Get the ccurrent loggers' parent
//To set a new level for a particular Logger
Logger logger = Logger.getLogger("TestLogger");
L evel lev = Level.toLevel("DEBUG");
to set use this:
logger.setLevel(lev);
回答3:
Or you can simply use the LogManager.getCurrentLoggers()
to return a Logger Enumeration
.Loop through it and set the Logger
's level by setLevel()
for (Enumeration<Logger> loggerEnumeratin = LogManager.getCurrentLoggers() ;loggerEnumeratin.hasMoreElements() ;){
Logger logger = loggerEnumeratin.nextElement();
logger.setLevel(Level.ERROR);
}