Python根记录器名称及name='root'设级别无效问题咨询
Python Root Logger: Name and Configuration Quirks
Q1: What's the name of Python's root logger?
Python's root logger doesn't use the name "root" — its actual identifier is an empty string (""). You can verify this with a quick test:
import logging print(logging.getLogger().name) # Outputs an empty string
Q2: Why can't I set the root logger's level with logging.getLogger('root'), but can with no arguments?
This is a super common gotcha! Let's break it down simply:
- Calling
logging.getLogger()without arguments gives you the actual top-level root logger instance. This is the parent of all other loggers, and modifying its settings affects the entire logging hierarchy. - Passing
"root"as the name creates (or fetches) a regular child logger named "root" — not the actual root logger. This is just a standard logger in the hierarchy, so changing its level won't impact the root logger's behavior at all.
Here's a code snippet to show the difference clearly:
import logging # Correct: Get the real root logger root_logger = logging.getLogger() print(f"Real root logger name: '{root_logger.name}'") # Prints '' root_logger.setLevel(logging.INFO) # This updates the root logger's level # Incorrect: This is a child logger named "root" fake_root = logging.getLogger("root") print(f"Fake root logger name: '{fake_root.name}'") # Prints 'root' fake_root.setLevel(logging.INFO) # Only affects this child logger, not the real root
The root logger is the top of the logging hierarchy, identified solely by its empty string name. All loggers without an explicit parent inherit settings from it — but a logger named "root" is just another node in the tree, not the top-level root itself.
内容的提问来源于stack exchange,提问作者Kurt Peek
相关产品推荐
相关产品推荐

