I often find myself doing something like this in order to log the output of a method call:
def someMethod() {
def retVal = //stuff
log.debug("The return value is: $retVal")
retVal
}
This seems like a lot of ceremony to just log the return value of the method. I know I can use Aspect Oriented Programming (AOP) to do this sort of thing, but I was hoping to do it with just Groovy.
Groovy has the great @Memoize
annotation to auto-memoize method calls, so does it have a similar @LogReturn
sort of annotation to do what I'm after?
Ideally, I would expect something clean, like this:
@LogReturn("debug")
def someMethod() {
// Stuff
}
Note 1: I know I could use meta-programming to wrap the method in another method, but I was hoping to be able to make it more explicit with an annotation
Note 2: I'm also open to suggestions for accomplishing this in a different way
I don't know if any such annotations that would log return value exists in the groovy core. Having said that, I think it should be possible with some AST transformation. If you follow this document, it does somewhat similar i.e. logs entry and exist to annotated method but does not print the return value.
This blog shows how to the catch the returned value for caching, you can instead use that for logging. I suspect you need to be careful as this assumes last statement to be a return value so if you explicitly return before last statement this might not work. This is just my guess, I have not tried it myself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With