Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $YECBGYFECGEAFWHA as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2

Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $BBWFDDBHHYHDXXAB as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2
Python logging模块自定义Filter为何无法输出指定级别的日志信息?_创想鸟

Python logging模块自定义Filter为何无法输出指定级别的日志信息?

python logging模块自定义filter为何无法输出指定级别的日志信息?

python的logging模块自定义filter无法输出指定级别的日志信息

在python中,使用logging模块来记录日志非常方便。有时,我们需要仅记录特定级别的日志信息。我们可以通过自定义过滤器来实现此目的。但是,在某些情况下,logging模块的自定义filter无法输出指定级别的日志信息。

问题

以下代码演示了此问题:

立即学习“Python免费学习笔记(深入)”;

class customfilter(logging.filter):    def filter(self, record):        message = record.getmessage()        return 'custom' in messagecustomfilter = customfilter()logger: logger = logging.getlogger()logger.setlevel(logging.debug)logger.addfilter(customfilter)logger.debug('this is a debug message with custom keyword')logger.info('this is an info message with custom keyword')logger.warning('this is a warning message with custom keyword')logger.error('this is an error message with custom keyword')logger.critical('this is a critical message with custom keyword')

问题是:为什么上述代码不会在控制台打印出debug和info级别的日志信息?

答案

这不是过滤器的问题,而是使用方式的问题。正确的方法如下:

import logginglogging.getLogger().setLevel(logging.DEBUG)logging.debug("This is a debug message with custom keyword")logging.info("This is an info message with custom keyword")logging.warning("This is a warning message with custom keyword")logging.error("This is an error message with custom keyword")logging.critical("This is a critical message with custom keyword")

原因

这是因为logging模块中的过滤器不是自动应用的。我们需要在日志记录程序中添加一个处理器(handler),处理器才能应用过滤器并输出日志信息。

在修改后的代码中,我们添加了一个streamhandler,该处理器将日志信息输出到控制台。现在,将正确应用过滤器,并且只有包含“custom”关键字的日志信息才会输出。

以上就是Python logging模块自定义Filter为何无法输出指定级别的日志信息?的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1353513.html

赞 (0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
Python 类方法装饰器:如何使用类 A 的方法作为装饰器并访问类 A?
上一篇 2025年12月13日 17:45:32
用 Python 的 Turtle 模块绘制星号组成的正方形,应该怎么做?
下一篇 2025年12月13日 17:45:40

相关推荐

发表回复

登录后才能评论
关注微信