意外的内置记录器行为:记录器名称与“.”重复

2024-06-16 08:24:08 发布

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

似乎内置python记录器在每个'.'上进行拆分,并多次复制记录器

In [1]: import logging, pprint

In [2]: logging.getLogger('\\\\my\\path\\to\\file.py')
Out[2]: <Logger \\my\path\to\file.py (WARNING)>

In [3]: pprint.pprint(logging.Logger.manager.loggerDict)
{'TerminalIPythonApp': <Logger TerminalIPythonApp (WARNING)>,
 '\\\\my\\path\\to\\file': <logging.PlaceHolder object at 0x00000000066F34E0>,
 '\\\\my\\path\\to\\file.py': <Logger \\my\path\to\file.py (WARNING)>,
 'asyncio': <Logger asyncio (WARNING)>,
 'concurrent': <logging.PlaceHolder object at 0x0000000003F81128>,
 'concurrent.futures': <Logger concurrent.futures (WARNING)>,
 'parso': <logging.PlaceHolder object at 0x0000000004E73748>,
 'parso.cache': <Logger parso.cache (WARNING)>,
 'parso.python': <logging.PlaceHolder object at 0x000000000465CEF0>,
 'parso.python.diff': <Logger parso.python.diff (WARNING)>}

为什么要这样做?这是预期的功能吗

编辑 在文档中似乎没有提及这一点,除了名称通常是aa.b之类的层次结构之外。这并不意味着重复日志

logging.getLogger(name=None)

Return a logger with the specified name or, if name is None, return a logger which is the root logger of the hierarchy. If specified, the name is typically a dot-separated hierarchical name like ‘a’, ‘a.b’ or ‘a.b.c.d’. Choice of these names is entirely up to the developer who is using logging.

All calls to this function with a given name return the same logger instance. This means that logger instances never need to be passed between different parts of an application.


Tags: thetopathnamepyobjectismy
1条回答
网友
1楼 · 发布于 2024-06-16 08:24:08

The name is potentially a period-separated hierarchical value, like foo.bar.baz (though it could also be just plain foo, for example). Loggers that are further down in the hierarchical list are children of loggers higher up in the list. For example, given a logger with a name of foo, loggers with names of foo.bar, foo.bar.baz, and foo.bam are all descendants of foo.

从文档https://docs.python.org/3/library/logging.html来看,这是logger对象下的第二段。因此,名称中的点使其成为层次结构下的记录器

相关问题 更多 >