【问题标题】:How to use Python's built in logger for INFO messages如何使用 Python 的内置记录器记录 INFO 消息
【发布时间】:2016-05-04 01:14:10
【问题描述】:

我在使用内置记录器模块时遇到了困难。显示警告消息,但不显示信息消息。像这样:

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

成功了!问题是为什么第一个版本不起作用。

注意:问题已被编辑。

【问题讨论】:

  • 奇怪。如果您没有设置 level=logging.DEBUG 参数,那将是预期的行为。它对我有用,正如你所拥有的那样。
  • Thomas 链接中的代码对我有用。使用有效的代码行在下面查看我的答案。
  • 仅供参考:PyScripter 中存在一个错误(否则它是一个很好的调试环境),并且在使用推荐的远程 Python 解释器时无法正确显示日志消息。

标签: python logging


【解决方案1】:

我对您的输出感到困惑,可能值得仅使用日志记录代码重试:例如

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 了解更多详情。

【讨论】:

  • 谢谢。我再次尝试使用您的代码并且它有效。这让我找到了问题所在。请参阅修改后的问题。
【解决方案2】:

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

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

参考:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-30
    • 1970-01-01
    • 2018-04-29
    • 1970-01-01
    • 2011-12-24
    • 2023-02-01
    • 1970-01-01
    相关资源
    最近更新 更多