More Java posts
October 16, 2002
Simple log4j configuration

Log4j is an excellent logging package for Java. I've been using it since version 0.7.4 in early 2000 and we use it at work for all our logging. Presenting the information below may seem to many log4j users like teaching your grandmother to suck eggs but I think it's useful so I though I'd write it down.

Log4j's free documentation is good for describing the various configuration and logging choices you can make but doesn't present any task based or how-to information. This note describes a simple log4j setup that uses four files to record debug, informational, warning and error messages. The debug file will contain all messages, the informational file only informational, warning and error messages, the warning file only warnings, and errors and the error file only errors.

In each Java source file I define a private static final Logger instance and use that for logging. Using the class the logger is in as the value for the getLogger method means each class gets it's own Logger instance, and the logger hierarchy parallels the class hierarchy. This gives you good information about where messages are coming from and good control over which ones are logged. So in a class called Test I'd use:

private static final Logger log =
    Logger.getLogger(Test.class);

When logging a debug or info message it's good practice to preceed each with a test using the isDebugEnabled or isInfoEnabled method. This will save you cycles later when debug or info messages are disabled, especially if the message being logged includes objects that are expesive to compute. For example:

	if (log.isDebugEnabled())
	    log.debug("A Debug Message");

In the log4j configuration file the first stage is to define four appenders, one for each output file. If this file is named log4j.xml and is on the classpath then it is found automatically by log4j when it is needed. Use the threshold parameter to limit the messages that are written to the file. As threshold is a property of the AppenderSkeleton class the same technique should work for any appender. Here's the definition of the DEBUG appender.

<appender name="DEBUG" class="org.apache.log4j.FileAppender">
  <param name="File" value="logs/debug.log" />
  <param name="Threshold" value="DEBUG" />
  <layout class="org.apache.log4j.PatternLayout">
    <param name="ConversionPattern"
	value="%d{ISO8601} %-5p %c - %m%n"/>
  </layout>
</appender>

After all of the appenders the lowest level logger to be controlled is defined. It is associated with all four appenders so that all messages sent to the logger are presented to all appenders. As explained in the log4j manual appenders are additive Each enabled logging request for a given logger will be forwarded to all the appenders in that logger as well as the appenders higher in the hierarchy. So the single logger definition below will see messages logged by any loggers in the com.zanthan hierarchy.

<logger name="com.zanthan">
  <level value="debug"/>
  <appender-ref ref="DEBUG"/>
  <appender-ref ref="INFO"/>
  <appender-ref ref="WARN"/>
  <appender-ref ref="ERROR"/>
</logger>

You can turn on or off logging of various levels by class or package by adding extra logger entries. For example the entry below will meant that classes whose names start with com.zanthan.xsltxt will only output warning and error messages.

<logger name="com.zanthan.xsltxt">
  <level value="warn"/>
</logger>
Posted by Alex at October 16, 2002 07:12 PM
Comments
The isDebugEnabled suggestion is a valid one but should be better qualified. The logger obviously does level checking so your isDebugEnabled could end up being an isDebugEnabled wrapper on a call to isDebugEnabled: this adds noise with virtually no performance gain. I would only use an isDebugEnabled when you do have an expensive string to create: as you have pointed out that is definitely useful. Posted by: Barney on December 6, 2002 07:44 AM
Possibly. I just tend to stick isDebugEnabled in anywhere. The overhead is very small and in those places where it does make a difference I'm going to rip the debug code out anyway when I find out it's a hot spot. Posted by: Alex on December 6, 2002 09:57 PM
VERY useful and FAST guide to teach us how to write log files. Got the idea in like 15 minutes after like a 5 hour reading on those jakarta docs Thank you Rodrigo Posted by: Rodrigo on June 9, 2003 10:02 AM
Thanks Rodrigo. Glad you found it useful. Posted by: Alex on June 11, 2003 10:44 PM
Has anyone run into the problem where you've set your threshold to "INFO" but the function "isDebugEnabled" is still returning "TRUE"? Posted by: Chris on June 17, 2003 01:00 PM
How do you get around the file not found exception for the log files? Is there a way to have log4j auto-create the files if they don't exist?? Posted by: craigm on June 19, 2003 04:57 PM
Craig. Log4j should create the log files if they don't exist. What it won't do is create the directory they should be in if that's not there. This is generally the problem I have. Chris. I've not seen this problem. I'd guess misconfiguration, perhaps, though I'm sure you've look at the config lots of times. The way the levels cascade might be the issue. Posted by: Alex on June 24, 2003 08:40 PM
Hi same help please a. Write down a partial definition of a class Employee which contains variables to represent the following: · Company name; · Department name; · Number of years service; · Payroll number. b. Give an example of class method and an instance method which illustrate the difference between the tow type. Posted by: Gramos on September 5, 2003 10:42 AM
hi can you give some help in this question please a. Write down a partial definition of a class Employee which contains variables to represent the following: · Company name; · Department name; · Number of years service; · Payroll number. b. Give an example of class method and an instance method which illustrate the difference between the tow type. Posted by: Romeo on September 5, 2003 10:46 AM
This article has been very insightful, however the log files are not created no matter what I tried. There seems to be 2 issues: Where should the 'logs' directory mentioned in log4j.xml be located? I understand I should create it myself, but I can't figure out where. Trying to use a configuration without a directory (ommitting the "logs/" in log4j.xml) I made a small progress, now I'm getting FileNotFoundException but the files are not stored. Help? Posted by: Ophir on August 10, 2004 03:16 PM
In the lines above, how do I read the name of the log file "logs/debug.log" in my Java program? I've tried using the DOMParser but once I get to the node appender name = DEBUG, I cannot figure out how to read the param values. Any help will be greatly appreciated. SR Posted by: SRChow on April 12, 2005 04:15 PM
where can i find the log files that are logged by using the log4j API. Posted by: paramesh on October 24, 2005 06:13 AM
Where will be the logfiles stored Posted by: sathish on October 24, 2005 06:14 AM
Good article. There appears to be little on using xml config files. I am looking at using log4j instead of java.util.logging.Logger in an apache/tomcat environment. One problem that I have found so far is that Exceptions get written to catalina.out instead of the applications log file. How can I override this ? Posted by: bill on January 6, 2006 10:36 AM
This is one of the few good examples of log4j.xml I have seen. Thanks. Posted by: Guy on March 30, 2006 08:04 PM
Question: Is there a way to set different log levels in different appenders for the same package? Ex: I want to log INFO (Just info only) for package com.foo in appender info_log, also, I want to log ERROR(Just error only) for package com.foo in appender error_log? Thanks joe Posted by: Joe on June 15, 2006 11:29 AM
in production, once the applicaton server crashdown, after restaring, log4j is not writting logs where isEnableInfo() is checked but writing logs when this condition is not checked, what might have gone wrong after restarting server? log4j.xml and other setting are still them same, before and after app server crash. Thanks Posted by: Naveen on July 17, 2006 06:00 AM
Was very useful for me Posted by: Faisal Faizan on August 7, 2006 04:12 AM
I hav just started working with logj.I hav some prob.I hav set all the classpath and also writen a sample prog.it compiled successfully but at run time giving an error java.lang.noclassdeffounderror:(class name) and also i m not finding log4j.xml. i hav build.xml in my log4j folder.Is these two r same?pls help Posted by: sumit on December 7, 2006 02:12 AM
Post a comment
Name:


Email Address:


URL:


Comments:


Remember info?