Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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.

Free Resource

Transform incident management with machine learning and analytics to help you maintain optimal performance and availability while keeping pace with the growing demands of digital business with this eBook, brought to you in partnership with BMC.

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:

@Grapes(
    @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.

Evolve your approach to Application Performance Monitoring by adopting five best practices that are outlined and explored in this e-book, brought to you in partnership with BMC.

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

Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}