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

[java]
Logger log = LoggerFactory.getLogger(this)

[/java]

and method calls goes on log object like log.info(), 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 .

[java]

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

[/java]

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

[java]

@Log4j(value=’LOGGER’)
class LoggerDemoUsingCustomVariableName {
def useLogger() {
LOGGER.info "Hey! You have changed variable’s name"
}
}

[/java]

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.

FOUND THIS USEFUL? SHARE IT

comments (1 “Groovy Annotations for Logging”)

Leave a Reply

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