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:
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}") } }
And call the method of the new class:
def userService = new UserService...