You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python logging中__name__取值与模块导入方式的关联问题

The Catch with 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 module bar uses the syntax from pkg import foo to import the sibling module foo, then foo.__name__ will be pkg.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) uses import foo to import that same foo module, foo.__name__ will only be foo. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:22:04