Python logging中__name__取值与模块导入方式的关联问题
logging.getLogger(__name__) and Import Syntax Let's start with what the official Python logging docs state:
日志器名称可为点分隔的层级值,如foo.bar.baz,其层级与Python包层级类似;若按推荐用法logging.getLogger(name)为每个模块创建日志器,__name__应是模块在包命名空间中的名称。
But here's a gotcha that trips up many developers when working with package modules: the value of __name__ for a module isn't fixed—it depends entirely on how you import it, even when importing a sibling module within the same package.
From hands-on testing:
- Inside a package named
pkg, if modulebaruses the syntaxfrom pkg import footo import the sibling modulefoo, thenfoo.__name__will bepkg.foo. This aligns perfectly with what the logging docs expect, giving you a logger name that properly reflects the package hierarchy. - However, if another module in the same package (like
baz) usesimport footo import that samefoomodule,foo.__name__will only befoo. This breaks the recommended logging naming convention, as the logger won't carry the package prefix, losing the hierarchical structure the docs intend.
In short, the "recommended" approach of using logging.getLogger(__name__) only works as intended when you use absolute imports (or explicit relative imports like from . import foo) for sibling modules. Implicit relative imports (plain import foo within the same package) alter the __name__ value, resulting in logger names that don't match your package's structure—this is definitely not the behavior you'd expect when following the official documentation.
内容的提问来源于stack exchange,提问作者Steve Cohen

