Log4J Configuration

Introduction

With log4j it is possible to enable logging at runtime without modifying the XDoclet binary. The log4j package is designed so that these statements can remain in shipped code without incurring a heavy performance cost. Logging behavior can be controlled by editing a configuration file, without touching the XDoclet binary.

log4j.xml

Log4j is usually used in conjunction with external log files so that options do not have to be hard-coded within the software. The advantage of using an external configuration file is that changes can be made to the options without having to recompile the software. A disadvantage could be, that due to the io instructions used, it is slightly slower.

There are two ways in which one can specify the external configuration file: a plain text file or an XML file. Since everything is written in XML these days, this document will focus on the XML approach but will also include relevant plain text examples. To begin with, examine the sample XML config file shown below:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

    <appender name="ConsoleAppender" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.SimpleLayout"/>
    </appender>

    <root>
        <priority value="debug" />
        <appender-ref ref="ConsoleAppender"/>
    </root>

</log4j:configuration>/

Here an Appender is created and called "ConsoleAppender", note that any name could have been chosen. The class for the appender is then specified in full, when referring to classes, one always uses the fully qualified class name. An Appender must always have a name and a class specified. Nested within Appender is the layout element which defines the layout to be a SimpleLayout. Layout must always have the class attribute.

The root element always exists and cannot be sub-classed. The example shows the priority being set to "debug" and the appender setup by including an appender-ref element, of which, more that one may be specified. See the file src/java/org/apache/log4j/xml/log4j.dtd in your log4j distribution for more information about the structure of an XML configuration file.