April 9, 2020
Estimated Post Reading Time ~

Groovy Annotations for Logging

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 go on log objects 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.

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

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

@Log4j(value='LOGGER')
class LoggerDemoUsingCustomVariableName {
def useLogger() {
LOGGER.info "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


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.