Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a clean way to log the result of a method in Groovy?

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

like image 948
cdeszaq Avatar asked Nov 23 '22 23:11

cdeszaq


1 Answers

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.

like image 76
kdabir Avatar answered Dec 09 '22 22:12

kdabir