Sunday, April 19, 2009

How to write log to multiple appenders in log4j


log4j.properties


# TRACE is setting show that all messages will be sent to appender
log4j.rootLogger=TRACE, stdout
log4j.category.AppLogging=TRACE, FILE
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[%5p] %d{hh:mm:ss} (%F:%M:%L)%n%m%n%n
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.file=log.txt
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern=[%5p] %d{hh:mm:ss} (%F:%M:%L)%n%m%n%n
log4j.appender.FILE.append=false
# setting custom level for each appender
log4j.appender.stdout.Threshold=ERROR
log4j.appender.FILE.Threshold=DEBUG

Log4jDemo.java

import org.apache.log4j.Logger;

public class Log4jDemo {
static Logger log = Logger.getLogger("AppLogging");

public static void main(String args[]) {
log.debug("this is my debug message");
log.info("this is my info message");
log.warn("this is my warn message");
log.error("this is my error message");
log.fatal("this is my fatal message");
}
}

No comments: