Loki Logger Handler

1.1.2 · active · verified Thu Apr 16

Loki Logger Handler is a Python logging handler designed for transmitting logs to Grafana Loki. It formats logs in JSON by default, allows custom label definitions, and supports extracting extra keys from log records as labels or structured metadata. The library is currently at version 1.1.2 and appears to be under active development with regular updates addressing compatibility and feature enhancements.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to configure the `LokiLoggerHandler` with Python's standard `logging` module. It sets up a handler to send logs to a Loki instance, including static labels and dynamically extracting `extra` dictionary keys as labels. Ensure the `LOKI_URL` environment variable is set or replace the placeholder.

import logging
import os
from loki_logger_handler.loki_logger_handler import LokiLoggerHandler, LoggerFormatter

LOKI_URL = os.environ.get('LOKI_URL', 'http://localhost:3100/loki/api/v1/push')

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

# Configure Loki Handler
loki_handler = LokiLoggerHandler(
    url=LOKI_URL,
    labels={
        'application': 'my-python-app',
        'environment': 'dev'
    },
    # Optionally, specify keys from 'extra' dict to be used as labels
    label_keys={'user_id', 'request_id'},
    # For Loki 3.0+ and structured metadata
    # enable_structured_loki_metadata=True,
    # loki_metadata_keys={'metadata_field'}
)

# Optionally, use a specific formatter (LoggerFormatter is default for standard logging)
loki_handler.setFormatter(LoggerFormatter())

logger.addHandler(loki_handler)

# Example logging
logger.info('Application started successfully.')
logger.warning('Potential issue detected.', extra={'user_id': '12345'})

try:
    1 / 0
except ZeroDivisionError:
    logger.error('A critical error occurred!', exc_info=True, extra={'request_id': 'abc-123'})

view raw JSON →