Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Groovy Is there a way to decorate every class to add tracing?

Tags:

groovy

How would I go about making every method call of every groovy class of mine print "Entering ${methodname}" as it enters the method call?

Without having to wrap every new object I create with new TracingDecorator(new Object())?

like image 616
Kyle Avatar asked Sep 11 '10 17:09

Kyle


1 Answers

You'd need to override metaClass.invokeMethod on all of your classes and have it wrap the method call to the original class with your tracing stuff.

You could probably spin through the class list that you get from the classloader matching some sort of naming/package pattern and then for each of those do something like this decorateMethodsWithLogging:

class Foo {
    def bar() {
        println "in bar"
    }

    def baz(String name) {
        println "in baz with $name"
    }
}



def decorateMethodsWithLogging(clazz) {
    def mc = clazz.metaClass

    mc.invokeMethod = { String name, args ->
        println "before $name, args = $args"
        def result = mc.getMetaMethod(name, args).invoke(delegate, args)
        println "after $name"
        return result
    }
}


decorateMethodsWithLogging(Foo.class)

def f = new Foo()
f.bar()
f.baz("qux")

this prints

before bar, args = []
in bar
after bar
before baz, args = [qux]
in baz with qux
after baz
like image 161
Ted Naleid Avatar answered Nov 15 '22 11:11

Ted Naleid