我有一个我写的日志类,我喜欢使用。看起来像这样:
class EasyLogger(object):
SEP = " "
def __init__(self, logger=logging.getLogger(__name__)):
self.logger = logger
def _format_str(self, *args):
return self.SEP.join([str(a) for a in args])
def debug(self, *args):
self.logger.debug(self._format_str(*args))
.... repeated for the other logging methods, like info, warning, etc....
def __getattr__(self, name):
return getattr(self.logger, name)
这给了我如下语法:
^{pr2}$我喜欢。我不想从logging.Logger
继承,因为组合比继承好,我真的不想搞乱这样的内置类。在
我的格式字符串如下所示:
LOGGING_FMT = "<%(filename)s:%(lineno)s(%(levelname)s) - %(funcName)s() >"\
"%(message)s"
但这行不通,因为行号和函数名总是报告easylogger.py
中的内容,而不是调用函数。在
我通过以下this奇妙的答案和monkey修补findCaller
方法修复了这个问题,如下所示:
def __init__(self, logger=logging.getLogger(__name__)):
self.logger = logger
# Ugly, ugly, ugly dirty hack to fix line numbers
self.logger.findCaller = find_caller_monkeypatch
这行得通,但我很困惑。我最初用以下签名定义了find_caller_monkeypatch
:
def find_caller_monkeypatch(self):
(函数的主体是从链接的答案中复制+粘贴的)。但是,这会导致错误:
File "/usr/lib64/python2.7/logging/__init__.py", line 1262, in _log
fn, lno, func = self.findCaller()
TypeError: find_caller_monkeypatch() takes exactly 1 argument (0 given)
删除self
作为find_caller_multipatch
的参数可以修复这个错误,但是我很困惑:为什么find_caller_monkeypatch
在{self.findCaller()
时,为什么不将{self
作为参数?在
以下片段是同一问题的一个较小示例:
In [7]: class Foo(object):
...: def say_hi(self):
...: print "Hello World"
...:
In [8]: def say_bye_self(self): print "Goodbye world"
In [9]: def say_bye(): print "Goodbye world"
In [10]: foo = Foo()
In [11]: foo.say_hi()
Hello World
In [12]: foo.say_hi = say_bye_self
In [13]: foo.say_hi()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-13-10baea358e0b> in <module>()
----> 1 foo.say_hi()
TypeError: say_bye_self() takes exactly 1 argument (0 given)
In [14]: foo.say_hi = say_bye
In [15]: foo.say_hi()
Goodbye world
这是怎么回事?在
你可以在班上瞎搞
或者你可以用Monkeypatch一个实例
^{pr2}$相关问题 更多 >
编程相关推荐