November 10, 2008

Using a different log4j configuration in a Cocoon 2.2 block

The Cocoon 2.2 Maven plugin provides a good method for developing a block. When we configure the plugin correctly we can start Jetty and have a reloadable web application. This means every change we make to a source file is reflected immediately in the web application. The plugin also has a default Log4j configuration file. The configuration defines a FileAppender with the filename ./target/work/log/log4j.log. The append property is set to true. This can result in a very big log4j.log file, because as long we don't run mvn clean all logging is added to the existing file.

We can change the configuration for Log4j by setting a parameter in the Cocoon 2.2 Maven plugin. We must add the parameter customLog4jXconf to our plugin definition:


Notice we defined the parameter customLog4jXconf and set it to the file src/main/etc/log4j.xml. Now we can create the new log4j.xml file and save it in src/main/etc:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="CORE" class="org.apache.log4j.RollingFileAppender">
        <param name="File" value="./target/work/log/log4j.log"/>
        <param name="Append" value="true"/>
        <param name="MaxBackupIndex" value="10"/>     
        <param name="MaxFileSize" value="5MB"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d %t %-5p %c{2} - %m%n"/>
        <priority value="\${org.apache.cocoon.log4j.loglevel}"/>
        <appender-ref ref="CORE" />

Notice: in line 14 we must escape the $ sign with a \. The plugin will run this file through StringTemplate and therefore we must escape the $ sign.

Now when we run mvn jetty:run our new Log4j configuration file is used.