{"id":5304,"library":"logging","title":"Python Standard Library logging module","description":"The `logging` module is a robust and flexible event logging system for Python applications and libraries, integrated into the Python Standard Library since version 2.3. It enables all Python modules to participate in logging, facilitating the integration of messages from applications and third-party modules into a unified log. The module provides extensive functionality to produce structured log messages and direct them to various destinations such as the console, files, or network sockets.","status":"active","version":"Python 3.x Standard Library (introduced in Python 2.3)","language":"en","source_language":"en","source_url":"https://docs.python.org/3/library/logging.html","tags":["standard library","logging","observability","diagnostics","application development"],"install":[],"dependencies":[],"imports":[{"symbol":"logging","correct":"import logging"},{"note":"getLogger is a function directly within the logging module, not a submodule.","wrong":"import logging.getLogger","symbol":"getLogger","correct":"from logging import getLogger"},{"note":"basicConfig is a function directly within the logging module, not a submodule.","wrong":"import logging.basicConfig","symbol":"basicConfig","correct":"from logging import basicConfig"}],"quickstart":{"code":"import logging\nimport os\n\n# Basic configuration for quick scripts (logs to console, INFO level and above)\nlogging.basicConfig(\n    level=logging.INFO,\n    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'\n)\n\n# Recommended for applications: get a named logger\nlogger = logging.getLogger(__name__)\n\n# Configure a file handler for a more complex setup\nlog_file_path = os.environ.get('LOG_FILE', 'application.log')\nfile_handler = logging.FileHandler(log_file_path)\nfile_handler.setLevel(logging.DEBUG)\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s (%(filename)s:%(lineno)d)')\nfile_handler.setFormatter(formatter)\nlogger.addHandler(file_handler)\n\n# Prevent messages from propagating to the root logger handlers (often console) if file is primary\nlogger.propagate = False\n\n# Example log messages\nlogger.debug('This is a debug message - will only go to file handler.')\nlogger.info('This is an info message.')\nlogger.warning('This is a warning message!')\nlogger.error('This is an error message!')\nlogger.critical('This is a critical message!', exc_info=True)\n\nprint(f\"\\nCheck '{log_file_path}' for detailed logs.\")","lang":"python","description":"This quickstart demonstrates both basic `basicConfig` usage for simple scripts and a more robust application-level setup using a named logger with a `FileHandler` and custom formatter. It also shows how to prevent propagation to avoid duplicate messages."},"warnings":[{"fix":"Do not install a package named 'logging' from PyPI. The standard library `logging` module is always available without installation. If encountered, uninstall the PyPI package (`pip uninstall logging`).","message":"Installing `pip install logging` (PyPI package version 0.4.9.6) can conflict with the standard library `logging` module in modern Python environments (Python 2.3+). This legacy PyPI package was intended for very old Python versions (< 2.3) and can break tools like Pipenv if incorrectly installed.","severity":"breaking","affected_versions":"Python 2.3+"},{"fix":"Always call `logging.basicConfig(level=logging.DEBUG)` (or `INFO`, etc.) at the start of your application to ensure all desired message levels are processed.","message":"If `logging.basicConfig()` is not called, the default log level for the root logger is `WARNING`. This means `DEBUG` and `INFO` messages will be silently ignored and not appear in output unless the logger's level is explicitly set lower.","severity":"gotcha","affected_versions":"All Python 3.x versions"},{"fix":"For application code, prefer `logger = logging.getLogger(__name__)` and then `logger.info(...)`. For library code, defer configuration to the application using your library, usually by adding only a `NullHandler`.","message":"Using global functions like `logging.debug()` directly operates on the *root logger*. For structured applications, it's recommended to create and configure named loggers using `logging.getLogger(__name__)` for better modularity and control. Libraries should never configure the root logger directly.","severity":"gotcha","affected_versions":"All Python 3.x versions"},{"fix":"When developing a library, add `logging.getLogger(__name__).addHandler(logging.NullHandler())` to prevent emitting messages if no other configuration is present, and avoid adding any other handlers.","message":"Libraries should generally avoid adding handlers to their loggers other than `logging.NullHandler`. This allows the application using the library to fully control where and how the library's logs are processed, preventing unexpected output or conflicts with the application's logging configuration.","severity":"gotcha","affected_versions":"All Python 3.x versions"},{"fix":"For async applications, consider using `logging.handlers.QueueHandler` and `logging.handlers.QueueListener` to offload actual logging I/O to a separate thread, preventing the main event loop from blocking.","message":"Logging from asynchronous code using blocking network or file handlers can stall the event loop, impacting performance. Standard `StreamHandler` or `FileHandler` can be blocking operations.","severity":"gotcha","affected_versions":"All Python 3.x versions with async code"},{"fix":"Consider using structured logging (e.g., JSON output with `python-json-logger`) where messages are explicitly contained within a field, or ensure custom formatters properly escape or sanitize potentially disruptive characters from user-provided input.","message":"Log formatters can be vulnerable to log injection if raw newlines or other control characters within log messages are not properly handled (e.g., quoted or sanitized). This can lead to misinterpretation of logs by parsers or security tools.","severity":"gotcha","affected_versions":"All Python 3.x versions"}],"env_vars":null,"last_verified":"2026-04-13T00:00:00.000Z","next_check":"2026-07-12T00:00:00.000Z"}