Handler designed for transmitting logs to Grafana Loki in JSON format.
Project description
loki_logger_handler
A logging handler that sends log messages to (Grafana) Loki in JSON format.
Features
- Logs pushed in JSON format by default
- Custom labels definition
- Allows defining loguru and logger extra keys as labels
- Logger extra keys added automatically as keys into pushed JSON
- Publish in batch of Streams
- Publish logs compressed
Args
- url (str): The URL of the Loki server.
- labels (dict): A dictionary of labels to attach to each log message.
- label_keys (dict, optional): A dictionary of keys to extract from each log message and use as labels. Defaults to None.
- additional_headers (dict, optional): Additional headers for the Loki request. Defaults to None.
- timeout (int, optional): Timeout interval in seconds to wait before flushing the buffer. Defaults to 10 seconds.
- compressed (bool, optional): Whether to compress the log messages before sending them to Loki. Defaults to True.
- loguru (bool, optional): Whether to use
LoguruFormatter
. Defaults to False. - default_formatter (logging.Formatter, optional): Formatter for the log records. If not provided,
LoggerFormatter
orLoguruFormatter
will be used.
Formatters
- LoggerFormatter: Formatter for default python logging implementation
- LoguruFormatter: Formatter for Loguru python library
How to use
Logger
from loki_logger_handler.loki_logger_handler import LokiLoggerHandler,
import logging
import os
# Set up logging
logger = logging.getLogger("custom_logger")
logger.setLevel(logging.DEBUG)
# Create an instance of the custom handler
custom_handler = LokiLoggerHandler(
url=os.environ["LOKI_URL"],
labels={"application": "Test", "environment": "Develop"},
label_keys={},
timeout=10,
)
# Create an instance of the custom handler
logger.addHandler(custom_handler)
logger.debug("Debug message", extra={'custom_field': 'custom_value'})
Loguru
from loki_logger_handler.loki_logger_handler import LokiLoggerHandler, LoguruFormatter
from loguru import logger
import os
os.environ["LOKI_URL"]="https://USER:PASSWORD@logs-prod-eu-west-0.grafana.net/loki/api/v1/push"
custom_handler = LokiLoggerHandler(
url=os.environ["LOKI_URL"],
labels={"application": "Test", "environment": "Develop"},
label_keys={},
timeout=10,
default_formatter=LoguruFormatter(),
)
logger.configure(handlers=[{"sink": custom_handler, "serialize": True}])
logger.info(
"Response code {code} HTTP/1.1 GET {url}", code=200, url="https://loki_handler.io"
)
Loki messages samples
Without extra
{
"message": "Starting service",
"timestamp": 1681638266.542849,
"process": 48906,
"thread": 140704422327936,
"function": "run",
"module": "test",
"name": "__main__"
}
With extra
{
"message": "Response code 200 HTTP/1.1 GET https://loki_handler.io",
"timestamp": 1681638225.877143,
"process": 48870,
"thread": 140704422327936,
"function": "run",
"module": "test",
"name": "__main__",
"code": 200,
"url": "https://loki_handler.io"
}
Exceptions
{
"message": "name 'plan' is not defined",
"timestamp": 1681638284.358464,
"process": 48906,
"thread": 140704422327936,
"function": "run",
"module": "test",
"name": "__main__",
"file": "test.py",
"path": "/test.py",
"line": 39
}
Loki Query Sample
Loki query sample :
{environment="Develop"} |= `` | json
Filter by level:
{environment="Develop", level="INFO"} |= `` | json
Filter by extra:
{environment="Develop", level="INFO"} |= `` | json | code=`200`
Development Environment: Dev Container
This 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.
Why Use a Dev Container?
- Consistency: Ensures everyone works in the same environment, regardless of the host OS.
- Isolation: Keeps project dependencies separate from your system.
- Portability: Easily onboard new developers by setting up the environment with a single command.
- Pre-configured Tools: Includes all required tools and dependencies for the project.
Getting Started with the Dev Container
To start working with the Dev Container, follow these steps:
Prerequisites
- Install Docker Desktop (required for running containers).
- Install Visual Studio Code (VS Code).
- Install the Dev Containers extension in VS Code:
- Go to Extensions (
Ctrl+Shift+X
/Cmd+Shift+X
) and search forDev Containers
. - Install the extension by Microsoft.
- Go to Extensions (
Setup Instructions
- Clone the repository
- Open in VS Code
- Open the Command Palette (Ctrl+Shift+P / Cmd+Shift+P) and select: Dev Containers: Reopen in Container
- VS Code will:
- Pull the Dev Container image.
- Install all dependencies and tools specified.
Resources
The loki_logger_handler Dev Container provides the following resources:
- Grafana: Accessible externally at http://localhost:3000.
- Loki: Accessible internally at http://loki:3100/loki/api/v1/push. You can use this URL in your code as the publish endpoint for logs. Logs can be viewed and queried via the Grafana interface.
os.environ["LOKI_URL"]=http://loki:3100/loki/api/v1/push
License
The MIT License
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file loki_logger_handler-1.0.1.tar.gz
.
File metadata
- Download URL: loki_logger_handler-1.0.1.tar.gz
- Upload date:
- Size: 13.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/5.1.1 CPython/3.12.7
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 790b013447d34e11f7b21d6c10241856c1ac19a10dfe6661bbfe10c378049e1a |
|
MD5 | 4eb77e32b511752d252f9ac104705277 |
|
BLAKE2b-256 | 3dd708ec4735bd184c8c499a0f99e4f23a72b8b6ad92d9506caedcda602b8a3a |
Provenance
The following attestation bundles were made for loki_logger_handler-1.0.1.tar.gz
:
Publisher:
publish.yml
on xente/loki-logger-handler
-
Statement type:
https://in-toto.io/Statement/v1
- Predicate type:
https://docs.pypi.org/attestations/publish/v1
- Subject name:
loki_logger_handler-1.0.1.tar.gz
- Subject digest:
790b013447d34e11f7b21d6c10241856c1ac19a10dfe6661bbfe10c378049e1a
- Sigstore transparency entry: 150446882
- Sigstore integration time:
- Predicate type:
File details
Details for the file loki_logger_handler-1.0.1-py3-none-any.whl
.
File metadata
- Download URL: loki_logger_handler-1.0.1-py3-none-any.whl
- Upload date:
- Size: 14.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/5.1.1 CPython/3.12.7
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | b5efd2ed5641a9f1bc55cb3494c17b25ad9c1b4dbec40f189b1b205acdd8d919 |
|
MD5 | 7dd385adf667d54143cce71a02f50f83 |
|
BLAKE2b-256 | 2cf107799b5921e6fdf96500428094aa84079fc16dc16057c9c81a85a69461f4 |
Provenance
The following attestation bundles were made for loki_logger_handler-1.0.1-py3-none-any.whl
:
Publisher:
publish.yml
on xente/loki-logger-handler
-
Statement type:
https://in-toto.io/Statement/v1
- Predicate type:
https://docs.pypi.org/attestations/publish/v1
- Subject name:
loki_logger_handler-1.0.1-py3-none-any.whl
- Subject digest:
b5efd2ed5641a9f1bc55cb3494c17b25ad9c1b4dbec40f189b1b205acdd8d919
- Sigstore transparency entry: 150446884
- Sigstore integration time:
- Predicate type: