Python 日志记录不输出任何内容

新手上路,请多包涵

在我正在编写的 python 脚本中,我正在尝试使用日志记录模块记录事件。我有以下代码来配置我的记录器:

 ERROR_FORMAT = "%(levelname)s at %(asctime)s in %(funcName)s in %(filename) at line %(lineno)d: %(message)s"
DEBUG_FORMAT = "%(lineno)d in %(filename)s at %(asctime)s: %(message)s"
LOG_CONFIG = {'version':1,
              'formatters':{'error':{'format':ERROR_FORMAT},
                            'debug':{'format':DEBUG_FORMAT}},
              'handlers':{'console':{'class':'logging.StreamHandler',
                                     'formatter':'debug',
                                     'level':logging.DEBUG},
                          'file':{'class':'logging.FileHandler',
                                  'filename':'/usr/local/logs/DatabaseUpdate.log',
                                  'formatter':'error',
                                  'level':logging.ERROR}},
              'root':{'handlers':('console', 'file')}}
logging.config.dictConfig(LOG_CONFIG)

当我尝试运行 logging.debug("Some string") 时,控制台没有输出,即使 文档中的此页面logging.debug 应该让根记录器输出消息。为什么我的程序没有输出任何东西,我该如何解决?

原文由 murgatroid99 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 607
2 个回答

默认的日志记录级别是警告。由于您没有更改级别,根记录器的级别仍然是警告。这意味着它将忽略任何级别低于警告的日志记录,包括调试日志记录。

这在 教程 中有解释:

 import logging
logging.warning('Watch out!') # will print a message to the console
logging.info('I told you so') # will not print anything

‘info’ 行不打印任何内容,因为级别高于 info。

要更改级别,只需在根记录器中设置它:

 'root':{'handlers':('console', 'file'), 'level':'DEBUG'}

换句话说,定义一个 level=DEBUG 的处理程序是不够的,实际的日志记录级别也必须是 DEBUG 才能让它输出任何东西。

原文由 Omri Barel 发布,翻译遵循 CC BY-SA 3.0 许可协议

许多年后,Python 记录器似乎仍然存在可用性问题。下面是一些带有示例的解释:

 import logging
# This sets the root logger to write to stdout (your console).
# Your script/app needs to call this somewhere at least once.
logging.basicConfig()

# By default the root logger is set to WARNING and all loggers you define
# inherit that value. Here we set the root logger to NOTSET. This logging
# level is automatically inherited by all existing and new sub-loggers
# that do not set a less verbose level.
logging.root.setLevel(logging.NOTSET)

# The following line sets the root logger level as well.
# It's equivalent to both previous statements combined:
logging.basicConfig(level=logging.NOTSET)

# You can either share the `logger` object between all your files or the
# name handle (here `my-app`) and call `logging.getLogger` with it.
# The result is the same.
handle = "my-app"
logger1 = logging.getLogger(handle)
logger2 = logging.getLogger(handle)
# logger1 and logger2 point to the same object:
# (logger1 is logger2) == True

logger = logging.getLogger("my-app")
# Convenient methods in order of verbosity from highest to lowest
logger.debug("this will get printed")
logger.info("this will get printed")
logger.warning("this will get printed")
logger.error("this will get printed")
logger.critical("this will get printed")

# In large applications where you would like more control over the logging,
# create sub-loggers from your main application logger.
component_logger = logger.getChild("component-a")
component_logger.info("this will get printed with the prefix `my-app.component-a`")

# If you wish to control the logging levels, you can set the level anywhere
# in the hierarchy:
#
# - root
#   - my-app
#     - component-a
#

# Example for development:
logger.setLevel(logging.DEBUG)

# If that prints too much, enable debug printing only for your component:
component_logger.setLevel(logging.DEBUG)

# For production you rather want:
logger.setLevel(logging.WARNING)


一个常见的混淆源来自一个错误初始化的根记录器。考虑一下:

 import logging
log = logging.getLogger("myapp")
log.warning("woot")
logging.basicConfig()
log.warning("woot")

输出:

 woot
WARNING:myapp:woot

根据您的运行时环境和日志级别, 第一行日志(在基本配置之前)可能不会出现在任何地方

原文由 Hubert Grzeskowiak 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题