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

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

问题描述

我想为我的应用程序设置日志级别跟踪 (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:

I've a mylogger.py with the following content:

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),则会错误地打印 lower level 消息.

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__.pyclass Logger 的代码,这就是所有标准日志函数所做的(.critical, .调试等).

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天全站免登陆