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
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.
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.
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
Thanks Rodrigo. Glad you found it useful.
Has anyone run into the problem where you've set your threshold to "INFO" but the function "isDebugEnabled" is still returning "TRUE"?
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??
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.
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.
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.
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?
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
where can i find the log files that are logged by using the log4j API.
Where will be the logfiles stored
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 ?
This is one of the few good examples of log4j.xml I have seen. Thanks.
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
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
Was very useful for me
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