Friday, April 2, 2010

Programmetically add Log4J Appenders

Following code snippet shows how to programmetically add log4j Appenders to your java code.

import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.SimpleLayout;

public class SampleLoggingAppender {
static Logger logger = Logger.getLogger(SampleLoggingAppender.class);

public static void main(String args[]) {
SimpleLayout layout = new SimpleLayout();
FileAppender fileAppender = null;
try {
fileAppender = new FileAppender(layout, "log.txt", false);
} catch (Exception ignored) {
}

ConsoleAppender consoleAppender = new ConsoleAppender(new PatternLayout());

logger.addAppender(fileAppender);
logger.addAppender(consoleAppender);
logger.setLevel(Level.DEBUG);

logger.debug("DEBUG");
logger.info("INFO");
logger.warn("WARN");
logger.error("ERROR");
logger.fatal("FATAL");
}
}

No comments: