Mar 31, 2010

How to Use Log4j?

A very simple incorporation of log4j is here!If you really want to know as to how to incorporate log4j logging in your application, here are the details. Though this is simple, I see a bunch of questions related to this in every java related forum and hence I thought of posting this blog!

  • Let us have a simple Bean.xml and Bean.class. the xml file has the bean definition and the bean class just prints a string. This is a very simple application written to make you all understand the incorporation of log4j!

  • Just create a Spring Project in eclipse (since am using a bean and bean.xml is being used for configuring the bean). The project hierarchy is as shown below. You also have a file (empty file) in the classpath of this project as shown below:

  • Select the project.Right click and go to properties. Here you can add the required jars. For the implementation of log4j in a spring project, you would need
  1. Spring jars (all the 3.0 version jars)
  2. log4j.jar(latest)
  • Now add the following code to your

# Set root category for logging error messages

# Debug statements logged by Spring framework., AppAppender

#AppAppender is set to DailyRollingFileAppender and new file rolls every day.

  • Now just run as a java application. Only errors get printed in the log gile.

If you want to change the level of logging, you can make the warninggs or information to get printed in the log file by changing the log4j.rootCategory to INFO, WARN etc.

  • If you have a directory hewrarchy in your application, you can enable logging levels for each of the package by adding an entry as

<br /><br /><your package structure>==ERROR, AppAppender<br /><br />

  • AppAppender is nothing but a file in the logs folder under c: whose layout, date pattern and type are as described in the code above. Here, it is a daily rolling appender. A new file gets created everyday and the old file is stored after being renamed with proper dates.


  1. Yet another ProgrammerApril 27, 2010 at 9:43 PM

    There is a bunch of edition that is going in with this write up in log4j!Sorry for the inconvenience and stay tuned to hear about the updates!

  2. good post dude, indeed quite useful logging tips in java. In my opinion using correct logging level for different message is most important thing to learn and logging has important performance impact (ever found process running in DEBUG mode in production ) and has to be handled efficiently. I have also blogged my tips as my favorite java logging tips , let me know how do you find it.