{"id":8294,"library":"loki-logger-handler","title":"Loki Logger Handler","description":"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.","status":"active","version":"1.1.2","language":"en","source_language":"en","source_url":"https://github.com/xente/loki-logger-handler","tags":["logging","loki","grafana","handler","json","loguru"],"install":[{"cmd":"pip install loki-logger-handler","lang":"bash","label":"Install stable version"}],"dependencies":[{"reason":"Used internally for making HTTP POST requests to the Loki API endpoint.","package":"requests","optional":false}],"imports":[{"symbol":"LokiLoggerHandler","correct":"from loki_logger_handler.loki_logger_handler import LokiLoggerHandler"},{"note":"Standard Python logging formatter provided by the library.","symbol":"LoggerFormatter","correct":"from loki_logger_handler.loki_logger_handler import LoggerFormatter"},{"note":"Formatter specifically for Loguru users.","symbol":"LoguruFormatter","correct":"from loki_logger_handler.loki_logger_handler import LoguruFormatter"}],"quickstart":{"code":"import logging\nimport os\nfrom loki_logger_handler.loki_logger_handler import LokiLoggerHandler, LoggerFormatter\n\nLOKI_URL = os.environ.get('LOKI_URL', 'http://localhost:3100/loki/api/v1/push')\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\n# Configure Loki Handler\nloki_handler = LokiLoggerHandler(\n    url=LOKI_URL,\n    labels={\n        'application': 'my-python-app',\n        'environment': 'dev'\n    },\n    # Optionally, specify keys from 'extra' dict to be used as labels\n    label_keys={'user_id', 'request_id'},\n    # For Loki 3.0+ and structured metadata\n    # enable_structured_loki_metadata=True,\n    # loki_metadata_keys={'metadata_field'}\n)\n\n# Optionally, use a specific formatter (LoggerFormatter is default for standard logging)\nloki_handler.setFormatter(LoggerFormatter())\n\nlogger.addHandler(loki_handler)\n\n# Example logging\nlogger.info('Application started successfully.')\nlogger.warning('Potential issue detected.', extra={'user_id': '12345'})\n\ntry:\n    1 / 0\nexcept ZeroDivisionError:\n    logger.error('A critical error occurred!', exc_info=True, extra={'request_id': 'abc-123'})\n","lang":"python","description":"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."},"warnings":[{"fix":"Upgrade to version 1.0.0 or higher to ensure broader Python 2/3 compatibility. If sticking to older versions, test thoroughly across target Python environments.","message":"Older versions (pre-1.0.0, especially pre-0.1.3) had Python 2/3 compatibility issues related to file operations (`open` vs `io.open`) and dictionary merging syntax, which could lead to runtime errors on specific Python versions.","severity":"breaking","affected_versions":"<1.0.0"},{"fix":"Upgrade to version 1.1.1 or later to utilize the `auth` parameter for basic authentication credentials.","message":"The `auth` attribute for basic authentication was added in version 1.1.1. If you are using an older version and require authenticated access to Loki, this feature will be unavailable.","severity":"gotcha","affected_versions":"<1.1.1"},{"fix":"Ensure you are using `loki-logger-handler` version 1.1.0 or newer and have a Loki 3.0+ instance if you intend to send structured metadata.","message":"Enabling structured metadata (for Loki 3.0+) requires specific parameters (`enable_structured_loki_metadata`, `loki_metadata`, `loki_metadata_keys`) introduced in version 1.1.0. Using these features with older versions or an incompatible Loki server will not work as expected.","severity":"gotcha","affected_versions":"<1.1.0"},{"fix":"Upgrade to version 1.1.2 or higher to resolve the `AttributeError` when `message_in_json_format` is `False`.","message":"An `AttributeError` could be raised in version 1.1.1 when `message_in_json_format` was set to `False` due to an incorrect attribute access. This was fixed in 1.1.2.","severity":"gotcha","affected_versions":"1.1.1"},{"fix":"Move high-cardinality fields into the log message body or as structured metadata (if using Loki 3.0+ and the handler supports it) rather than labels. Use labels for broad categories like `application`, `environment`, `service`.","message":"Avoid using high-cardinality values (e.g., `user_id`, `request_id`, dynamic timestamps) directly as Loki labels. This can lead to performance degradation and increased storage costs in Loki itself.","severity":"gotcha","affected_versions":"All"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"Upgrade the `loki-logger-handler` library to version 1.1.2 or newer.","cause":"This error occurred in version 1.1.1 when `message_in_json_format` was set to `False` due to a bug in attribute handling.","error":"AttributeError: 'LoggerFormatter' object has no attribute 'message_in_json_format'"},{"fix":"Double-check the `url` parameter in `LokiLoggerHandler` for correctness, including the `/loki/api/v1/push` endpoint. Verify network access to the Loki instance. Ensure that `labels` are provided and that log lines do not exceed Loki's maximum entry size (default 256KB).","cause":"This usually indicates an incorrect Loki URL, network connectivity issues, or Loki rejecting the log entries due to validation errors (e.g., missing stream labels, line_too_long, or invalid JSON format).","error":"Logs are not appearing in Grafana Loki, or I see HTTP 400 Bad Request errors in my application logs when sending to Loki."},{"fix":"Ensure `logger.addHandler()` is called only once for each handler. In testing scenarios, call `logger.removeHandler(handler)` in teardown or use `logging.basicConfig` with `force=True` (Python 3.8+) or check `if not logger.handlers:` before adding handlers.","cause":"This is a common Python `logging` module issue where handlers are added multiple times to the same logger instance without being removed.","error":"Duplicate log entries appear when running tests or reloading my application."},{"fix":"When logging, ensure you pass the `extra` dictionary with the keys you expect: `logger.info('My message', extra={'some_extra_field': 'value'})`. Verify that `label_keys` or `loki_metadata_keys` correctly list the fields you intend to extract.","cause":"The `extra` dictionary was not passed to the logging call, or the specified key was not present in the `extra` dictionary provided.","error":"KeyError: 'some_extra_field' when trying to access log.extra in a custom formatter or `label_keys` is not working."}]}