繁体   English   中英

当级别设置为 logging.DEBUG 时,为什么 log.debug() 不记录?

[英]Why does log.debug() not log when the level is set to logging.DEBUG?

我期待以下代码会输出两个日志行

import logging

log = logging.getLogger('hello')
log.setLevel(logging.DEBUG)
print(log.getEffectiveLevel())
log.debug('debug log')
log.critical('critical log')

输出是

10
critical log

级别正确设置为10对应于DEBUG ),尽管有这个log.debug('debug log')不输出任何东西 - 为什么?

您尚未配置日志记录系统,因此它仍在使用默认值(根记录器的级别 WARN)。

https://docs.python.org/3/library/logging.html#logging.basicConfigbasicConfig

通过创建带有默认格式化程序的 StreamHandler 并将其添加到根记录器,为日志记录系统进行基本配置。

首先使用basicConfig配置日志记录系统将创建您的记录器将使用的处理程序和格式化程序:

logging.basicConfig()
log = logging.getLogger('hello')
log.setLevel(logging.DEBUG)
print(log.getEffectiveLevel())
log.debug('debug log')
log.critical('critical log')

输出:

10
DEBUG:hello:debug log
CRITICAL:hello:critical log

Logger.callHandlers 中,每个处理程序将日志记录的级别与其级别进行比较。 如果没有任何处理程序,它将使用默认值WARNING。

使用StreamHandler它将

将日志输出发送到流,例如 sys.stdout、sys.stderr 或任何类似文件的对象”

根据文档

import logging 
import sys

# Initialize Logger and set Level to DEBUG
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

# Initialize a Handler to print to stdout
handler = logging.StreamHandler(sys.stdout)

# Format Handler output
logFormatter = logging.Formatter(
    "%(asctime)s %(message)s", datefmt="%m/%d/%Y %I:%M:%S %p"
)
handler.setFormatter(logFormatter)

# Set Handler Level to DEBUG
handler.setLevel(logging.DEBUG)
logger.addHandler(handler)

logger.debug('Debug Info')
>>> 09/19/2020 09:01:00 PM Debug Info

您需要添加流处理程序

import logging

log = logging.getLogger('hello')
log.setLevel(logging.DEBUG)

# # Create a file handler to store the logs
file_handler = logging.FileHandler('test.log')
log.addHandler(file_handler)

# # Send output to terminal
stream_handler = logging.StreamHandler()
log.addHandler(stream_handler)

log.debug('debug log')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM