Adding performance logging to methods
In this recipe, we will learn how to add the logging of execution time metrics to any method of a class, without littering the actual method with logging code. Java has used Aspect Oriented Programming (AOP) for many years now to add aspects (or common features) to functions, without having the functions to know that the code was there. It is behavior that looks and smells like it should have a structure, but you can't find a way to express this structure in code with traditional object-oriented techniques.
Metrics is one common aspect that is often added to the code to figure out where the bottleneck is that is keeping you awake at night. Let's look at a typical example:
def createCustomer() { long start = System.currentTimeMillis() ... // Slow operation long spentTime = System.currentTimeMillis() - start log.debug("Execution time: ${spentTime}ms.") }
Imagine repeating such code in hundreds or thousands of methods and you will quickly realize...