home

Log4j Tutorial : Adding Log4j logger to your project

July 26, 2009 · 28 comments

Hi there! I have created a small eBook explaining about Log4j logger and appenders. Download the Log4j PDF (200 KB)

If you are new to Log4j, here is a short description on what is it and why should we care about it:

Log4j is a flexible logging library, an open source project from Apache. Using Log4j, we can replace the debugging print line statements, like System.out.println(“Value is ” + someVariable), with a configurable logging statement like logger.debug(“Value is ” + someVariable). The advantage in using Log4j is, if you do not want to print the debugging print lines in production application, you can easily switch them off using Log4j configuration file (which we will see it how, shortly).

How to add Log4j logger support to your project?

  1. Download the latest Log4j distribution from Apache website (at the time of this article is written, the latest version of Log4j is 1.2) and put the log4j-xxx.jar in your project class path. For Java web application, you can place the jar file in WEB-INF/lib folder. For Java applications, you can place the jar in any folder, but remember to add the folder to your classpath.
  2. Next we need to configure the Log4j library to our requirements. Log4j reads its configurations from log4j.properties file (or log4j.xml) placed in the CLASSPATH. Every log4j.properties file defines the following three things, mainly:
    • an Log4j Appender – this is the class file which does the actual logging. It could be a simple Console appender which writes  the log messages to stdout (screen) or a file appender, which sends the log messages to a log file.
    • a Layout – is nothing but how the log message is formatted. This format is very simlar to C languages’s printf function formatting.
    • and a Logger – a logger ties the appender with the log messages that are coming from the Java application. Basically, a logger tells that the log messages from these packages should go to some appender which will log the message in the defined layout.
  3. Below is a sample log4j.properties for configuring the console appender for your project.
    #define the console appender
    log4j.appender.consoleAppender = org.apache.log4j.ConsoleAppender
    
    # now define the layout for the appender
    log4j.appender.consoleAppender.layout = org.apache.log4j.PatternLayout
    log4j.appender.consoleAppender.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
    
    # now map our console appender as a root logger, means all log messages will go to this appender
    log4j.rootLogger = DEBUG, consoleAppender

    In the above properties file, we are first defining a Console appender and a layout pattern (refer this complete documentation to know what’s the weired symbols in the conversion patterns means). Then we are mapping all the DEBUG level log messages from the entire application to go into the consoleAppender, since we added the consoleAppender to the rootLogger.

  4. In any of your Java file, add the below lines, in order to start logging:
    private static Logger logger = Logger.getLogger(MyclassName.class);
    logger.debug("this is a sample log message.");
  5. Now you are done. Run your application and you should be seeing the log messages coming in your console window.

Next: How to send log messages to a file?

Related Posts

{ 25 comments… read them below or add one }

vishnu July 27, 2009 at 9:50 AM

Nice description.
.-= vishnu´s last blog ..??? ????? ?????? =-.

Reply

huu2uan August 6, 2009 at 1:28 PM

nice tut :)

Reply

Veera August 6, 2009 at 10:32 PM

thanks!

Reply

huu2uan August 6, 2009 at 1:36 PM

so, what’s about java.util.logging, log4j vs jul ?

Reply

Veera August 6, 2009 at 10:35 PM

I’ve never used any logging frameworks, other than log4j. Even I would like to learn about java.util.logging. Will try to publish tutorial for that also.

Reply

Ceki Gulcu August 9, 2009 at 7:48 PM

Have a look at logback, log4j’s successor. It’s very similar to log4j but better.

Reply

Veera August 9, 2009 at 9:21 PM

logback looks impressive. Will definitely give it a try.

Reply

Ceki Gulcu August 9, 2009 at 9:36 PM

Good. If you look closely, I am confident that you will find at least one cant-live-without feature that will have you prefer logback over log4j.

Reply

Anand Kanagaraj September 24, 2009 at 12:10 AM

Hi Veera,

Your explanations made me to understand log4j quickly.
Please explain how the following can be achieved.

1) Seperate log file for each java class
2) Log files getting created must be stored in datewise folder.

Reply

huu2uan November 13, 2009 at 11:03 PM

nice tut :)

Reply

Tsering Shrestha February 11, 2010 at 8:35 PM

Any comments on SLF4J static binding with log4j or other logging frameworks? And also about how to NOT use commons-logging. Very often my profiling tools show that logging is the one place I am using too much time.
Oftentimes I end up doing something like the following:
if(currently active logging level > INFO) {
logger.info(String.format(“…..”,…);
}

Reply

vijay kumar September 18, 2010 at 8:54 PM

thanks and its simple to understand in the same way in there any bugs means errors will coming configuration and run in project explian how it will be handled.
some possible errors and how it will be handled………..
once again thanks

Reply

suarabh agrawal October 22, 2010 at 1:46 PM

quick and easy….
thanks veera…

Reply

ramu November 16, 2010 at 10:57 AM

could u tell me how can we work with log4j in eclipse

Reply

Veera November 16, 2010 at 11:53 AM

There are no special instructions for Eclipse alone. You can download the log4j jar, put it somewhere in your file system. Then, in Eclipse, right click on your project name and go to properties. there you can add the log4j JAR file to CLASSPATH.

Once that is done, follow the steps mentioned in this post and then you should be able to log message.

let me know in case you need any help.

Reply

ramu November 17, 2010 at 9:55 AM

thanks

Reply

ramu November 17, 2010 at 11:30 AM

hey sunder ,
i am new to eclipse. i had developed a simple project and build the project with ANT s/w.in the build i made a target to build a jar file. can u please tell me where i can find that jar file where i have developed.
give the details in a step by step process.thanks for ur last reply

Reply

Veera November 17, 2010 at 2:49 PM

Ramu,

in your build.xml file you would be having a target to build JAR file, something like: <jar destfile="build/jar/HelloWorld.jar" basedir="build/classes"> : in this case, the JAR file will be created in the directory PROJECT BASE DIRECTORY/build/jar/ and HelloWorld.jar

Reply

7a2i5wat February 7, 2011 at 7:52 AM

Hey Veera,

I have been trying to log my application, but it is still not working. I have the log4j.properties file configured right as you explained in one of the other posts, but I still can’t get the appender to write to the file I specify. It writes to the console in Eclipse instead. Also, the logger instantiation:

private static Logger logger = Logger.getLogger(MyclassName.class);

does not seem to work in my Java class, the syntax error I get is that Logger.getLogger method has a string argument so it should be Logger.getLogger(String subsystem), so what I did is just put in my clasess’s name (one i want to log) as a string argument. Can this be the problem for not getting the logger to write in the specified file? Any help is appreciable.

Thanks,

Reply

Veera February 7, 2011 at 8:00 PM

If you are getting the syntax error at Logger.getLogger, it might be because the compiler can’t find the log4j JAR file in CLASSPATH. From your comment, I guess that you are using Java’s Logger utility , which is different from Log4j and takes a String as an argument.

Please verify whether you have added the log4j.jar file to the class path and ensure that you have imported the Log4j Logger from by checking the import statements. It should be something like this.

import org.apache.log4j.Logger;

Reply

Pavan Kulkarni July 5, 2011 at 4:22 PM

Great! Thanks a lot Veera! Helped me meet my deadline. :)

Reply

Chetan August 4, 2011 at 5:14 PM

Hi Veera,
Nice tutorial… I wanted to create separate log file on different folder on my every execution based on some logic. Can you please tell me how I can do it?

Regards,
Chetan

Reply

Susanta kumar Mohanty September 11, 2011 at 2:06 PM

Kindly send me the Log4j pdf.

Thank You………..

Reply

Astranaut September 28, 2011 at 2:21 PM

Hi Veera,
I went through your instructions and implemented the above block of code, how ever i am receiving below error.
=================
D:\>javac testlogger.java
testlogger.java:20: error: expected
logger.DEBUG(“this is a sample log message”);
^
testlogger.java:20: error: illegal start of type
logger.DEBUG(“this is a sample log message”);
^
2 errors
D:\>
=================
At code : logger.debug(“message”);
================
I have the above code written in an servlet program.
I have few questions on setting up Class path.

My class path = .;C:\apache-tomcat-6.0.28\lib\servlet-api.jar

I have log4j 1.2.16 downloaded to below location
C:\apache-tomcat-6.0.28\webapps\examples\WEB-INF\lib,

Do let me know if i have to download log4j 1.2.16 to this location : , which is my class path : C:\apache-tomcat-6.0.28\lib\

Please get this fixed for me.

Reply

Astronaut September 29, 2011 at 4:36 PM

I got it fixed by myself, i mean, i changed the class path and restarted the server, it started to work

Reply

Leave a Comment

{ 3 trackbacks }

Previous post:

Next post: