Logging is an important and pretty useful mechanism for every application. It can help developers to debug and improve their code or test it’s functionality. Apache has made a great work in this field with it’s tool named log4j. You can find more information about it here.
In this post I will provide a quick guide to help you get up and started with log4j. But first of all you’ll have to download the latest version. Once you do, follow the instructions below:
1. Add log4j’s jar(log4j-x.x.xx.jar where x.x.xx is the version of the release you’ve downloaded) file to your application’s classpath.
2. Create a file named “log4j.properties” and place it in the default package of your source code(the root folder where all your code resides). Copy the following lines in it:
# Log levels
# Uncomment the following line to enable full loggin for every class
#log4j.rootLogger=trace, stdout, R
log4j.logger.gr.xfrag=trace, stdout, R
# Console appender configuration
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
# Rolling File Appender
log4j.appender.R=org.apache.log4j.RollingFileAppender
# Path and file name to store the log file.
log4j.appender.R.File=./logs/applog.log
log4j.appender.R.MaxFileSize=500KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1
# Rolling File Appender layout
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d - %c - %p - %m%n
Here is a quick explanation of what the above properties do:
“log4j.logger.xxx” controls the loggers, where xxx is the package for witch you want to set log levels.
The line
log4j.logger.foo.bar=trace, stdout, R
means that you want every class under the foo.bar package to have a logging level of trace, and output the log to the standard output(the console) using a Console Appender named stdout and to a file using a Rolling File Appender named R.
After that you define the appenders I mentioned earlier and set their properties.
The lines
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) – %m%n
define the ConsoleAppender named stdout, set it’s layout to PatternLayout and then assign a pattern for the output.
Following the same procedure the RollingFileAppender is defined, setting some additional properties: the file name of the log, the size of the log and the number of backup files to keep.
3. The third and final step is about the code you’ll have to use. There’s not much to be said, this is the easiest part. Take a look of the class below:
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
public class Main {
private static Logger logger = Logger.getLogger(Main.class);
public static void main(String[] args) {
long time = System.currentTimeMillis();
logger.info("main method called..");
logger.info("another informative message");
logger.warn("This one is a warning!");
logger.log(Level.TRACE,
"And a trace message using log() method.");
long logTime = System.currentTimeMillis() - time;
logger.debug("Time taken to log the previous messages: "
+ logTime + " msecs");
// Exception logging example:
try{
String subs = "hello".substring(6);
}catch (Exception e){
logger.error("Error in main() method:", e);
}
}
}
First you have to import org.apache.log4j.Logger and org.apache.log4j.Level(if you want to use the log() method).
Then instantiate a static Logger object using the static method getLogger() and provide your class as an argument.
To log messages through your class, you use the logging methods of the created Logger object. There are two ways to log messages:
Directly, using the methods trace(), debug(), info(), warn(), error() and fatal(), providing the message as an argument.
Using the log() method, providing the level of the message from the Level class and the message to log as arguments.
According to the configuration you provide in the properties file, a message will be logged – or not. For example, if you set the level to WARN, all messages of level WARN, ERROR and FATAL will be logged and everything else will be omitted. In other words, the hierarchy is:
TRACE < DEBUG < INFO < WARN < ERROR < FATAL.
Now, check out how the appenders output the messages according to their pattern. Here’s what you get at the console when you run the Main class:
INFO [main] (Main.java:12) - main method called..
INFO [main] (Main.java:13) - another informative message
WARN [main] (Main.java:14) - This one is a warning!
TRACE [main] (Main.java:15) - And a trace message using log() method.
DEBUG [main] (Main.java:19) - Time taken to log the previous messages: 0 msecs
ERROR [main] (Main.java:26) - Error in main() method:
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1938)
at java.lang.String.substring(String.java:1905)
at gr.xfrag.loggingexample.Main.main(Main.java:24)
And the same in the log file:
2008-01-10 15:39:46,724 - gr.xfrag.loggingexample.Main - INFO - main method called..
2008-01-10 15:39:46,724 - gr.xfrag.loggingexample.Main - INFO - another informative message
2008-01-10 15:39:46,724 - gr.xfrag.loggingexample.Main - WARN - This one is a warning!
2008-01-10 15:39:46,724 - gr.xfrag.loggingexample.Main - TRACE - And a trace message using log() method.
2008-01-10 15:39:46,724 - gr.xfrag.loggingexample.Main - DEBUG - Time taken to log the previous messages: 0 msecs
2008-01-10 15:39:46,724 - gr.xfrag.loggingexample.Main - ERROR - Error in main() method:
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1938)
at java.lang.String.substring(String.java:1905)
at gr.xfrag.loggingexample.Main.main(Main.java:24)
Besides the formatting differences, notice how long it takes to log those messages – zero milliseconds on my machine. If you ask me, I’ll say that speed is the most impressive feature of log4j..
I hope the above information will help you get started with log4j and logging in general. You can learn more by reading the manual located at log4j’s home page: Log4j Manual
I also uploaded the example code as a NetBeans 6.0 project. Use the following link to download the zip archive:
Log4j Example NetBeans Project
Posted in General
Thanks for this quick introduction!
cheers
moments
Posted at January 15th, 2008 - 2:50 am