Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

Log4j delivers control over logging

The open source log4j API for Java offers fast, efficient log services

  • Print
  • Feedback
Almost every large application includes its own logging or tracing API. Experience indicates that logging represents an important component of the development cycle. As such, logging offers several advantages. First, it can provide precise context about a run of the application. Once inserted into the code, the generation of logging output requires no human intervention. Second, log output can be saved in a persistent medium to be studied at a later time. Finally, in addition to its use in the development cycle, a sufficiently rich logging package can also be employed as an audit tool.

In conformance with that rule, in early 1996 the EU SEMPER (Secure Electronic Marketplace for Europe) project decided to write its own tracing API. After countless enhancements, several incarnations, and much work, that API has evolved into log4j, a popular logging package for Java. The package is distributed under the IBM Public License, certified by the open source initiative.

Logging does have its drawbacks. It can slow down an application. If too verbose, it can cause scrolling blindness. To alleviate those concerns, log4j is designed to be fast and flexible. Since logging is rarely the main focus of an application, log4j API strives to be simple to understand and use.

This article starts by describing the main components of the log4j architecture. It proceeds with a simple example depicting basic usage and configuration. It wraps up by touching on performance issues and the upcoming logging API from Sun.

Categories, appenders, and layouts

Log4j has three main components:

  • Categories
  • Appenders
  • Layouts


The three components work together to enable developers to log messages according to message type and priority, and to control at runtime how these messages are formatted and where they are reported. Let's look at each in turn.

Category hierarchy

The first and foremost advantage of any logging API over plain System.out.println resides in its ability to disable certain log statements while allowing others to print unhindered. That capability assumes that the logging space, that is, the space of all possible logging statements, is categorized according to some developer-chosen criteria.

In conformance with that observation, the org.log4j.Category class figures at the core of the package. Categories are named entities. In a naming scheme familiar to Java developers, a category is said to be a parent of another category if its name, followed by a dot, is a prefix of the child category name. For example, the category named com.foo is a parent of the category named com.foo.Bar. Similarly, java is a parent of java.util and an ancestor of java.util.Vector.

The root category, residing at the top of the category hierarchy, is exceptional in two ways:

  1. It always exists
  2. It cannot be retrieved by name


In the Category class, invoking the static getRoot() method retrieves the root category. The static getInstance() method instantiates all other categories. getInstance() takes the name of the desired category as a parameter. Some of the basic methods in the Category class are listed below:

package org.log4j;
public Category class {
   // Creation & retrieval methods:
   public static Category getRoot();
   public static Category getInstance(String name);
   // printing methods:
   public void debug(String message);
   public void info(String message);
   public void warn(String message);
   public void error(String message);
   // generic printing method:
   public void log(Priority p, String message);
}


Categories may be assigned priorities from the set defined by the org.log4j.Priority class. Although the priority set matches that of the Unix Syslog system, log4j encourages the use of only four priorities: ERROR, WARN, INFO and DEBUG, listed in decreasing order of priority. The rationale behind that seemingly restricted set is to promote a more flexible category hierarchy rather than a static (even if large) set of priorities. You may, however, define your own priorities by subclassing the Priority class. If a given category does not have an assigned priority, it inherits one from its closest ancestor with an assigned priority. As such, to ensure that all categories can eventually inherit a priority, the root category always has an assigned priority.

To make logging requests, invoke one of the printing methods of a category instance. Those printing methods are:

  • error()
  • warn()
  • info()
  • debug()
  • log()


By definition, the printing method determines the priority of a logging request. For example, if c is a category instance, then the statement c.info("..") is a logging request of priority INFO.

A logging request is said to be enabled if its priority is higher than or equal to the priority of its category. Otherwise, the request is said to be disabled.. A category without an assigned priority will inherit one from the hierarchy.

Below, you'll find an example of that rule:

// get a category instance named "com.foo"
Category  cat = Category.getInstance("com.foo");
// Now set its priority.
cat.setPriority(Priority.INFO);
Category barcat = Category.getInstance("com.foo.Bar");
// This request is enabled, because WARN >= INFO.
cat.warn("Low fuel level.");
// This request is disabled, because DEBUG < INFO.
cat.debug("Starting search for nearest gas station.");
// The category instance barcat, named "com.foo.Bar",
// will inherit its priority from the category named
// "com.foo" Thus, the following request is enabled
// because INFO >= INFO.
barcat.info("Located nearest gas station.");
// This request is disabled, because DEBUG < INFO.
barcat.debug("Exiting gas station search");


Calling the getInstance() method with the same name will always return a reference to the exact same category object. Thus, it is possible to configure a category and then retrieve the same instance somewhere else in the code without passing around references. Categories can be created and configured in any order. In particular, a parent category will find and link to its children even if it is instantiated after them. The log4j environment typically configures at application initialization, preferably by reading a configuration file, an approach we'll discuss shortly.

  • Print
  • Feedback

Resources