{"id":48189712,"url":"https://github.com/xente/loki-logger-handler","last_synced_at":"2026-04-04T17:54:16.113Z","repository":{"id":203188957,"uuid":"705589868","full_name":"xente/loki-logger-handler","owner":"xente","description":"A logging handler that sends log messages to Loki in JSON format","archived":false,"fork":false,"pushed_at":"2026-01-09T08:22:50.000Z","size":43,"stargazers_count":55,"open_issues_count":11,"forks_count":27,"subscribers_count":3,"default_branch":"main","last_synced_at":"2026-03-28T02:53:36.091Z","etag":null,"topics":["handler","logger","loguru","loki","python"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/xente.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2023-10-16T10:04:18.000Z","updated_at":"2026-03-15T20:54:46.000Z","dependencies_parsed_at":null,"dependency_job_id":"48656439-a68a-48ee-a772-a0debcb6b999","html_url":"https://github.com/xente/loki-logger-handler","commit_stats":null,"previous_names":["xente/loki-logger-handler"],"tags_count":11,"template":false,"template_full_name":null,"purl":"pkg:github/xente/loki-logger-handler","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xente%2Floki-logger-handler","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xente%2Floki-logger-handler/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xente%2Floki-logger-handler/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xente%2Floki-logger-handler/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/xente","download_url":"https://codeload.github.com/xente/loki-logger-handler/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xente%2Floki-logger-handler/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31407655,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-04T10:20:44.708Z","status":"ssl_error","status_checked_at":"2026-04-04T10:20:06.846Z","response_time":60,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["handler","logger","loguru","loki","python"],"created_at":"2026-04-04T17:54:15.649Z","updated_at":"2026-04-04T17:54:16.104Z","avatar_url":"https://github.com/xente.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# loki_logger_handler\n\n[![PyPI](https://img.shields.io/pypi/v/loki_logger_handler?color=blue\u0026label=pypi%20version)]()\n[![PyPI](https://img.shields.io/pypi/pyversions/loki_logger_handler.svg)]()\n[![Downloads](https://pepy.tech/badge/loki_logger_handler)](https://pepy.tech/project/loki_logger_handler)\n\nA logging handler that sends log messages to **(Grafana) Loki** in JSON format.\n\n## Features\n\n* Logs pushed in JSON format by default\n* Custom labels definition\n* Allows defining *loguru* and *logger* extra keys as labels\n* Logger extra keys added automatically as keys into pushed JSON\n* Publish in batch of Streams\n* Publish logs compressed\n\n## Args\n\n* url (str): The URL of the Loki server.\n* labels (dict): A dictionary of labels to attach to each log message.\n* label_keys (dict, optional): A dictionary of keys to extract from each log message and use as labels. Defaults to None.\n* auth (tuple, optional): Basic authentication credentials for the Loki request. Defaults to None.\n* additional_headers (dict, optional): Additional headers for the Loki request. Defaults to None.\n* message_in_json_format (bool): Whether to format log values as JSON.\n* timeout (int, optional): Timeout interval for flushing logs in seconds. Defaults to 10 seconds.\n* compressed (bool, optional): Whether to compress the logs before sending them using gzip. Defaults to True.\n* default_formatter (logging.Formatter, optional): Formatter for the log records. If not provided, `LoggerFormatter` or`LoguruFormatter` will be used.\n* enable_self_errors (bool, optional): Set to True to show Handler errors on console. Default False\n* insecure_ssl_verify (bool, optional): Whether to verify ssl certificate. Defaults to True\n\n### Loki 3.0 \n* enable_structured_loki_metadata (bool, optional):  Whether to include structured loki_metadata in the logs. Defaults to False. Only supported for Loki 3.0 and above\n* loki_metadata (dict, optional): Default loki_metadata values. Defaults to None. Only supported for Loki 3.0 and above\n* loki_metadata_keys (array, optional): Specific log record keys to extract as loki_metadata. Only supported for Loki 3.0 and above\n\n## Formatters\n* **LoggerFormatter**: Formatter for default python logging implementation\n* **LoguruFormatter**: Formatter for Loguru python library\n\n## How to use \n\nFirst create an environment variable to set up your loki url with this structure (Ej: https://100239:wdadw....dwad@logs-prod-eu-west-0.grafana.net/loki/api/v1/push)\n````python\nLOKI_URL=\"https://{{USER}}:{{PASSWORD}}@{{GRAFANA_LOKI_URL}}/loki/api/v1/push\"\n````\n\n### Install\n```sh\npip install loki-logger-handler\n```\n\n### Logger\n```python\nfrom loki_logger_handler.loki_logger_handler import LokiLoggerHandler\nimport logging\nimport os\n\n# Set up logging\nlogger = logging.getLogger(\"custom_logger\")\nlogger.setLevel(logging.DEBUG)\n\n# Create an instance of the custom handler\ncustom_handler = LokiLoggerHandler(\n    url=os.environ[\"LOKI_URL\"],\n    labels={\"application\": \"Test\", \"environment\": \"Develop\"},\n    label_keys={},\n    timeout=10,\n)\n# Create an instance of the custom handler\n\nlogger.addHandler(custom_handler)\nlogger.debug(\"Debug message\", extra={'custom_field': 'custom_value'})\n```\n\n\n### Loguru\n\n```python\nfrom loki_logger_handler.loki_logger_handler import LokiLoggerHandler\nfrom loki_logger_handler.formatters.loguru_formatter import LoguruFormatter\nfrom loguru import logger\nimport os\n\ncustom_handler = LokiLoggerHandler(\n    url=os.environ[\"LOKI_URL\"],\n    labels={\"application\": \"Test\", \"environment\": \"Develop\"},\n    label_keys={},\n    timeout=10,\n    default_formatter=LoguruFormatter(),\n)\nlogger.configure(handlers=[{\"sink\": custom_handler, \"serialize\": True}])\n\nlogger.info(\n    \"Response code {code} HTTP/1.1 GET {url}\", code=200, url=\"https://loki_handler.io\"\n)\n```\n\n## Loki messages samples\n\n### Without extra\n\n```json\n{\n  \"message\": \"Starting service\",\n  \"timestamp\": 1681638266.542849,\n  \"process\": 48906,\n  \"thread\": 140704422327936,\n  \"function\": \"run\",\n  \"module\": \"test\",\n  \"name\": \"__main__\"\n}\n\n```\n\n### With extra\n\n```json\n{\n  \"message\": \"Response code  200 HTTP/1.1 GET https://loki_handler.io\",\n  \"timestamp\": 1681638225.877143,\n  \"process\": 48870,\n  \"thread\": 140704422327936,\n  \"function\": \"run\",\n  \"module\": \"test\",\n  \"name\": \"__main__\",\n  \"code\": 200,\n  \"url\": \"https://loki_handler.io\"\n}\n```\n\n### Exceptions\n\n```json\n{\n  \"message\": \"name 'plan' is not defined\",\n  \"timestamp\": 1681638284.358464,\n  \"process\": 48906,\n  \"thread\": 140704422327936,\n  \"function\": \"run\",\n  \"module\": \"test\",\n  \"name\": \"__main__\",\n  \"file\": \"test.py\",\n  \"path\": \"/test.py\",\n  \"line\": 39\n}\n```\n\n## Loki Query Sample\n\nLoki query sample :\n\n ```\n {environment=\"Develop\"} |= `` | json\n ```\n\nFilter by level:\n\n```\n{environment=\"Develop\", level=\"INFO\"} |= `` | json\n```\nFilter by extra:\n\n```\n{environment=\"Develop\", level=\"INFO\"} |= `` | json | code=`200`\n```\n\n\n## Loki Structured Metadata\n\nLoki structured metadata to include additional context in your logs. This can be useful for filtering and querying logs in Loki.\n\nWe can add metadata in 3 ways:\n\n1. Defile static loki_metadata that will be injected into all logs lines\n2. Use logger extra options adding metadata inside `loki_metadata` key\n3. Use logger  `loki_metadata_keys` to move logs keys to loki metadata. \n\n### Example global metadata\n\n```python\nfrom loki_logger_handler.loki_logger_handler import LokiLoggerHandler\nimport logging\nimport os\n\n# Set up logging\nlogger = logging.getLogger(\"custom_logger\")\nlogger.setLevel(logging.DEBUG)\n\n# Create an instance of the custom handler with structured metadata\ncustom_handler = LokiLoggerHandler(\n  url=os.environ[\"LOKI_URL\"],\n  labels={\"application\": \"Test\", \"environment\": \"Develop\"},\n  label_keys={},\n  timeout=10,\n  enable_structured_loki_metadata=True,\n  loki_metadata={\"service\": \"user-service\", \"version\": \"1.0.0\"}\n)\n\nlogger.addHandler(custom_handler)\n\n```\n\nIn this example, the `loki_metadata` dictionary includes metadata that will be attached to every log message. The `enable_structured_loki_metadata` flag ensures that this metadata is included in the logs.\n\n### Example log metadata\n\n\n```python\nfrom loki_logger_handler.loki_logger_handler import LokiLoggerHandler\nimport logging\nimport os\n\n# Set up logging\nlogger = logging.getLogger(\"custom_logger\")\nlogger.setLevel(logging.DEBUG)\n\n# Create an instance of the custom handler with structured metadata\ncustom_handler = LokiLoggerHandler(\n  url=os.environ[\"LOKI_URL\"],\n  labels={\"application\": \"Test\", \"environment\": \"Develop\"},\n  label_keys={},\n  timeout=10,\n  enable_structured_loki_metadata=True,\n  loki_metadata={\"service\": \"user-service\", \"version\": \"1.0.0\"}\n)\n\nlogger.addHandler(custom_handler)\n\nlogger.info(\"User action\", extra={\"loki_metadata\": {\"user_id\": 12345, \"operation\": \"update\", \"status\": \"success\"}})\n\n```\n\n```python\nfrom loki_logger_handler.loki_logger_handler import LokiLoggerHandler\nimport logging\nimport os\n\n# Set up logging\nlogger = logging.getLogger(\"custom_logger\")\nlogger.setLevel(logging.DEBUG)\n\n# Create an instance of the custom handler with structured metadata\ncustom_handler = LokiLoggerHandler(\n  url=os.environ[\"LOKI_URL\"],\n  labels={\"application\": \"Test\", \"environment\": \"Develop\"},\n  label_keys={},\n  timeout=10,\n  enable_structured_loki_metadata=True,\n  loki_metadata={\"service\": \"user-service\", \"version\": \"1.0.0\"},\n  loki_metadata_keys=[\"trace_id\"]\n)\n\nlogger.addHandler(custom_handler)\n\nlogger.info(\"User action\", extra={\"loki_metadata\": {\"user_id\": 12345, \"operation\": \"update\", \"status\": \"success\"}, \"trace_id\": \"000-000000-0000\"})\n\n```\n\n\n### Querying Logs with Structured Metadata\n\nYou can query logs in Loki using the structured metadata.\n\nThis query will return all logs where the `service` metadata is set to `user-service`.\n\n```\n{application=\"Test\"} |= `` | service=\"user-service\"\n```\n\nThis query will return all logs where the `user_id` metadata is set to `12345`.\n\n```\n{application=\"Test\"} |= `` | user_id=\"12345\"\n```\n\nThis query will return all logs where the `trace_id` metadata is set to `000-000000-0000`.\n\n```\n{application=\"Test\"} |= `` | trace_id=\"000-000000-0000\"\n```\n\n\n## Development Environment: Dev Container\n\nThis project uses a **Dev Container** to provide a consistent and reproducible development environment. A Dev Container ensures all team members have the same tools, dependencies, and configurations, avoiding \"works on my machine\" issues.\n\n---\n\n### **Why Use a Dev Container?**\n\n- **Consistency**: Ensures everyone works in the same environment, regardless of the host OS.\n- **Isolation**: Keeps project dependencies separate from your system.\n- **Portability**: Easily onboard new developers by setting up the environment with a single command.\n- **Pre-configured Tools**: Includes all required tools and dependencies for the project.\n\n---\n\n### **Getting Started with the Dev Container**\n\nTo start working with the Dev Container, follow these steps:\n\n#### **Prerequisites**\n1. Install [Docker Desktop](https://www.docker.com/products/docker-desktop) (required for running containers).\n2. Install [Visual Studio Code (VS Code)](https://code.visualstudio.com/).\n3. Install the **Dev Containers** extension in VS Code:\n   - Go to Extensions (`Ctrl+Shift+X` / `Cmd+Shift+X`) and search for `Dev Containers`.\n   - Install the extension by Microsoft.\n\n#### **Setup Instructions**\n1. Clone the repository\n2. Open in VS Code\n3. Open the Command Palette (Ctrl+Shift+P / Cmd+Shift+P) and select: **Dev Containers: Reopen in Container**\n\n- VS Code will:\n  - Pull the Dev Container image. \n  - Install all dependencies and tools specified.\n\n\n#### Resources\n\nThe loki_logger_handler Dev Container provides the following resources:\n\n- Grafana: Accessible externally at http://localhost:3000.\n- Loki: Accessible internally at http://loki:3100/loki/api/v1/push.\nYou can use this URL in your code as the publish endpoint for logs.\nLogs can be viewed and queried via the Grafana interface.\n\n```\nos.environ[\"LOKI_URL\"]=http://loki:3100/loki/api/v1/push\n````\n\n## License\nThe MIT License\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fxente%2Floki-logger-handler","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fxente%2Floki-logger-handler","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fxente%2Floki-logger-handler/lists"}