Skip to main content

Импорт

from async_loki_handler import LokiHandler
  • _Пример использования c logging:
import logging
from src.async_loki_handler import LokiHandler


if __name__ == "__main__":

    loki_handler = LokiHandler(
        url="http://127.0.0.1:3100/loki/api/v1/push",
        labels={"app": "logging"},
        batch_size=1000,
        extra_label_keys=["action", "endpoint", "status_code"],
    )

    # Настройка логирования
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(levelname)s - %(message)s',
        handlers=[
            logging.StreamHandler(), # <- Добавили вывод в консоль
            logging.FileHandler('../content_generator.log', encoding='utf-8'), # <- Добавили запись в файл
            loki_handler,  # <- Добавили отправку на сервер с Loki

        ]
    )

    logger = logging.getLogger(__name__)

    # Настройка для async_loki_handler
    logger.setLevel(logging.DEBUG)

    logger.info(
        "API request completed",
        extra={"data": {
            "action": "api_call",  # → label
            "endpoint": "/users/create",  # → label
            "status_code": "200",  # → label
            "response_time": 0.45,  # → extra в JSON
            "user_name": "yehor",  # → extra в JSON
            "custom_field": "value"  # → extra в JSON
        }}
    )
    logger.info(
        "Some event",
        extra={
            "user_id": "12345",  # попадёт (стандартное поле)
            "custom_field": "value"  # НЕ попадёт (не в extra_label_keys)
        }
    )
    logger.debug("LokiHandler - logging", )
    logger.info("Тестируем logging с библиотекой LokiHandler", )
  • _Пример использования c loguru:
import sys
from loguru import logger
from async_loki_handler import LokiHandler

if __name__ == "__main__":
    logger.remove()

    loki_handler = LokiHandler(
        url="http://127.0.0.1:3100/loki/api/v1/push",
        labels={"app": "loguru"},
        extra_label_keys=["action"],
    )

    # Простой строковый формат (без функции)
    console_format = (
        "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | "
        "<level>{level:<8}</level> | "
        "<cyan>{name}:{function}:{line}</cyan> - "
        "<level>{message:<30}</level>"
        " | <cyan>{extra}</cyan>"  # ← с разделителем и цветом
    )

    logger.add(sys.stderr, format=console_format, colorize=True)
    logger.add(loki_handler, format="{message}")

    # Тесты
    logger.info("Simple message")
    logger = logger.bind(extra={"action": "test", "account": "user"})
    logger.info("Login success")
    logger.warning("Warning message")
    logger.bind(user_id="999").error("Error occurred")

Metadata

Release files for async-loki-handler 0.0.9

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for async-loki-handler 0.0.9
File Size Uploaded
async_loki_handler-0.0.9.tar.gz 12.1 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for async-loki-handler 0.0.9
File Interpreter ABI Platform
async_loki_handler-0.0.9-py3-none-any.whl Python 3 none any Details

Total release size: 23.7 kB

Release files / async_loki_handler-0.0.9.tar.gz

Download URL async_loki_handler-0.0.9.tar.gz
Size 12.1 kB
Tags Source
SHA-256 checksum
How to use checksums
921c138a9ced26db14b5abd95017bbc30f847e5e8863df9d2f2c997691ea0547
BLAKE2b-256 checksum
How to use checksums
320421f6d0ca7194bf8345dae5e282b4621cad5bb19eab750e3ea9caa69f3e9a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.10.18

Release files / async_loki_handler-0.0.9-py3-none-any.whl

Download URL async_loki_handler-0.0.9-py3-none-any.whl
Size 11.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
bd60e5790f6b7f50f4cc32d17177e0877430b7c8448b2346ef4d7078137e9365
BLAKE2b-256 checksum
How to use checksums
fc14a13ce2bc46185f06f2fcc7805e948e3f40c6efa0459e448826e1d9342b84
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.10.18

Release history Release notifications | RSS feed

This release

0.0.9 This release

2 release files

0.0.7

2 release files

0.0.4

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page