Python记录奇怪的行为

标签 python ubuntu logging module daemon

考虑这段代码:

ubuntu_logger = logging.getLogger('ubuntu-logger')

mail_handler = MailHandler()
mail_handler.setLevel(logging.INFO)
ubuntu_logger.addHandler(mail_handler)

filepath = "/home/ubuntu/logs/central.log"
formatter = logging.Formatter('[%(asctime)s - %(name)s - %(levelname)s]: %(message)s')

central_handler = logging.handlers.RotatingFileHandler(
    filename=filepath,
    mode="a+"
)
central_handler.setLevel(logging.DEBUG)
central_handler.setFormatter(formatter)
ubuntu_logger.addHandler(central_handler)

我在 serverutils.logutils 中创建了这个处理程序,一个自定义的python模块。然后,我将它导入到由 root 运行的守护程序服务脚本中。用户:
from serverutils.logutils import ubuntu_logger as logger, DEFAULT_LOGGING_CONFIG

logger.info('pydaemons launching...')

使用上面的代码,ubuntu_logger根本什么都不做。更改如下代码后,ubuntu_logger除根记录器外,按预期工作:
import logging
from serverutils.logutils import ubuntu_logger as logger, DEFAULT_LOGGING_CONFIG

config = DEFAULT_LOGGING_CONFIG # Fancy format, log level DEBUG
config.update(filename='/home/ubuntu/test.log')

logging.basicConfig(**config)

logging.error('omg, this works')
logger.info('pydaemons launching...')

我错过了什么?

最佳答案

您需要在 ubuntu_logger 上设置日志级别:

ubuntu_logger.setLevel(logging.DEBUG)

否则它会找到 WARNING默认情况下在根记录器上设置的级别。当你运行 logging.basicConfig()您将根记录器的日志级别设置为 DEBUG ,所以 ubuntu_logger拿起它,不再过滤你的INFO级别的日志消息。

当您调用 logger.log() 之一时通常会发生什么?辅助函数(例如 logger.info() )是记录器检查当前级别是否允许该消息。如果它自己的等级是NOTSET (默认),查询父日志对象等,直到找到根,这里默认为WARNING .

如果您在特定记录器上设置了处理程序,您可能希望禁用日志传播:
ubuntu_logger.propagate = False

否则,还会要求根记录器处理日志消息。传播不会影响记录器在什么级别开始发送消息。

关于Python记录奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26212174/

相关文章:

Python,理解霍夫曼代码

c++ - 加载共享库时出错 : libboost_iostreams. so.1.59.0: 无法打开共享对象文件: 没有这样的文件或目录

python - pip freeze 不显示包

SSL 错误 : OCSP_basic_verify() failed

tomcat - 如何在 Tomcat 控制台日志中记录 sessionId?

python - 如何通过 python adwords API 获取 adwords 转换以及 gclid?

python - 列表理解,获取匹配的嵌套项

linux - 从 shell 脚本中调用 Curl

mongodb - 日志查看实用程序数据库选择

python - Tornado/python 中的 if else 语句