Groovy Goodness: Customise Log AST Annotations
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.