Thursday, July 15, 2010

Configure log4j environment programmatically in Java

I tried to find out how to configure log4j environment programmatically, but could not get any instant example which can be run. Here is a real example, which can be run directly. The program needs the log4j-x.x.x.jar ( I used log4j-1.2.16.jar) in the path in order to compile and run the program, and I hope anybody trying to configure can easily do that.

In this program, a parameter can be passed to indicate, whether a Console logger ( logging to System.out) or a Application logger ( logging to some file) is needed. If the argument passed is console then, it creates a Console logger, and log to it.

Otherwise a file path ( complete path) should be provided as the argument, and it will log to the file.

Again, based on the requirements, it should be customized. In order to customize the pattern of logging, you need to change the pattern string. To understand how you can customize, you can go through the PatternLayout docs at the following link.

http://logging.apache.org/log4j/1.2/apidocs/index.html


Also if you want to set the level at run time, then you can modify it to take a parameter, and based on the value, you can set the level. This is just a basic example.




import java.io.IOException;
import org.apache.log4j.Appender;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;


public class TestLogger {

static Logger logger = null ;
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {

if(args[0].equalsIgnoreCase("console")){
logger = getConsoleLogger();
}
else {
logger = getAppLogger(args[0]);
}

logger.info("Hi");
logger.debug("debug");

}

public static Logger getAppLogger(String path) throws IOException{
Logger rootLogger = Logger.getLogger(TestLogger.class.getCanonicalName());
Layout pattern = new PatternLayout("%d{MM-dd-yyyy HH:mm:ss,SSS} %-5p %c:%m%n");
Appender newAppender = null;
newAppender = new FileAppender(pattern, path, true);
rootLogger.setAdditivity(false);
rootLogger.setLevel(Level.INFO);
rootLogger.addAppender(newAppender);
return rootLogger;

}

public static Logger getConsoleLogger() throws IOException{
Logger rootLogger = Logger.getLogger(TestLogger.class.getCanonicalName());
rootLogger.setLevel(Level.INFO);
rootLogger.addAppender(new ConsoleAppender(
new PatternLayout("%d{MM/dd/yyyy HH:mm:ss,SSS} %-5p %c:%m%n")));
return rootLogger;

}
}