Python记录器不符合设置的级别 [英] Python logger doesn't adhere to the set level

查看:82
本文介绍了Python记录器不符合设置的级别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Python3交互式提示中创建了一个记录器:

I created a logger in the Python3 interactive prompt:

>>> import logging
>>> logger = logging.getLogger('foo')
>>> logger.setLevel(logging.INFO)
>>> logger.warn('bar')
bar
>>> logger.info('bar')
>>> 

在这种情况下,我希望logger.info输出bar,因为我已经明确设置了日志记录级别.但这不是事实.为什么?

I'd expect logger.info to output the bar in this case, since I've explicitly set the logging level. But it's not the case here. Why?

推荐答案

实际上,在您的情况下,由于您尚未配置日志记录,因此两者都不应该输出任何内容.您需要运行logging.basicConfig()或向记录器添加处理程序,以获取任何输出:

Actually, in your case neither should output anything since you haven't configured logging. You'll need to run logging.basicConfig() or add a handler to your logger to expect any output:

In [1]: import logging

In [2]: logger = logging.getLogger('foo')

In [3]: logger.setLevel(logging.INFO)

In [4]: logger.warn('foo')
No handlers could be found for logger "foo"

In [5]: logger.info('foo')

In [6]: logging.basicConfig()

In [7]: logger.info('foo')
INFO:foo:foo

In [8]: logger.warn('foo')
WARNING:foo:foo

正如Larsks在评论中所提到的,在Python 3中,日志记录默认配置为级别WARNING(这意味着如果使用warning()或默认更高级别,则将获得输出).在您的情况下,您可以调用logging.basicConfig()来为所有记录器添加默认处理程序,如上例所示,或者将处理程序添加到记录器中:

As mentioned by larsks in the comments, in Python 3 logging is configured by default with level WARNING (which means you'll get output if you use warning() or any higher level by default). In your case, you either can call logging.basicConfig() to add a default handler to all loggers as in the example above, or add a handler to your logger:

logger.addHandler(logging.StreamHandler())

这篇关于Python记录器不符合设置的级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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