Monday, August 20, 2007

Log4J all over again

I've not had to do Log4J configuration since before the time of the introduction of log4j.xml. Before that I used the simple log4j.properties variation.

But now, since I've run across an application using lo4j.xml I've had to learn how to configure Log4J using it. Initially, I thought "Argh" but as it turns out, it's not as bad as I had feared.

Having searched high and low on the internet, I found a lot of sites on the subject on log4j configuration. Some sites were good and other sites were not so good. All of them were broad; explained everything and then some. None offered real clarity. This was probably due to my impatience from just wanting a 1, 2, 3... list.

The log4j.xml file

Briefly, there's a layout to log4j.xml, shown below.


1. The class file
This is where the sequence of events begin. Somewhere, usually at the class level or perhaps in the constructor, you're going to have an entry such as this:

Logger log = Logger.getLogger(name);

The name may appear to be arbitrary, but its actual value is important. This is because it is linked to a named logger defined in log4j.xml. Many examples show the getLogger() method like this:

Logger log = Logger.getLogger(this.getClass().getName() );

Documentation such as this is a dis-service to both you and Log4j. The fact is that when getting a logger using the above approach returns the named logger only if one has been defined! If a logger having this name is not defined in log4j.xml a new logger instance will be created. Consequently, log entries will be sent to ALL log-files in your application. If you only have one then the problem is masked. Needless to say this approach should be avoided. Stick with names that are associated with named loggers you have defined in log4j.xml and your logging output to the correct log files will be much more predictable. Under this approach, you should expect to see something like this throughout your application:

Logger log = Logger.getLogger("Example_Logger");

Using named loggers you can create a separate set of log-files designed to contain entries for a given process.

2. Log4J looks-up the Logger Definition
Using the name ("Example_Logger") Log4J looks up logger information that were described using Logger Definitions.

From this lookup, Log4J obtains the name of the Appender.

3. Appender Definitions
Logger Definitions "point-to" Appenders which are described using Appender Definitions. Among other things, Appender Definitions define the log-file (and the filtering logging level) used to receive entries.


4. The Root Definition
The Root definition is used to define which logger is to descend from Log4J's root logger.

No comments: