Friday, December 31, 2010

log4j.xml - A sample configuration

I could not post anything last month though all the time I was dying to post something. The reason behind this was I change in my profession profile. Actually, I changed my employer. All of the last month I was busy in official work and to settle down in my new office.
The last week of the year is normally a holiday in the new company. So, I could rest a while in my home and able to write the blog post.

Though I had a couple of other topics in mind but writing them will take more time which I don't want to spend during the festivities. So, I'll discuss about a simple but useful thing.
How many of us in Java sphere use log4j for logging? You know the answer. log4j is a very popular logging framework. Configuring log4j is quite simple. Still when you get the task of doing it, you try to find an example (I do the same). That is why I'll show a simple log4j configuration to print to a file.

 
 
 

 
  


 
  
  


  
  


    
    


There are 2 ways to configure log4j, log4j.properties and log4j.xml. I prefer the xml format.
In this example I have configured the log4j to generate logs in apache tomcat's log directory (the application is a web app). Also I have channeled hibernate logs to the same log file.
Another important feature which is used very often is rollingFileAppender. It can roll your log files when they reach their limits.
To use this example you need a log4j.jar (I used 1.2.16). Hibernate (3.6.0) uses self4j logging APIs. So, you'll need self4j-log4j.jar. It can be downloaded from self4j site. I have defined a CONSOLE appender to display log messages in system console. You can add it to root logger to enable the console logging. That's all for this sample log4j.xml.

I hope the New Year 2011 brings best for everyone.