Dark theme | Light theme

February 17, 2011

Grails Goodness: Use Log4j Extras Companion RollingFileAppender

Apache Extras Companion for Log4j contains a RollingFileAppender, which can be configured to automatically compress old log files. We can even save the old, archived log files to another directory than the active log file. In this post we learn how we can add and configure the RollingFileAppender in our Grails application.

First we must define our dependency on the Log4j Extras Companion libary. We open grails-app/conf/BuildConfig.groovy and add to the dependencies section the following code:

// File: grails-app/conf/BuildConfig.groovy
grails.project.dependency.resolution = {
    dependencies {
        compile 'log4j:apache-log4j-extras:1.0'

Next we can configure the appender in grails-app/conf/Config.groovy:

// File: grails-app/conf/Config.groovy
import org.apache.log4j.rolling.RollingFileAppender
import org.apache.log4j.rolling.TimeBasedRollingPolicy

log4j = {
    def rollingFile = new RollingFileAppender(name: 'rollingFileAppender', layout: pattern(conversionPattern: "%d [%t] %-5p %c{2} %x - %m%n"))
    // Rolling policy where log filename is logs/app.log.
    // Rollover each day, compress and save in logs/backup directory.
    def rollingPolicy = new TimeBasedRollingPolicy(fileNamePattern: 'logs/backup/app.%d{yyyy-MM-dd}.gz', activeFileName: 'logs/app.log')
    rollingFile.setRollingPolicy rollingPolicy

    appenders {
        appender rollingFile

    root {
        // Use our newly created appender.
        debug 'rollingFileAppender'

We use TimeBasedRollingPolicy, which is quite powerful. We can configure the rollover period using a date/time pattern. If the fileNamePattern ends with .gz the contents of the log file is compressed. Finally we decouple the active log file name from the location where the archived log files are saved with the property activeFileName.