如何使用Python的内置记录器来处理INFO消息

时间:2016-05-04 01:14:10

标签: python logging

我对内置记录器模块有困难。警告消息显示但不显示INFO消息。像这样:

Python 2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import logging
>>> logging.info('Info')  # This line was inserted.
>>> logging.basicConfig(level=logging.DEBUG)
>>> logging.warning('Warning')
WARNING:root:Warning
>>> logging.info('Info')
>>>

有趣的是,从我的办公桌走了一个小时左右,然后开始新的会议后,我得到了以下内容:

Python 2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import logging
>>> logging.basicConfig(level=logging.DEBUG)
>>> logging.warning('Warning')
WARNING:root:Warning
>>> logging.info('Info')
INFO:root:Info
>>> 

有效!问题是为什么第一个版本不起作用。

注意:问题已经过编辑。

2 个答案:

答案 0 :(得分:2)

我对您的输出感到困惑,可能只需使用日志记录代码再试一次:例如

Python 2.7.10 (default, May 23 2015, 09:40:32)
Type "help", "copyright", "credits" or "license" for more information.
>>> import logging
>>> logging.basicConfig(level=logging.DEBUG)
>>> logging.warning('warning')
WARNING:root:warning
>>> logging.debug('debug')
DEBUG:root:debug
>>> logging.info('info')
INFO:root:info

您可以参考https://docs.python.org/2/library/logging.html获取更多详细信息。

答案 1 :(得分:-1)

logging设置的默认级别为警告。不显示该级别以下的任何消息(例如信息消息)。要更改它,请使用以下代码:

logging.getLogger().setLevel(logging.INFO)

<强>参考:

logging.info doesn't show up on console but warn and error do