Registry / observability / python-logging-loki

python-logging-loki

JSON →
library0.3.1pypypi✓ verified 25d ago

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-loki
INSTALL
IMPORT
SIG · PYTHON-LOGGING-LOK
P
python-logging-loki
observabilitypythonv0.3.1
Install
2.2s avg
Import
503ms
Disk
19MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.3.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.528s · 21.2MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 2.2s · import 0.478s · 22MB
19MB installed
● package 19MB
Code
Verified usage

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

LokiHandler
from logging_loki import LokiHandler
The primary synchronous logging handler.
LokiQueueHandler
from logging_loki import LokiQueueHandler
A non-blocking handler for high-throughput applications, often preferred in production. It uses `multiprocessing.Queue` internally.

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.

import logging import os from logging_loki import LokiHandler # Configure Loki URL and optional authentication LOKI_URL = os.environ.get('LOKI_URL', 'http://localhost:3100/loki/api/v1/push') LOKI_USERNAME = os.environ.get('LOKI_USERNAME', '') LOKI_PASSWORD = os.environ.get('LOKI_PASSWORD', '') # Create a Loki handler handler_kwargs = { 'url': LOKI_URL, 'tags': {'app': 'my-python-app', 'environment': 'development'}, 'version': '1' # Use '1' for Loki >= 0.4.0 } if LOKI_USERNAME and LOKI_PASSWORD: handler_kwargs['auth'] = (LOKI_USERNAME, LOKI_PASSWORD) handler = LokiHandler(**handler_kwargs) # Get a logger and add the Loki handler logger = logging.getLogger('my-app') logger.setLevel(logging.INFO) logger.addHandler(handler) # Log a message logger.info('Hello, Loki! This is an info message.') logger.warning('This is a warning message with extra data.', extra={'tags': {'component': 'auth'}}) print(f"Logs sent to Loki at {LOKI_URL}")
Debug
Known issues
breakingVersion 0.3.0 dropped official support for Python 3.5. Ensure your environment uses Python 3.6 or newer.
fix
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.
affects: <0.3.0
gotchaThe default Loki API version used by the handler has changed over time. Loki 0.4.0 and newer typically require API version '1' for the `/loki/api/v1/push` endpoint. Older Loki versions might expect API version '0' at `/api/prom/push`.
fix
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.
affects: All versions
gotchaUsing hyphens (`-`) in Loki label keys can cause Loki to return internal server errors during ingestion.
fix
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`.
affects: All versions
gotchaThe `LokiHandler` is blocking, meaning each log call waits for the HTTP request to Loki to complete. In high-throughput applications, this can negatively impact performance.
fix
For production or performance-critical applications, use `LokiQueueHandler` which processes logs asynchronously in a separate thread, preventing the main application thread from blocking.
affects: All versions
gotchaThe `python-logging-loki` library, while functional, has not seen a new release since November 2019 (v0.3.1). This means it may not incorporate the latest Loki features or recent bug fixes, and maintenance might be limited.
fix
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.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'logging_loki'
The `python-logging-loki` library is either not installed in the current environment or is being imported with an incorrect module name.
fix
Ensure the library is installed with `pip install python-logging-loki` and imported using `import logging_loki` or `from logging_loki import LokiHandler`.
TypeError: __init__ missing 1 required positional argument: 'url'
The `LokiHandler` or `LokiQueueHandler` class requires the Loki API endpoint URL to be explicitly provided as the first argument during initialization.
fix
Initialize the handler by passing the `url` keyword argument, e.g., `handler = LokiHandler(url="http://localhost:3100/loki/api/v1/push")`.
requests.exceptions.ConnectionError: HTTPConnectionPool(host='your-loki-host', port=3100): Max retries exceeded with url: /loki/api/v1/push
The Python application cannot establish a connection to the specified Loki server, often due to the server being down, incorrect URL/port, or network issues like a firewall blocking access.
fix
Verify that the Loki server is running and accessible at the provided `url` in the `LokiHandler` configuration, checking the hostname, port, and network connectivity.
TypeError: 'list' object is not callable
The `labels` parameter in `LokiHandler` expects either a dictionary of string key-value pairs or a callable that returns such a dictionary, but a list was provided.
fix
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')}`).
Upgrade
Version history
0.3.1latest on PyPI · released Nov 28, 2019
Audit
Dependencies
pythonrequiredRequires Python 3.6 or newer.
Agent activity
21 hits · last 30 days
node
18
Amazon
1
OpenAI (training)
1
Resources
python-logging-loki — pip install python-logging-loki · libregistry