Python Logging Loki Handler
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.
Warnings
- breaking Version 0.3.0 dropped official support for Python 3.5. Ensure your environment uses Python 3.6 or newer.
- gotcha The 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`.
- gotcha Using hyphens (`-`) in Loki label keys can cause Loki to return internal server errors during ingestion.
- gotcha The `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.
- gotcha The `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.
Install
-
pip install python-logging-loki
Imports
- LokiHandler
from logging_loki import LokiHandler
- LokiQueueHandler
from logging_loki import LokiQueueHandler
Quickstart
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}")