Intercept method calls in Python

Python

Python Problem Overview


I'm implementing a RESTful web service in python and would like to add some QOS logging functionality by intercepting function calls and logging their execution time and so on.

Basically i thought of a class from which all other services can inherit, that automatically overrides the default method implementations and wraps them in a logger function. What's the best way to achieve this?

Python Solutions


Solution 1 - Python

Something like this? This implictly adds a decorator to your method (you can also make an explicit decorator based on this if you prefer that):

class Foo(object):
    def __getattribute__(self,name):
        attr = object.__getattribute__(self, name)
        if hasattr(attr, '__call__'):
            def newfunc(*args, **kwargs):
                print('before calling %s' %attr.__name__)
                result = attr(*args, **kwargs)
                print('done calling %s' %attr.__name__)
                return result
            return newfunc
        else:
            return attr

when you now try something like:

class Bar(Foo):
    def myFunc(self, data):
        print("myFunc: %s"% data)

bar = Bar()
bar.myFunc(5)

You'll get:

before calling myFunc
myFunc:  5
done calling myFunc

Solution 2 - Python

What if you write a decorator on each functions ? Here is an example on python's wiki.

Do you use any web framework for doing your webservice ? Or are you doing everything by hand ?

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEraView Question on Stackoverflow
Solution 1 - PythonKillianDSView Answer on Stackoverflow
Solution 2 - PythondzenView Answer on Stackoverflow