Search

Dark theme | Light theme

April 27, 2011

Groovy Goodness: Inject Logging Using Annotations

With Groovy 1.8 we can inject a log field into our classes with a simple annotation. In our class we can invoke method on the log field, just as we would do if we wrote the code to inject the log field ourselves. How many times have we written code like this Logger log = LoggerFactory.getLogger(<class>) at the top of our classes to use for example the Slf4j API? Since Groovy 1.8 we only have to add the @Slf4j annotation to our class and get the same result. AND each invocation of a log method is encapsulated in a check to see if the log level is enabled.

// File: LogSlf4j.groovy
// Add dependencies for Slf4j API and Logback
@Grapes([
    @Grab(group='org.slf4j', module='slf4j-api', version='1.6.1'),
    @Grab(group='ch.qos.logback', module='logback-classic', version='0.9.28')
])
import org.slf4j.*
import groovy.util.logging.Slf4j

// Use annotation to inject log field into the class.
@Slf4j
class HelloWorldSlf4j {
    def execute() {
        log.debug 'Execute HelloWorld.'
        log.info 'Simple sample to show log field is injected.'
    }
}

def helloWorld = new HelloWorldSlf4j()
helloWorld.execute()

When we run this script we get the following output:

$ groovy LogSlf4j.groovy
21:20:02.392 [main] DEBUG HelloWorldSlf4j - Execute HelloWorld.
21:20:02.398 [main] INFO  HelloWorldSlf4j - Simple sample to show log field is injected.

Besides an annotation for the Slf4j API other logging frameworks are supported with annotations:

Logging frameworkAnnotation
java.util.logging@Log
Log4j@Log4j
Apache Commons Logging@Commons
Slf4j API@Slf4j