Groovy Annotations for Logging

16 / Dec / 2014 by Neetesh Bhardwaj 1 comments

We use logging in our application to report and persist error and warning messages as well as info messages (e.g. runtime statistics) so that the messages can later be retrieved and analyzed.

Initially we were getting an instance of Logger from LoggerFactory and uses it in our class for logging information, errors, exceptions, warnings etc.

Example code we use to write to get the instance of Logger

Logger log = LoggerFactory.getLogger(this)


and method calls goes on log object like, log.error()… etc
With Groovy 1.8 we can inject a log field into our classes with a simple annotation (@Log4j). We don’t need to write the above line in each and every class, just put @Log4j annotation above the class .


class LoggerDemo {
def useLogger() { "Cool!!! log field injected"
log.debug "This is log’s debug method"


You can also change logger variable’s name by passing value to Annotation


class LoggerDemoUsingCustomVariableName {
def useLogger() { "Hey! You have changed variable’s name"


Other than @Log4j API grails provides other logging libraries too. Here is the list of available loggers:

  • @Log for java.util.logging
  • @Commons for Commons-Logging
  • @Log4j for Log4J
  • @Slf4j for SLF4J


Cool! you are done. Hope this will help you.


comments (1 “Groovy Annotations for Logging”)

Leave a Reply

Your email address will not be published. Required fields are marked *