![]() |
|
Real Time Pricing - a Demo Application: Logging using Log4J
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:
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.
log4j.appender.R=org.apache.log4j.RollingFileAppenderThis 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.logThe next line defines the 'pattern'
log4j.appender.R.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss} -- %p --%c{2} %M.%L %x -- %m%nThis will print date, name of the class and line number with every line that is logged. The complete config file is here.