简体   繁体   English

Python记录奇怪的行为

[英]Python logging strange behavior

Consider this code: 考虑以下代码:

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)

I create this handler in serverutils.logutils , a custom python module. 我在自定义python模块serverutils.logutils创建此处理程序。 Then, I import it into my daemon service script, which is run by root user: 然后,将其导入我的守护程序服务脚本中,该脚本由root用户运行:

from serverutils.logutils import ubuntu_logger as logger, DEFAULT_LOGGING_CONFIG

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

With the code above, the ubuntu_logger simply does nothing at all. 使用上面的代码, ubuntu_logger根本不执行任何操作。 After changing the code like below, ubuntu_logger works as expected, in addition to the root 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...')

What am I missing? 我想念什么?

You'll need to set a log level on ubuntu_logger : 您需要在ubuntu_logger上设置日志级别:

ubuntu_logger.setLevel(logging.DEBUG)

otherwise it'll find the WARNING level set by default on the root logger instead. 否则,它将在根记录器上找到默认设置的WARNING级别。 When you ran logging.basicConfig() you set the log level of the root logger to DEBUG , so the ubuntu_logger picked that up and no longer filtered your INFO level log messages. 当您运行logging.basicConfig() ,将根记录器的日志级别设置为DEBUG ,因此ubuntu_logger选中了它,并且不再过滤您的INFO级别日志消息。

What normally happens when you call one of the logger.log() helper functions (such as logger.info() ) is that the logger checks if the current level allows for that message. 当您调用logger.log()帮助函数之一(例如logger.info() )时,通常发生的情况是,记录器检查当前级别是否允许该消息。 If it's own level is NOTSET (the default), the parent log object is consulted, etc. until the root is found, where the default is WARNING . 如果它自己的级别为NOTSET (默认值),则将查询父日志对象, NOTSET ,直到找到根为止,默认值为WARNING

You may want to disable log propagation if you have handlers set on a specific logger: 如果您在特定的记录器上设置了处理程序,则可能要禁用日志传播:

ubuntu_logger.propagate = False

otherwise the root logger is also asked to handle the log message. 否则, 要求根记录器处理日志消息。 Propagation does not affect at what level a logger starts emitting messages. 传播不会影响记录器开始发出消息的级别。

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

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