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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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.