将记录器消息存储在字符串中

将记录器消息存储在字符串中,第1张

记录器消息存储在字符串中

它可以像登录到

StringIO
对象一样简单:

import loggingtry:    from cStringIO import StringIO      # Python 2except importError:    from io import StringIOlog_stream = StringIO()    logging.basicConfig(stream=log_stream, level=logging.INFO)logging.info('hello world')logging.warning('be careful!')logging.debug("you won't see this")logging.error('you will see this')logging.critical('critical is logged too!')print(log_stream.getvalue())

输出量

INFO:root:hello world警告:root:请小心!错误:根:您将看到此也记录了CRITICAL:root:critical!

如果您只想记录WARN,INFO和ERROR级别的消息,则可以使用过滤器进行记录。

LevelFilter
下面检查每个日志记录的级别号,仅允许所需级别的那些记录:

import loggingtry:    from cStringIO import StringIO      # Python 2except importError:    from io import StringIOclass LevelFilter(logging.Filter):    def __init__(self, levels):        self.levels = levels    def filter(self, record):        return record.levelno in self.levelslog_stream = StringIO()    logging.basicConfig(stream=log_stream, level=logging.NOTSET)logging.getLogger().addFilter(LevelFilter((logging.INFO, logging.WARNING, logging.ERROR)))logging.info('hello world')logging.warning('be careful!')logging.debug("you won't see this")logging.error('you will see this')logging.critical('critical is no longer logged!')print(log_stream.getvalue())

输出量

INFO:root:hello world警告:root:请小心!错误:根:您将看到此


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5663021.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存