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

Groovy Goodness: Customize Log Variable Name with Log AST Annotations

DZone's Guide to

Groovy Goodness: Customize Log Variable Name with Log AST Annotations

· Java Zone ·
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

To add logging to a class with Groovy is easy. We apply one of the logging AST transformations and we get a variable in our class named log. We can invoke methods on the variable and the AST transformation will also automatically wrap those statement in a "if-logging-level-is-enabled" block. The transformation is even intelligent enough to do this only if Strings are added or a GString is used. If we want to use a different name than log we simply use the value parameter of the annotation. We assign the name we want to use and then we can use it in our code.

import groovy.util.logging.*

@Log(value = 'LOGGER')
class Event {
    String name
    Boolean started
    
    void start() {
        LOGGER.info "Event $name is started"
        started = true
    }
}

final Event event = new Event(name: 'gr8Conf')
event.start()
INFO: Event gr8Conf is started
...

Code written with Groovy 2.1.3

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}