SourceForge.net Logo

RTP - Demo

Real Time Pricing - a Demo Application: Logging using Log4J

  www.theopenstack.com .

 

Using logging feature instead of println statements:

We have defined a common configuration for Log4J at the top level of the source tree (look at the ConfigLogger class for more details). With this to add logging in your code you need to take the following steps:

The log is stored in a log file. The name and location of the file is defined in the Log4J config file.

Log4J setup and config

Log4J is much more than just storing log statements in a file. You can look at the apache web site for more details. But the good part is with set up we have, as a developer you do not need to learn Log4J. During deployment, one can use the additional logging features as needed.

As mentioned earlier the ConfigLogger class is sort of our root logger. Lets look at some code of the class:
Here is the constructor:

private ConfigLogger(){

	super();

	Properties props = new Properties();

      /* The confif file defined what will be logged such as class name, line no etc.
       * it defines where it will be logged such as file or console etc.
       * finally we could supress logging by setting loging level in this file.
       */

	try{
		props.load((this.getClass().getClassLoader().getResourceAsStream("com/theopenstack/rtpdemo/Log4jConfig.properties")));
	} catch(Exception ie){
		log.error("Could not open Log4J properties file");
	ie.printStackTrace();
	}
	if (props != null)
		PropertyConfigurator.configure(props);

   }
As you can see it loads Log4jConfig.properties file and configures Log4J.

As mentioned earlier this class is defined at the top level (com.theopenstack.rtpdemo). This is to take the advantage of the way Log4J works. Any class that is defined under this directory (com.theopenstack.rtpdemo), 'inherits' this configuration (unless you specify a different one). This way in your code you do not need to define the config part mentioned above.
Now lets look at some parts of the the config file:
log4j.appender.R=org.apache.log4j.RollingFileAppender
This line tells Log4J to use RollingFileAppender - the 'appender' that appned the log in a file. The next line defines which file to write the log:
log4j.appender.R.File=D:\\projects\\OSTK\\rtpdemo\\RTPDEMO\\rtpdemo.log
The next line defines the 'pattern'
log4j.appender.R.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss} -- %p --%c{2} %M.%L %x -- %m%n

This will print date, name of the class and line number with every line that is logged. The complete config file is here.