Log4J HOW TO: Enable, Disable or Switch Log4J Logging Level at Run-Time
Question:
How do I enable, disable and switch the logging level between (INFO, WARN, DEBUG, ERROR, FATAL, OFF, ALL) the various levels at run-time in my web application.
Solution :
Most Logging options within Log4J can be done by understanding a few classes such as Logger, LogManager and Level. See JavaDoc here. Some of the useful methods are listed below.
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");
Level lev = Level.toLevel("DEBUG");
logger.setLevel(lev);
Utility:
To help you with the process, I have developed a JSP page that lists all the loggers and you can select and choose the loggers and apply a level of logging and it applies the changes immediatly without restarting. Download the zip and drop the "logger.jsp" into your web app and make sure that the log4j.jar is deployed under /WEB-INF/lib directory. And you goto the URL and you should see something similar to the picture below:
If you have any questions please feel free to contact us via the Aveda Technology Website.
If you found this article helpful, send me an email. Also if you know places (Java Blogs) that you can post a link to this article that would hopefully help others in locating this article.
Created By: Venkatt Guhesan at Aveda Technology, Inc.
Last Updated: Thursday, August 28, 2005.
Happy Coding!!!