analytics

Sunday, April 17, 2011

Multiple Appenders Using Properties File

Log4j Multiple Appender Example


In this example you will see how to create a console and file appender and add it to the rootLogger.

The log4j.properties file is shown below.

log4j.rootLogger=DEBUG, CA, FA
#Console Appender
log4j.appender.CA=org.apache.log4j.ConsoleAppender
log4j.appender.CA.layout=org.apache.log4j.PatternLayout
log4j.appender.CA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
#File Appender
log4j.appender.FA=org.apache.log4j.FileAppender
log4j.appender.FA.File=sample.log
log4j.appender.FA.layout=org.apache.log4j.PatternLayout
log4j.appender.FA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
# Set the logger level of File Appender to WARN
log4j.appender.FA.Threshold = WARN
Here we create two appenders ConsoleAppender and FileAppender. You need to set the File attribute of the FileAppender to the log file name, here it is sample.log. Add the FileAppender (FA) and the ConsoleAppender (CA) to the rootLogger.


You can also set the logger level for each appender seperately. Here the FileAppender logger level is set to WARN. Only WARN, ERROR and FATAL level log messages will be logged in the sample.log file. Since we don't set any log level explicitly for the ConsoleAppender it will inherit the rootLogger level, that is DEBUG.

Here is our example code.

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class HelloWorld {
static final Logger logger = Logger.getLogger(HelloWorld.class);
public static void main(String[] args) {
PropertyConfigurator.configure("log4j.properties");
logger.debug("Sample debug message");
logger.info("Sample info message");
logger.warn("Sample warn message");
logger.error("Sample error message");
logger.fatal("Sample fatal message");
}
}
The output on the cosole.


[main] DEBUG com.vaannila.helloworld.HelloWorld - Sample debug message

[main] INFO com.vaannila.helloworld.HelloWorld - Sample info message
[main] WARN com.vaannila.helloworld.HelloWorld - Sample warn message
[main] ERROR com.vaannila.helloworld.HelloWorld - Sample error message
[main] FATAL com.vaannila.helloworld.HelloWorld - Sample fatal message
The contents of the sample.log file.


[main] WARN com.vaannila.helloworld.HelloWorld - Sample warn message
[main] ERROR com.vaannila.helloworld.HelloWorld - Sample error message
[main] FATAL com.vaannila.helloworld.HelloWorld - Sample fatal message

No comments:

Post a Comment