如何在Python的日志记录工具中添加自定义日志级别 [英] How to add a custom loglevel to Python's logging facility

查看:558
本文介绍了如何在Python的日志记录工具中添加自定义日志级别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的应用程序使用日志级别TRACE(5),因为我认为debug()不足.另外,log(5, msg)不是我想要的.如何将自定义日志级别添加到Python记录器?

I'd like to have loglevel TRACE (5) for my application, as I don't think that debug() is sufficient. Additionally log(5, msg) isn't what I want. How can I add a custom loglevel to a Python logger?

我有一个mylogger.py,内容如下:

import logging

@property
def log(obj):
    myLogger = logging.getLogger(obj.__class__.__name__)
    return myLogger

在我的代码中,我通过以下方式使用它:

In my code I use it in the following way:

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的非常好的建议的出色解决方案.

Edit (Dec 8th 2016): I changed the accepted answer to pfa's which is, IMHO, an excellent solution based on the very good proposal from Eric S.

推荐答案

@Eric S.

Eric S.的回答很好,但是我通过实验得知,这将始终导致打印以新的调试级别记录的消息-不管设置为什么日志级别.因此,如果您将新的级别编号设置为9,则调用setLevel(50),则会错误地打印较低级别消息.

Eric S.'s answer is excellent, but I learned by experimentation that this will always cause messages logged at the new debug level to be printed -- regardless of what the log level is set to. So if you make a new level number of 9, if you call setLevel(50), the lower level messages will erroneously be printed.

为防止这种情况发生,您需要在"debugv"函数内的另一行检查是否实际启用了相关日志记录级别.

To prevent that from happening, you need another line inside the "debugv" function to check if the logging level in question is actually enabled.

固定的示例,该示例检查是否启用了日志记录级别:

Fixed example that checks if the logging level is 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,.debug等)的作用.

If you look at the code for class Logger in logging.__init__.py for Python 2.7, this is what all the standard log functions do (.critical, .debug, etc.).

我显然不能发表因缺乏声誉而对其他人的回答的回复...希望埃里克(Eric)会在看到这一点后更新他的帖子. =)

I apparently can't post replies to others' answers for lack of reputation... hopefully Eric will update his post if he sees this. =)

这篇关于如何在Python的日志记录工具中添加自定义日志级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆