Registry / observability / logging

logging

JSON →
library0.4.9.6pypypiunverified

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.

pip install logging
INSTALL
IMPORT
SIG · LOGGING
L
logging
observabilitypythonv0.4.9.6
harness data pending
Install & Compatibility
Where this runs

No compatibility data collected yet for this library.

Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

logging
import logging
getLogger
from logging import getLogger
import logging.getLogger
getLogger is a function directly within the logging module, not a submodule.
basicConfig
from logging import basicConfig
import logging.basicConfig
basicConfig is a function directly within the logging module, not a submodule.

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.

import logging import os # Basic configuration for quick scripts (logs to console, INFO level and above) logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) # Recommended for applications: get a named logger logger = logging.getLogger(__name__) # Configure a file handler for a more complex setup log_file_path = os.environ.get('LOG_FILE', 'application.log') file_handler = logging.FileHandler(log_file_path) file_handler.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s (%(filename)s:%(lineno)d)') file_handler.setFormatter(formatter) logger.addHandler(file_handler) # Prevent messages from propagating to the root logger handlers (often console) if file is primary logger.propagate = False # Example log messages logger.debug('This is a debug message - will only go to file handler.') logger.info('This is an info message.') logger.warning('This is a warning message!') logger.error('This is an error message!') logger.critical('This is a critical message!', exc_info=True) print(f"\nCheck '{log_file_path}' for detailed logs.")
Debug
Known issues
breakingInstalling `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.
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`).
affects: Python 2.3+
gotchaIf `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.
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.
affects: All Python 3.x versions
gotchaUsing 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.
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`.
affects: All Python 3.x versions
gotchaLibraries 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.
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.
affects: All Python 3.x versions
gotchaLogging from asynchronous code using blocking network or file handlers can stall the event loop, impacting performance. Standard `StreamHandler` or `FileHandler` can be blocking operations.
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.
affects: All Python 3.x versions with async code
gotchaLog 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.
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.
affects: All Python 3.x versions
Errors
Common errors & fixes
python logging duplicate messages
Log messages appear multiple times because either several handlers are attached to the same logger (especially the root logger when `basicConfig` is called repeatedly or by imported libraries) or log records are propagating up to ancestor loggers that also have handlers.
fix
Ensure that handlers are not added multiple times to a logger. If `logging.basicConfig()` is used, call it only once at the application's entry point. For custom loggers, consider setting `logger.propagate = False` if you do not want messages to be passed to parent loggers, or manually clear existing handlers using `logger.handlers.clear()` before reconfiguring.
AttributeError: module 'logging' has no attribute 'handlers'
The `logging.handlers` submodule, which contains specialized handler classes like `RotatingFileHandler` or `TimedRotatingFileHandler`, is not automatically imported when you simply `import logging`. You must explicitly import the submodule to access its contents.
fix
To fix this, explicitly import the `logging.handlers` submodule: `import logging.handlers`.
python logging not writing to file
This often occurs because `logging.basicConfig()` is called after a handler has already been configured on the root logger (e.g., by another imported module), rendering subsequent `basicConfig()` calls ineffective. Other causes include an incorrect logging level (messages are below the configured threshold) or issues with file path/permissions.
fix
Ensure `logging.basicConfig()` is called early in your application's lifecycle, preferably only once. Verify that the `level` parameter in `basicConfig` or on your specific logger/handler is set to capture the desired messages (e.g., `logging.DEBUG`). Also, check the file path and directory permissions for the log file.
No handlers could be found for logger "your_logger_name"
This warning indicates that a logger instance has been created and used (e.g., `logging.getLogger('my_app')`), but no handlers have been configured for that specific logger or any of its ancestor loggers (including the root logger) to process the log messages. In Python 3, this message is printed to `stderr` by default when no handlers are configured.
fix
You must configure at least one handler to process log messages. For a simple setup, call `logging.basicConfig()` at the start of your application. For more complex setups, create and add specific handlers (e.g., `logging.StreamHandler()` or `logging.FileHandler()`) to your logger instance using `logger.addHandler(handler)`.
Upgrade
Version history
0.4.9.6latest on PyPI · released Jun 4, 2013
Audit
Dependencies

No dependency data recorded yet.

Agent activity
13 hits · last 30 days
node
10
OpenAI (training)
2
Resources