In this article, you will see how to generate logs using a XML file configured externally.
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>
log4j.xml provides some advanced configuration options such as Filter, ErrorHandlers and few advanced Appenders.
1. XML file
The following configuration creates the same result as in previous article.
log4j.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" > <log4j:configuration> <appender name="stdout" class="org.apache.log4j.ConsoleAppender"> <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="stdout"/> </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!!!"); } }
When you run the above example you’ll get an output like:
0 [main] INFO com.kruders.HelloWorld – Hello World!!!
You can download the source code of this example here.