Custom Log4j Configuration Examples

You can create your own custom log4j configurations that you can use for logging instead of the default log4j.xml file.

You can also see the official log4j wiki page for more information on log4j configurations at http://wiki.apache.org/logging-log4j/Log4jXmlFormat.

Following are the few example XML configurations for the some logging use cases, which you can use after overriding the default logging (see Overriding the Default Logging Mode for more information).

Multiple Log Files Using Single log4j Configuration

Define multiple FileAppender classed to create multiple logging as shown in the following example:

<appender name="FILE" class="org.apache.log4j.FileAppender">
        <param name="file" value="${be.home}/logs/sample.log" />
        <param name="append" value="false" /> <param name ="threshold" value="debug"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="[%t] %d{HH:mm:ss,SSS} %-5p %l - %m%n" />
        </layout>
</appender>
<appender name="FILE" class="org.apache.log4j.FileAppender">
        <param name="file" value="${be.home}/logs/sample2.log" />
        <param name="append" value="false" /> <param name ="threshold" value="info"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="[%t] %d{HH:mm:ss,SSS} %-5p %l - %m%n" />
        </layout>
</appender>

Rotating Log Files Based on Time

Define the DailyRollingFileAppender class to roll over log files based on time. The following example shows the configuration for rolling over the log file on midnight each day:

<appender name="FILE" class="org.apache.log4j.DailyRollingFileAppender">
        <param name="file" value="${be.home}/logs/sample.log" />
        <param name="DatePattern" value="'.'yyyy-MM-dd" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="[%t] %d{HH:mm:ss,SSS} %-5p %l - %m%n" />
        </layout>
</appender>
The following tables displays the example values of the DatePattern parameter which defines the time when to roll over the logs.
DatePattern Values For DailyRollingFileAppender
Time Value
Minutely '.'yyyy-MM-dd-HH-mm
Hourly '.'yyyy-MM-dd-HH
Half-daily '.'yyyy-MM-dd-a
Daily '.'yyyy-MM-dd
Weekly '.'yyyy-ww
Monthly '.'yyyy-MM

Real Time Streaming For Console Logs

Define the FlumeAppender class to allow applications to send events to the the console, as shown in the following example:

<appender name="flume" class="org.apache.flume.clients.log4jappender.Log4jAppender">
          <param name="Hostname" value="localhost" />
          <param name="Port" value="41414" />
         <param name="UnsafeMode" value="false" />
         <layout class="org.apache.log4j.PatternLayout">
                  <param name="ConversionPattern" value="[%t] %d{HH:mm:ss,SSS} %-5p %l - %m%n" />
         </layout>
</appender>