Number of loggers used

2020-02-11 05:18发布

问题:

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);
}