Over a million developers have joined DZone.

Groovy Goodness: Customise Log AST Annotations

DZone's Guide to

Groovy Goodness: Customise Log AST Annotations

Check out how to modify the category name of a log setup in Groovy in this post.

· Performance Zone ·
Free Resource

Container Monitoring and Management eBook: Read about the new realities of containerization.

Adding logging support to a class in Groovy is easy. We can choose to add SLF4J, Log4j, Log4j2, Apache Commons, or Java Util Logging to our class. The default implementation of the Abstract Syntax Tree (AST) transformation is to add a log field of the correct type. As category name, the complete class name (including the package) is used. We can change the name of the field with the value attribute. To alter the category name we use the attribute category.

In the following example snippet, we change the log field name to LOGGER and set a custom category name:

    @Grab(group='ch.qos.logback', module='logback-classic', version='1.1.7')
import groovy.util.logging.Slf4j

// Change name of the field to LOGGER and
// the category to 'mrhaki.blog.samples'.
@Slf4j(value = 'LOGGER', category = 'mrhaki.blog.samples')
class SampleLogging {

    String sample(final String message) {
        LOGGER.info 'Running sample({}) method', message

        "Groovy is $message!"


def s = new SampleLogging()
println "System.out says: ${s.sample('gr8')}"

When we execute the script we get the following output:

16:33:56.972 [Thread-7] INFO mrhaki.blog.samples - Running sample(gr8) method
System.out says: Groovy is gr8!

Notice the category is mrhaki.blog.samples and we use the field LOGGER in our code.

Written with Groovy 2.4.7.

Take the Chaos Out of Container Monitoring. View the webcast on-demand!

logging ,java ,ast ,annotations ,groovy ,syntax ,log4j ,slf4j

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}