Meyyappan has posted 101 posts at DZone. View Full User Profile

Log4j Multiple Appender Example

06.14.2012
| 79141 views |
  • submit to reddit

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.

package com.vaannila.helloworld;

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 console.

0    [main] DEBUG com.vaannila.helloworld.HelloWorld  - Sample debug message
0    [main] INFO  com.vaannila.helloworld.HelloWorld  - Sample info message
0    [main] WARN  com.vaannila.helloworld.HelloWorld  - Sample warn message
0    [main] ERROR com.vaannila.helloworld.HelloWorld  - Sample error message
0    [main] FATAL com.vaannila.helloworld.HelloWorld  - Sample fatal message

The contents of the sample.log file.

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

 You can download the log4j configuration file here.

Source: Download

Source + Lib: Download

 

Published at DZone with permission of its author, Meyyappan Muthuraman.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags: