2011-04-18

Dynamically changing log4j levels in web application

Log4j is a popular logging library for Java, and I've been using it for many years.

One thing I have found handy, especially with web applications, is the ability to dynamically change the logging level (like to DEBUG) of any category (aka logger) in a running application. I can selectively choose which components I want to change w/o affecting the logging level of other components.

A long time ago, I wrote a servlet to provide this capability, but it requires registering in web.xml and it depends on some utility classes. Although this is generally sufficient, I'm recently working on a project where adding my own custom servlets to the application is awkward, but dropping in a JSP can be done easily. Plus, since servlet engines (e.g. Tomcat) generally support dropping in a JSP at any time, having a JSP allows setting of logging levels w/o having to modify an application's web descriptor.

As a quick hack, I created a JSP version of the servlet, one that is self-contained. The JSP may not be a good example of good JSP coding style since I wanted to spend minimal time in getting things to work. The JSP is self-contained, requiring no external dependencies except log4j.

The JSP can be downloaded from the following location:

http://www.earlhood.com/blogspot/files/log4j.jsp

The interface is simple, but it does the job. When started, it will list out all the logging categories that are currently defined, with each a link to an edit form to change its logging level.

If you need to set the logging level for a category not yet loaded, you can select any other category and then edit the Category field to the category name you desire before submitting the form.

Categories that have their level explicitly set will have the level rendered in bold. Categories that have an inherited value will have the applicable level rendered in italics.