Python logger doesn't adhere to the set level

∥☆過路亽.° 提交于 2020-02-04 04:50:28

问题


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')
>>> 

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?


回答1:


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

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())


来源:https://stackoverflow.com/questions/39068465/python-logger-doesnt-adhere-to-the-set-level

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!