The `python-logging-loki` library provides a handler for Python's standard `logging` module, allowing applications to send logs directly to Grafana Loki. It includes `LokiHandler` for synchronous logging and `LokiQueueHandler` for asynchronous, non-blocking log submission. The library supports custom labels, basic HTTP authentication, and explicit Loki API versioning. The current stable version is 0.3.1.
pip install python-logging-lokiVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to configure a `LokiHandler` to send logs to a Loki instance. It includes setting the Loki URL, adding default and extra tags, and handling optional basic authentication using environment variables. It explicitly sets the Loki API version to '1' for compatibility with modern Loki deployments.
Upgrade Python to 3.6+ if using an older version of the library or remain on an older library version if Python 3.5 is strictly required.
Always explicitly set the `version` parameter in `LokiHandler` or `LokiQueueHandler` to '1' (recommended for modern Loki) or '0' to match your Loki instance's API.
When defining `tags` or `extra={'tags': ...}`, use underscores (`_`) instead of hyphens for label keys to ensure Loki processes them correctly. For example, use `my_app_tag` instead of `my-app-tag`.For production or performance-critical applications, use `LokiQueueHandler` which processes logs asynchronously in a separate thread, preventing the main application thread from blocking.
Evaluate if the current feature set meets your needs. Consider contributing to the project or forking it if specific new features or bug fixes are required. Be aware that community alternatives like `python-loki-logger` (unrelated project) exist with more recent activity.
Ensure the library is installed with `pip install python-logging-loki` and imported using `import logging_loki` or `from logging_loki import LokiHandler`.
Initialize the handler by passing the `url` keyword argument, e.g., `handler = LokiHandler(url="http://localhost:3100/loki/api/v1/push")`.
Verify that the Loki server is running and accessible at the provided `url` in the `LokiHandler` configuration, checking the hostname, port, and network connectivity.
Provide `labels` as a dictionary (e.g., `labels={'key': 'value'}`) or a function that returns a dictionary (e.g., `labels=lambda: {'app': os.getenv('APP_NAME')}`).