Log4j Tutorial : Adding Log4j logging to your project

by Veera on July 26, 2009

in How To, Java

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 support to your project?

Follow these steps if you want to add Log4j logging support to your Java 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 Appender – this is the class file which does the actual logging. It could be a simple Console appender which dumps 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?

Follow me on Twitter to get notified whenever I update this blog.

{ 2 trackbacks }

Java Blog | Log4j Tutorial : How to send log messages to different log files? | Veerasundar
August 6, 2009 at 11:47 PM
Java Blog | Log4j Tutorial: Additivity – what and why? | Veerasundar
August 13, 2009 at 7:24 PM

{ 11 comments }

vishnu July 27, 2009 at 9:50 AM

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

huu2uan August 6, 2009 at 1:28 PM

nice tut :)

Veera August 6, 2009 at 10:32 PM

thanks!

huu2uan August 6, 2009 at 1:36 PM

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

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.

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.

Veera August 9, 2009 at 9:21 PM

logback looks impressive. Will definitely give it a try.

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.

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.

huu2uan November 13, 2009 at 11:03 PM

nice tut :)

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(“…..”,…);
}

Comments on this entry are closed.

Previous post:

Next post: