Common Java Cookbook

Edition: 0.19

Download PDF or Read on Scribd

Download Examples (ZIP)

7.14. Configuring Log4J with XML

7.14.1. Problem

You need to configure Log4J with an XML document.

7.14.2. Solution

Use the DOMConfigurator to configure Log4J with an XML document. The following code configures Log4J from a resource named log4j.xml, and logs two messages:

import org.apache.log4j.DOMConfigurator;
import org.apache.log4j.Logger;
URL log4Jresource = this.getClass( ).getResource("log4j.xml");
DOMConfigurator.configure( lof4Jresource );
Logger log = Logger.getLogger( "com.discursive.SomeApp" );
log.info( "This is a log message" );
log.error( "This is an error message" );

The log4j.xml file contains a basic Log4J configuration, which sets the root category logging level to WARN, and the application's logging level to DEBUG. This XML document configures Log4J exactly the way that Log4J was configured by the previous example; log messages are sent to both the console and a RollingFileAppender:

<?xml version="1.0" encoding="UTF-8" ?>
<configuration configDebug="true">
    <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%5p (%F:%L) %m%n"/>
        </layout>        
    </appender>
    <appender name="FILE" class="org.apache.log4j.RollingFileAppender">
           <param name="File" value="output.log" />    
           <param name="MaxFileSize" value="2000KB" />    
           <param name="MaxBackupIndex" value="5" />    
           <layout class="org.apache.log4j.PatternLayout">
             <param name="ConversionPattern" value="%d %-5p %c - %m%n"/>
           </layout>      
    </appender>
    <category name="com.discursive">
      <priority value="DEBUG" />
    </category>
    
    <root>
       <priority value="WARN"/>
       <appender-ref ref="STDOUT" /> 
       <appender-ref ref="FILE" /> 
    </root>
    
</configuration>

This configuration will produce the same output as the previous recipe. The only difference between this recipe and the last is that XML is used to configure Log4J.

7.14.3. See Also

For more information about Log4J, see the Log4J project page at http://logging.apache.org/log4.


Creative Commons License
Common Java Cookbook by Tim O'Brien is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States License.
Permissions beyond the scope of this license may be available at http://www.discursive.com/books/cjcook/reference/jakartackbk-PREFACE-1.html. Copyright 2009. Common Java Cookbook Chunked HTML Output. Some Rights Reserved.