Log4j Configuration

This is pretty simple stuff. Too easy if you ask me.

 The log4j is a handy tool for handling logs for your application. Log4j can be configured to just display logs in console or to write logs in files. The above screenshot  shows how a typical console log looks like with log4j enabled. 

Heres how I configured it here :

First, I created a log4j.properties file. This file contains configuration specification of log4j. Here, I just defined a ConsoleAppender, which generates console logs. If you need a log file, then you need to define a FileAppender here : 

log4j.rootLogger=DEBUG, CA

log4j.appender.CA=org.apache.log4j.ConsoleAppender
log4j.appender.CA.layout=org.apache.log4j.PatternLayout
log4j.appender.CA.layout.ConversionPattern=%-4r [%t] %-5p %c %x – %m%n

Once this file is created, we need a listener to be added to the deployment descriptor, which is basically your web.xml. 

<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j.properties</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>

By this, the configuration of log4j for your application is complete. With just this, you should be able to see logs of spring and hibernate framework code. To add your own logs, you need to do just this : 

First get the logger instance in your class as : 

Logger logger = Logger.getLogger(getClass());

Once you have the logger instance, you can use the log() method to display log messages as : 

logger.log(Priority.ERROR, "LoginController – Credentials are invalid.");

There are other priorities like ERROR, DEBUG, etc, which can be used depending on how/when you want the log to be displayed. 

Thats it for now about log4j. Enjoy… 🙂

More From Author

The closest thing to replace pen and paper for good :)

I have used two other styluses namely, the Bamboo Stylus and the Cregle iPen. By…

Apple Event October 2012

Been watching the live streaming of the Oct 23rd apple event. This is the event where…

Bootcamping Windows 8

Finally installed Windows 8 to Bootcamp(to non-mac users, this means that the windows now runs…

Leave a Reply

Your email address will not be published. Required fields are marked *