Groovy Quick Tip - The groovy.util.logging Package

The groovy.util.logging package comes with a bunch of annotations. Each of the annotations adds logging capabilities of a particular logging library to the class where it is applied. For example, let us have a look at the @Log4j [0] annotation. As its name implies, it is used in projects that use the Log4j logging library [1]. Getting @Log4j into play for a Groovy class is simple, we can do so by just annotating the class with the @Log4j annotation on the type level:
 
@Log4j
class ItemRepository {

    void create(String name)  {

        // ...

        log.info "created a new item named ${name}, identifier ${item.id}"

    }
}
 
As you might have guessed from the source code example, the @Log4j annotation does not "only" annotate the class. It triggers an AST transformation that adds a private static final Logger field to the ItemRepository class. That field can now be used as if it were manually specified in this class. There is another cool feature that is only visible from the AST browser in groovyConsole. When we have a look for the code that is generated for the code line above,
 
log.info "created a new item named ${name}, identifier ${item.id}"
 
we can see in the "class generation" compile phase the code was changed to
 
log.isInfoEnabled() ? log.info "created a new item named ${name}, identifier ${item.id}" : ""
 
Isnt' that cool? The AST transformation automatically detected a GString and therefore wrapped the info method call in a conditional block that is only executed when the INFO log level is active at runtime. If we would have written something like
 
log.info "created a new item"
 
the AST transformation would see that the argument is of type java.lang.String and wouldn't add a conditional log statement. I know that this isn't a particular issue to Log4j, as Burt Beckwidth already explained here [2]. But be aware that @Log4j isn't the only logging annotation Groovy provides. In fact it's a so called @Log variant annotation. Besides the original @Log for the Java logging support, there are a bunch of such variant annotations: @Log4j, @Slf4j, @Commons and @Log4j2 included in the current Groovy 2.2 release candidate [3]. However, I've found that this is a Groovy feature that is not widely known though I'm using it every day. So keep on groovying with Groovy's logging annotations!

[0] Groovy Log4j Annotation - http://groovy.codehaus.org/api/groovy/util/logging/Log4j.html
[1] Apache Log4J - http://logging.apache.org/log4j/1.2/
[2] Burt Beckwith - Performance Issues with GStrings
[3] Guillaume Laforge - Groovy 2.2 Release Candidate