我想为我的应用程序设置日志级别 TRACE (5),因为我认为 debug()
还不够。另外 log(5, msg)
不是我想要的。如何向 Python 记录器添加自定义日志级别?
我有一个 mylogger.py
,内容如下:
import logging
@property
def log(obj):
myLogger = logging.getLogger(obj.__class__.__name__)
return myLogger
在我的代码中,我以下列方式使用它:
class ExampleClass(object):
from mylogger import log
def __init__(self):
'''The constructor with the logger'''
self.log.debug("Init runs")
现在我想调用 self.log.trace("foo bar")
编辑(2016 年 12 月 8 日):我将接受的答案更改为 pfa's恕我直言,这是基于 Eric S 非常好的建议的出色解决方案。
最佳答案
致 2022 年及以后阅读的人:您可能应该在此处查看当前评分第二高的答案:https://stackoverflow.com/a/35804945/1691778
我的原始答案如下。
--
@Eric S.
Eric S. 的回答非常好,但我通过实验了解到,这总是会导致打印在新调试级别记录的消息——无论日志级别设置为什么。所以如果你新建一个级别号9
,如果你调用setLevel(50)
,lower level信息会被错误的打印出来。
To prevent that from happening, you need another line inside the "debugv" function to check if the logging level in question is actually enabled.
检查日志级别是否启用的固定示例:
import logging
DEBUG_LEVELV_NUM = 9
logging.addLevelName(DEBUG_LEVELV_NUM, "DEBUGV")
def debugv(self, message, *args, **kws):
if self.isEnabledFor(DEBUG_LEVELV_NUM):
# Yes, logger takes its '*args' as 'args'.
self._log(DEBUG_LEVELV_NUM, message, args, **kws)
logging.Logger.debugv = debugv
如果您查看 Python 2.7 的 logging.__init__.py
中 class Logger
的代码,这就是所有标准日志函数所做的事情(.critical、.调试等)。
由于缺乏声誉,我显然无法回复其他人的答案...希望 Eric 看到此消息后会更新他的帖子。 =)
关于python - 如何将自定义日志级别添加到 Python 的日志记录工具,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2183233/