拦截Python中的方法调用 [英] Intercept method calls in Python
问题描述
我正在用 python 实现一个 RESTful Web 服务,并希望通过拦截函数调用并记录它们的执行时间等来添加一些 QOS 日志记录功能.
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?
推荐答案
类似这样的事情?这隐含地向您的方法添加了一个装饰器(如果您愿意,也可以基于此创建一个显式装饰器):
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)
你会得到:
before calling myFunc
myFunc: 5
done calling myFunc
这篇关于拦截Python中的方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!