Log4j Multiple Appender using XML File

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

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. XML file

The following configuration shows logs on console and files.

log4j.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration>
 	<appender name="CA" class="org.apache.log4j.ConsoleAppender">
   		<layout class="org.apache.log4j.PatternLayout">
     		<param name="ConversionPattern" value="%-4r [%t] %-5p %c %x - %m%n"/>
    	</layout>
     </appender>
     <appender name="FA" class="org.apache.log4j.FileAppender">
		<param name="File" value="C:\\logging.txt"/>
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%-4r [%t] %-5p %c %x - %m%n" />
		</layout>
	</appender>
    <root>
      <priority value="info"></priority>
      <appender-ref ref="CA"/>
      <appender-ref ref="FA" />
    </root>
</log4j:configuration> 

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