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

聖光之護
发布: 2024-11-15 19:23:58
原创
646人浏览过

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

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

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

问题

以下代码演示了此问题:

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

class customfilter(logging.filter):
    def filter(self, record):
        message = record.getmessage()
        return 'custom' in message

customfilter = 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级别的日志信息?

微信 WeLM
微信 WeLM

WeLM不是一个直接的对话机器人,而是一个补全用户输入信息的生成模型。

微信 WeLM 33
查看详情 微信 WeLM

答案

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

import logging

logging.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为何无法输出指定级别的日志信息?的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号