Search This Blog

Thursday, October 4, 2012

Using logback and slf4j in grails application

Recently I configured grails application with logback.
Logback is better than log4j as mentioned here: http://logback.qos.ch/reasonsToSwitch.html

The changes to a grails application are these

We need to exclude log4j in buildconfig.
We can also specify where the logback configuration file is located


In BuildConfig.groovy

   

   // inherit Grails' default dependencies

    inherits("global") {

        ...
        // excludes 'ehcache'
excludes 'grails-plugin-log4j'
    }

    dependencies {
  ....
compile 'ch.qos.logback:logback-classic:1.0.6'
    }

//last line in the file to specify config file location
this.classLoader.rootLoader.addURL(new File("${basedir}/grails-app/conf").toURI().toURL()) 

Once the changes above are made, we can use annotation to log information.

Using logging in your controller or service is as simple as using an annotation and the right log method.
You need to use the annotation @Slf4j.


Here is an example:

import groovy.util.logging.Slf4j

@Slf4j
class XXXController {

def yyyy() {
log.debug "yyyy called."
...
render view:"myview";
}
We were able to use the @Slf4j in services controller and even spock integration tests.

Hope this helps you in configuring  Slf4j and logback in your grails application.