How to use log4j logging API
January 8th, 2008 by Christos Fragoulides

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

moments

Thanks for this quick introduction!

cheers
moments

Posted at January 15th, 2008 - 2:50 am

Kiran Venkatarao

The NetBeans project was an amazing example, I browsed through many sites including Sun forums and Java Ranch sites, but none gave a fully working example as you have.
Thanks a million.

– Kiran V

Posted at April 5th, 2008 - 4:47 pm

theoracle1001

Good, quick introduction. Liked it very much. Keep them coming.

Posted at September 29th, 2008 - 3:17 am

Kavitha Kannan

Very Simple and easy to use. Thanks for giving such a good example.

- Kavitha.R

Posted at October 12th, 2008 - 10:30 pm

Dips

Excellent way to explaining.. Keep it up

Posted at October 17th, 2008 - 1:44 pm

mjb

Thanks for the quick and concise intro.

Posted at December 29th, 2008 - 4:55 pm

AG

Simple but effective explanation of a complex topic. Great work!

Posted at January 8th, 2009 - 10:17 am

kaviarasu

Thanks xfrag. It is really helpful.

Posted at March 7th, 2009 - 1:28 pm

Rakesh

Very useful article. thanks

Posted at May 8th, 2009 - 12:00 am

pankaj kumar gupta

Very useful and simple article for understanding log4j. Thanks.

Posted at August 1st, 2009 - 4:08 am

Vijayanand.D

Excellent guide for the beginners…. Very much usefull…. Good work and Thank You.

Posted at September 21st, 2009 - 11:44 pm

Sivambigai.M

Thanks for your guide..very nice and simple.

Posted at November 17th, 2009 - 9:26 pm

Muhammad Tariq Khan

I would just say.. Perfectly understandable.
Great job…

Posted at December 21st, 2009 - 6:35 am

varun

Helped me :)
Thanks a lot..

Posted at January 20th, 2010 - 1:54 pm

anil

Very good log4j explanations with examples.
Great work.

Posted at February 14th, 2010 - 7:54 pm

vivek

Really helps me ….

1)where to use the LogRecord class in log4j.
2)If the log file(Demo1.log) is filled up ,then how can it create and use the another log file(Demo2.log)

Posted at August 6th, 2010 - 5:23 am

Abdul Mannan

Nice tutorial.

Posted at November 12th, 2010 - 12:31 am

Farhaan

I want to know about conversion pattern string. I mean what it means 5p [%t] (%F:%L) – %m%n or =%d – %c – %p – %m%n

Posted at January 5th, 2011 - 10:05 pm

How to create a instance for logger?

[...] 4j..i dunno how to create a instance this logger can you guide me Have a look at this article : How to use log4j logging API Hope that helps, [...]

Posted at June 3rd, 2011 - 6:45 am

xfrag

Farhaan, take a look at this page: PatternLayout, you can find all the information you need there.

Posted at June 15th, 2011 - 3:43 pm

gourav garg

Ultimate code mast

Posted at August 26th, 2011 - 12:20 am

sumit

Nice Intro! Thank you so much!

Posted at October 10th, 2011 - 1:44 am

Madhusudan Suryanarayanan

Thanks a lot for the quick intro xfrag. It was very helpful. :) :)

Posted at December 9th, 2011 - 7:38 am

Sumit Khanna

I tried this code and followed the steps mentioned.. Although i am able to print my log message on the console, but nothing goes into the .log file.

Posted at January 5th, 2012 - 11:09 am

Christos Fragoulides

Hey Sumit, most probably you are missing something in your configuration file. Make sure there is no misspelling in the ‘log4j.properties’ file name, that it is located in the default package, etc..
Download and check the linked NetBeans project (at the end of the post), it should work as-is.

Posted at January 17th, 2012 - 8:51 am

Amol

Helped us a lot in setting some basic logs.

Posted at May 24th, 2012 - 4:00 am

Priya

Excellent post. I learnt logging information from this post only long back.Just completed a blog post on the same topic with an example implemented using Eclipse IDE and a little more information with screenshots here.

Posted at July 21st, 2012 - 11:42 am

Diem

Very useful for me. Thanks a lot

Posted at August 22nd, 2012 - 3:47 am

Stan

Great, thanks!

Posted at October 23rd, 2012 - 12:24 pm

Surya Chandra

Impressive tutorial to start with Logging and log4j. Thanks for the explanation

Posted at January 28th, 2013 - 11:51 pm

Log4j FastTrack | itsraja4u

Posted at February 24th, 2013 - 9:55 am

Mayur

Thanks A Lot….

Posted at July 21st, 2013 - 8:16 pm

Post a Comment Below »
Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.

Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries.