什么是子记录器的默认处理程序?

2024-09-30 12:27:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道根记录器有lastResort处理程序,如果根记录器处理程序没有使用logging.basicConfig配置,并且用户使用logging.info/debug/warning/error/critical("some msg"),则该处理程序会打印到控制台 或logger = logging.gerLogger()后跟logger.info/debug/warning/error/critical("some msg")

但是对于使用logger = logging.getLogger("someName")创建的子记录器,当我们编写logger.info/debug/warning/error/critical("some msg"),并且没有配置处理程序时,当propagate = true,那么子记录器是否有任何默认处理程序?或者它会返回到祖先的处理程序,然后返回到根记录器的处理程序,如果祖先/根记录器没有处理程序,则返回到根记录器lastResort处理程序

如果propagate设置为false,那么是否会有一些默认的处理程序分配给子记录器


Tags: 用户debuginfo处理程序loggingmsgerrorsome
1条回答
网友
1楼 · 发布于 2024-09-30 12:27:35

简而言之:logging.lastResort

长话短说:

根据doc,如果没有提供日志记录配置,那么:

The event is output using a ‘handler of last resort’, stored in logging.lastResort. This internal handler is not associated with any logger, and acts like a StreamHandler which writes the event description message to the current value of sys.stderr (therefore respecting any redirections which may be in effect). No formatting is done on the message - just the bare event description message is printed. The handler’s level is set to WARNING, so all events at this and greater severities will be output.

同样根据logging source code

class Logger(Filterer):
    # ...
    def callHandlers(self, record):
        # ...
        # found is the number of handlers
        if (found == 0):
            if lastResort:
                if record.levelno >= lastResort.level:
                    lastResort.handle(record)

因此,如果没有处理程序,它将调用lastResort,不管它是根记录器还是子记录器lastResort实际上是^{},这是:

class _StderrHandler(StreamHandler):
    """
    This class is like a StreamHandler using sys.stderr, but always uses
    whatever sys.stderr is currently set to rather than the value of
    sys.stderr at handler construction time.
    """
    def __init__(self, level=NOTSET):
        """
        Initialize the handler.
        """
        Handler.__init__(self, level)

    @property
    def stream(self):
        return sys.stderr

因此您可以看到它实际上是一个具有警告级别的StreamHandler

相关问题 更多 >

    热门问题