Log4j multiple appenders

Let us discuss the use of multiple appenders with the help of below example. In this example we are using two appenders CA(Console Appender) and FA(File Appender) with different configurations.

Example:

Log4jTest.java

import org.apache.log4j.Logger;
 
/**
 * This class is used to show the use of 
 * multiple appenders with the log4j.properties file.
 * @author w3spoint
 */
public class Log4jTest {
	//Get the Logger object.
	private static Logger log = Logger.getLogger(Log4jTest.class);
 
	public static void main(String[] args) {	
		//logger messages
		log.debug("Log4j debug message test.");
		log.info("Log4j info message test.");
		log.warn("Log4j warn message test.");
		log.error("Log4j error message test.");
		log.fatal("Log4j fatal message test.");		
	}
}

log4j.properties

#log4j.rootCategory=INFO,DEBUG,A1,LFS,FA,CA
log4j.rootLogger=DEBUG, CA, FA
 
#Set Console Appender
log4j.appender.CA=org.apache.log4j.ConsoleAppender
#Set CA Layout
log4j.appender.CA.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%m%n
 
#Set File Appender
log4j.appender.FA=org.apache.log4j.FileAppender
log4j.appender.FA.File=test.log
#Set FA Layout
log4j.appender.FA.layout=org.apache.log4j.PatternLayout
log4j.appender.FA.layout.ConversionPattern=%m%n
 
#Set the logging level of FA to WARN
log4j.appender.FA.Threshold = WARN

Output:

Console

Log4j debug message test.
Log4j info message test.
Log4j warn message test.
Log4j error message test.
Log4j fatal message test.

test.log

Log4j warn message test.
Log4j error message test.
Log4j fatal message test.

Download this example.
 
Previous Topic: Log4j file appender.

 

Content Protection by DMCA.com
Please Share