Tuesday, August 11, 2009

Source Code to log messages in Java Applications

This article will highlight the source code of logger functionality of Java. Whenever you build any application using Java, you need to log the certain details or any exceptions happened while execution of the program.
For that we use built in logger jar [log4j-1.2.9.jar - http://www.findjar.com/jar/log4j/jars/log4j-1.2.9.jar.html] which contains all the relevant class of the Logger functionalities. The below simple code logs the information messages, debug messages and the error messages.

Logger API: http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/Logger.html

There is one log4jconfig.properties which contains the logger file properties. So we will use another java class to access the properties file.

The entries which I have used in the log4jconfig.properties file are:

log4j.rootLogger=DEBUG,file
log4j.appender.file.layout=org.apache.log4j.HTMLLayout
log4j.appender.file.File=logger.html
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.MaxFileSize=2000KB



Log4Logger.java

/*
* Log4Logger.java
* Snehanshu Chatterjee
*/

import java.util.Properties;
import org.apache.log4j.Category;
import org.apache.log4j.PropertyConfigurator;

public class Log4Logger extends org.apache.log4j.Logger {
private static Category l=null;
/** Creates a new instance of Log4Logger */
public Log4Logger(String name) {
super(name);
}
static{
try{
Properties logProp=new Properties();
String fName=new String("./log4jconfig.properties");
PropertyConfigurator.configure(fName);
} catch(Exception e) {
e.printStackTrace();
}
}
/**
* This method gets category object and it is static method.
* @param name String.
* @return Category Object with the l field.
*/
public static Category returnLogger(String name) {
l= Log4Logger.getLogger(name);
return l;
}
}


The below code which actually logs any information.

LoggerDemo.java

/*
LoggerDemo.java
Snehanshu Chatterjee
*/
import org.apache.log4j.Category;

public class LoggerDemo {

private static Category OutputCtrl = Log4Logger.returnLogger(LoggerDemo.class.getName());

LoggerDemo() {
}

private void doLog() {
OutputCtrl.info("Info Message");
OutputCtrl.debug("Debug the Program");
OutputCtrl.error("Error Message");
}

public static void main(String args[]) {
LoggerDemo loggerDemo = new LoggerDemo();
loggerDemo.doLog();
}

}

Run the File [Putting java file and jar file in one folder]
set classpath=.;./log4j-1.2.9.jar/
javac LoggerDemo.java
java LoggerDemo
pause

No comments:

Total Pageviews