Metadata-Version: 2.4
Name: inuits-python-logging-loki
Version: 1.5.0
Summary: Python logging handler for Grafana Loki.
Author-email: Inuits <developers@inuits.eu>, Andrey Maslov <greyzmeem@gmail.com>
License: MIT License
        
        Copyright (c) 2019 Andrey Maslov
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
Project-URL: Homepage, https://github.com/inuits/python-logging-loki
Keywords: inuits-python-logging-loki,inuits_python_logging_loki,python-logging-loki,python_logging_loki
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3.6
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: rfc3339>=6.1
Requires-Dist: requests
Dynamic: license-file

# python-logging-loki

[![PyPI version](https://img.shields.io/pypi/v/inuits-python-logging-loki.svg)](https://pypi.org/project/inuits-python-logging-loki/)
[![Python version](https://img.shields.io/badge/python-3.6%20%7C%203.8%20%7C%203.7%20%7C%203.9%20%7C%203.10%20%7C%203.11-blue.svg)](https://www.python.org/)
[![License](https://img.shields.io/pypi/l/python-logging-loki.svg)](https://opensource.org/licenses/MIT)
[![Build Status](https://travis-ci.org/GreyZmeem/python-logging-loki.svg?branch=master)](https://travis-ci.org/GreyZmeem/python-logging-loki)

Python logging handler for Loki.  
https://grafana.com/loki

# Installation

```bash
pip install inuits-python-logging-loki
```

# Usage

```python
import logging
import logging_loki


handler = logging_loki.LokiHandler(
    url="https://my-loki-instance/loki/api/v1/push",
    tags={"application": "my-app"},
    headers={"X-Scope-OrgID": "example-id"},
    auth=("username", "password"),
    props_to_labels = ["foo"]
)

logger = logging.getLogger("my-logger")
logger.addHandler(handler)
logger.error(
    "Something happened",
    extra={"tags": {"service": "my-service"}},
)
```

Example above will send `Something happened` message along with these labels:

- Default labels from handler
- Message level as `serverity`
- Logger's name as `logger`
- Labels from `tags` item of `extra` dict
- Property `foo` from log record will be sent as loki label

## Properties to label

Using a dict instead of a list for `props_to_labels` will enable renaming labels

```python
handler = logging_loki.LokiHandler(
    url="https://my-loki-instance/loki/api/v1/push",
    tags={"application": "my-app"},
    props_to_labels = {
        "otelTraceID": "trace_id"
        "otelSpanID":  "span_id"
    }
)
```

In this case, the properties `otelTraceID` & `otelSpanID` will be renamed to `trace_id` & `span_id` loki labels

## Non-blocking mode

Adding a `LokiHandler` to a logger directly is **blocking**: every log call does an
HTTP POST to Loki on the calling thread and waits for the response. In a request
handler that puts Loki's latency (and Loki's rate limiting) straight into your own
response time.

Use `LokiQueueHandler` instead. It attaches to the logger, creates the
`LokiHandler` and a `QueueListener`, and starts the listener, so the calling
thread only puts the record on a queue.

```python
import logging_loki
from queue import Queue


handler = logging_loki.LokiQueueHandler(
    Queue(-1),
    batch_interval=2,  # seconds; omit or pass 0 to push every record separately
    url="https://my-loki-instance/loki/api/v1/push",
    tags={"application": "my-app"},
    headers={"X-Scope-OrgID": "example-id"},
    auth=("username", "password"),
    props_to_labels=["foo"],
)

logger = logging.getLogger("my-logger")
logger.addHandler(handler)
logger.error(...)
```

If you wire the queue up by hand, **you must start the listener yourself** —
a `QueueListener` that is never started means nothing ever drains the queue and
no log line reaches Loki:

```python
queue = Queue(-1)
handler = logging.handlers.QueueHandler(queue)
handler_loki = logging_loki.LokiHandler(url=..., tags=...)
listener = logging.handlers.QueueListener(queue, handler_loki)
listener.start()  # <- required
```

## Batching and timeouts

With `batch_interval` set, records are buffered and pushed as one request. This
is what keeps Loki from answering with `429 Too Many Requests`: without it every
log line is its own POST and its own stream.

| Variable | Default | Meaning |
| --- | --- | --- |
| `LOKI_BATCH_INTERVAL` | `2` | Seconds between batched pushes (`LokiLogger` only). `0` disables batching. |
| `LOKI_MAX_BATCH_BUFFER_SIZE` | `1000` | Records buffered before a push happens regardless of the interval. |
| `LOKI_CONNECT_TIMEOUT` | `2` | Connect timeout, in seconds, for a push to Loki. |
| `LOKI_READ_TIMEOUT` | `5` | Read timeout, in seconds, for a push to Loki. |

A push that Loki rejects (`429`, or any other unexpected status) raises
`logging_loki.emitter.LokiPushError` and the records in that batch are dropped.
The HTTP session is kept open, since the connection is still healthy — only a
transport-level failure closes it and forces a reconnect.

## Forking servers

`LokiQueueHandler` does its work on background threads, and threads do not
survive `fork()`. Handlers built before the fork — a logger created at import
time under `gunicorn --preload`, for example — recreate their queue, listener
and flush threads in the child automatically, so each worker delivers its own
records and does not re-send the parent's.
