Need one consistent logger across a module or application? Call logging.getLogger(name) instead of constructing Logger directly. The named logger can be retrieved from multiple places, configured once, and reused throughout the application. section 12.1.1
logger_good = logging.getLogger("task_app")
Retrieve a named logger with logging.getLogger rather than creating a Logger instance directly. section 12.1.1
For a module-level logger, use logging.getLogger(__name__). The module’s __name__ supplies its name, giving each module an identifiable logger while preserving shared retrieval for that name. section 12.1.1 section 12.1.5
Prefer getLogger because it:
- Returns the same named logger when called repeatedly. section 12.1.1
- Avoids separately configuring multiple distinct Logger instances for the same module. section 12.1.1
- Works with handlers, logging levels, and formatted records configured for the logger. section 12.6
Avoid duplicate handlers
Repeated setup can attach multiple file handlers to the same logger and produce duplicate records. Check whether the logger has handlers before adding one; existing handlers can also be removed through the logger’s handlers list. section 12.1.5
