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

Try Okta to add social login, MFA, and OpenID Connect support to your Java app in minutes. Create a free developer account today and never build auth again.

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

Build and launch faster with Okta’s user management API. Register today for the free forever developer edition!

Topics:

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

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}