更新时间:2023-02-16 17:45:15
您会忽略以下事实:a)每个记录器的最终祖先都是 root 记录器(默认情况下级别为WARNING
) b)记录器和处理程序都具有级别.
You are missing the fact that a) every logger's ultimate ancestor is the root logger (which has level WARNING
by default) and b) that both, loggers and handlers have levels.
文档状态:
创建记录器时,级别设置为NOTSET(这将导致 当记录器是根记录器时要处理的消息,或者 当记录器为非根记录器时委托给父级).
When a logger is created, the level is set to NOTSET (which causes all messages to be processed when the logger is the root logger, or delegation to the parent when the logger is a non-root logger).
因此,您将使用默认级别NOTSET
创建记录器和StreamHandler.您的记录器是 root 记录器的隐式后代.您可以使用该处理程序将处理程序设置为级别DEBUG
,但不能将 logger 设置为级别.
由于记录器上的级别仍为NOTSET
,因此在发生日志事件时,将遍历其祖先链...
So, you create a logger and a StreamHandler with their default level NOTSET
. Your logger is an implicit descendant of the root logger. You set the handler to level DEBUG
, but not the logger using that handler.
Since the level on your logger still is NOTSET
, when a log event occurs, its chain of ancestors is traversed ...
...直到找到一个非NOTSET级别的祖先,或者 到达根.
... until either an ancestor with a level other than NOTSET is found, or the root is reached.
[...]
如果到达根目录,并且其级别为NOTSET,则所有 消息将被处理.否则,将使用根级别 作为有效级别.
If the root is reached, and it has a level of NOTSET, then all messages will be processed. Otherwise, the root’s level will be used as the effective level.
这意味着,您立即结束 root 记录器以确定有效的日志级别;根据 root 记录器的默认值,它设置为WARNING
.
您可以使用parent
和level
属性以及logger
对象上的getEffectiveLevel
方法进行检查:
Which means, you immediately end up at the root logger to determine the effective log level; it is set to WARNING
as per the root logger's default.
You can check this with the parent
and level
properties and the getEffectiveLevel
method on the logger
object:
logThis = get_logger()
print(logThis.parent) # <RootLogger root (WARNING)>
print(logThis.level) # 0 (= NOTSET)
print(logThis.getEffectiveLevel()) # 30 (= WARNING) from root logger
要让记录器自行处理所需级别以上的消息,只需通过get_logger
函数中的logger.setLevel(level)
在记录器上进行设置即可.
To have your logger handle the messages on and above the desired level itself, simply set it on the logger via logger.setLevel(level)
in your get_logger
function.