Adding automatic logging to Groovy classes

In the Writing less verbose Java Beans with Groovy Beans, Adding the cloning functionality to Groovy Beans, and Inheriting constructors in Groovy classes recipes, we met some of the annotation-based AST transformations available in Groovy. An AST transformation is a process in which a programmer is able to hook into the bytecode generation process and influence the final shape of the resulting bytecode. Groovy ships with many useful transformations and in this recipe, we are going to look at the family of logging annotations.

How to do it...

The transformation we are going to demonstrate is the @groovy.util.logging.Log annotation that injects java.util.logging.Logger into a Groovy class:

  1. Let's apply the annotation to a Groovy class:
    @groovy.util.logging.Log
    class UserService {
      def createUser(String username, String password) {
        log.info("creating user with name ${username}")
      }
    }
  2. And call the method of the new class:
    def userService = new UserService()
    userService.createUser('john', 'secret')
  3. The output will be:
    INFO: creating user with name john
    

How it works...

The annotation takes a number of steps. First, it creates a logger with the variable name log and injects it in the class as a static final variable. Then it surrounds every call to the logger with a conditional check to verify whether the log level is enabled. No need to pollute your code with hard-to-read if statements just to check whether the log statement should be evaluated.

The variable that holds the logger can be modified by using an attribute on the annotation:

@groovy.util.logging.Log('someLogger')
class UserService { ... }

There's more...

The logging transformation is not limited to use only one logging framework but it also allows to use the following logging facilities by changing the annotation class:

  • @groovy.util.logging.Commons: It injects an Apache Commons logger and initializes it using LogFactory.getLog(class).
  • @groovy.util.logging.Log4j: It injects Log4J org.apache.log4j.Logger into the class and initializes it using Logger.getLogger(class).
  • @groovy.util.logging.Slf4j: It injects a Slf4J logger into the annotated class and initializes it using org.slf4j.LoggerFactory.getLogger(class). Slf4J is the underlying logger used by the newer framework Logback. If you wish to use that framework you should use the @Slf4j annotation.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.198.81