在Python中记录方法调用的更好方法? [英] Better way to log method calls in Python?
问题描述
我们可以编写某种日志装饰器,以回显函数/方法调用,如下所示:
We can code out some sort of logging decorator to echo function/method calls like the following:
def log(fn):
...
@log
def foo():
...
class Foo(object):
@log
def foo(self):
...
@log
def bar(self, a, b):
...
@log
def foobar(self, x, y, z):
...
但是,如果我们想记录方法调用而不在每个meth定义前放置那么多@log怎么办?是否有某种方法可以将一个装饰器放在类定义之上,以使其所有方法调用都进行装饰/记录?还是有其他更好且有趣的方法来代替装饰器呢?
But what if we are like to log method calls without putting that many @log in front of each meth definition? Is there some way to just put one decorator above a class definition to make all its method calls decorated/logged? Or are there some other better and interesting ways to do that instead of decorator?
推荐答案
请参见但是,正如对该问题的公认答案所指出的那样,通常这不是一个好主意.
However, as the accepted answer to that question points out, it generally isn't a good idea.
如果您决定采用面向方面的编程路线,建议从这里开始:任何AOP是否支持Python?
If you decide to go the aspect oriented programming route, I suggest starting here: Any AOP support library for Python?
这篇关于在Python中记录方法调用的更好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!