Log4j Multiple Appender

In this article, you will see how to use multiple appenders in Log4j.

First create a new Java Project and configure it as Maven Project. For Reference, Click Here

Add the following dependencies in pom.xml

  <dependencies>
	  <dependency>
		<groupId>log4j</groupId>
		<artifactId>log4j</artifactId>
		<version>1.2.17</version>
	  </dependency>
  </dependencies>  

1. Properties file

The following configuration shows logs on console and files.

log4j.properties

log4j.rootLogger=DEBUG, CA, FILE

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

log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=C:\\logging.txt
  
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n  

2. Log4j in Java Program

The following Java class is a very simple example that initializes, and then uses, the Log4J logging library for Java applications.

package com.kruders;

import org.apache.log4j.Logger;

public class HelloWorld {
	static final Logger logger = Logger.getLogger(HelloWorld.class);
	
	public static void main(String[] args) {
		logger.info("Hello World!!!");
	}
}

,

No comments yet.

Leave a Reply