nimavat.me

Java, Groovy, Grails, Spring, Vue, Ionic + Fun blog

Logback rolling file appender example

|

Since 3.x version grails has switched to logback as its logging framework. Logback comes with support for groovy configuration and provides a nice DSL. Just like me, if you hate xml, then you’ll definitely love the groovy configuration.

By default the grails cofigures the stdout appender which will write the log messages to console. It is quite common requirement to configure a file appender to write to log messages to a file in production environment.

What is an Appender ?

An appender is a component which is responsible for writing the log messages. log messages generated by loggers are delivered to appenders and its appenders responsibility to actually write the log messages to some where. There are appenders to write log messages to output stream, console, file, socket, smtp, system log file etc. And you can create your own appenders very easily if existing appenders doesnt fulfil your requirement.

Here’s an example of how to configure a rolling file appender. This example considers grails environemt. If you dont use grails, just ignore the environment related stuff.

    boolean isWarDeployed = Environment.isWarDeployed()
    String logsDir = System.getProperty('catalina.base', '.') + "/logs"
    String logFileName = logsDir + "/appname.log"
    
    if(isWarDeployed) {
        appender("file", RollingFileAppender) {
            file = logFileName
            append = true
            encoder(PatternLayoutEncoder) {
                pattern = "%date [%level] %logger - %msg%n%exception{10}"
            }
    
            rollingPolicy(TimeBasedRollingPolicy) {
                fileNamePattern = "${logFileName}.%d{yyyy-MM-dd}"
                maxHistory = 15
            }
        }
    }

The above code configures the rolling file appender, only when the application is deployed as a war. The logfile will be created under tomcat logs directory. The TimeBasedRollingPolicy will rollback the file every day, previous days log file will be renamed to logfilename-yyyy-mm-dd. It will keep maximum 15 log files, as the new files are created the old files will be deleted.

Filter log messages by level

Log back has a concept of filters. Filters can be used to filter log messages based on some criteria.

Lets see how to filter the log messages below a specified level using a ThresholdFilters.

    appender("error", FileAppender) {
            file = "error.log"
            append = true
    
            filter(ThresholdFilter) {
                level = "WARN"
            }
    
            encoder(PatternLayoutEncoder) {
                pattern = "%date [%level] %logger - %msg%n%exception{10}"
            }
    
       
    }

The above configuration configures a file appender with a threshold level WARN. It will filter out all log messages below the level WARN.