Python Logging Loki Handler

0.3.1 · active · verified Sun Apr 12

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

Install

Imports

Quickstart

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}")

view raw JSON →