Search

Dark theme | Light theme

February 17, 2011

Grails Goodness: Use TimeAndSizeRollingAppender for Logging

In a previous post we learned how to use the Log4j Extras Companion RollingFileAppender. In this post we learn how to use TimeAndSizeRollingAppender. This appender has a lot of nice features among rolling over the log file at a time interval and we can limit the number of rolled over log files. With this combination we can keep a history of log files, but limit how many log files are saved.

First we must download the JAR file with the appender and save it in the lib directory of our Grails application. Next we can configure the appender in grails-app/conf/Conf.groovy:

// File: grails-app/conf/Config.groovy
import org.apache.log4j.appender.TimeAndSizeRollingAppender
...
log4j = {
    appenders {
        appender new TimeAndSizeRollingAppender(name: 'timeAndSizeRollingAppender',
                     file: 'logs/app.log', datePattern: '.yyyy-MM-dd',
                     maxRollFileCount: 7, compressionAlgorithm: 'GZ',
                     compressionMinQueueSize: 2,
                     layout: pattern(conversionPattern: "%d [%t] %-5p %c{2} %x - %m%n"))
    }

    root {
        // Use the appender.
        debug 'timeAndSizeRollingAppender'
    }
}
...

We configured the appender to rollover daily, compress the contents of the archived log files after 2 rollovers, and only save 7 archived log files.