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

FlexNet Code Aware, a free scan tool for developers. Scan Java, NuGet, and NPM packages for open source security and open source license compliance issues.

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

 Scan Java, NuGet, and NPM packages for open source security and license compliance issues. 

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 }}