|
| 1 | +import logging |
| 2 | +from logging.handlers import QueueHandler, QueueListener |
| 3 | +from queue import Queue |
| 4 | +from typing import Optional, Tuple, Dict, Any |
| 5 | + |
| 6 | +import requests |
| 7 | +import rfc3339 |
| 8 | + |
| 9 | +BasicAuth = Optional[Tuple[str, str]] |
| 10 | + |
| 11 | + |
| 12 | +class LokiQueueHandler(QueueHandler): |
| 13 | + """ |
| 14 | + This handler automatically creates listener and `LokiHandler` to handle logs queue. |
| 15 | + """ |
| 16 | + |
| 17 | + def __init__(self, queue: Queue, url: str, tags: Optional[dict] = None, auth: BasicAuth = None): |
| 18 | + super().__init__(queue) |
| 19 | + self.handler = LokiHandler(url, tags, auth) |
| 20 | + self.listener = QueueListener(self.queue, self.handler) |
| 21 | + self.listener.start() |
| 22 | + |
| 23 | + |
| 24 | +class LokiHandler(logging.Handler): |
| 25 | + """ |
| 26 | + This handler sends log records to Loki via HTTP API. |
| 27 | + https://github.com/grafana/loki/blob/master/docs/api.md |
| 28 | + """ |
| 29 | + |
| 30 | + level_tag: str = "severity" |
| 31 | + logger_tag: str = "logger" |
| 32 | + |
| 33 | + def __init__(self, url: str, tags: Optional[dict] = None, auth: BasicAuth = None): |
| 34 | + super().__init__() |
| 35 | + |
| 36 | + # Tags that will be added to all records handled by this handler. |
| 37 | + self.tags = tags or {} |
| 38 | + |
| 39 | + # Loki HTTP API endpoint (e.g `http://127.0.0.1/api/prom/push`) |
| 40 | + self.url = url |
| 41 | + |
| 42 | + # Optional tuple with username and password for basic authentication |
| 43 | + self.auth = auth |
| 44 | + |
| 45 | + self._session: requests.Session = None |
| 46 | + |
| 47 | + @property |
| 48 | + def session(self) -> requests.Session: |
| 49 | + if self._session is None: |
| 50 | + self._session = requests.Session() |
| 51 | + self._session.auth = self.auth or None |
| 52 | + return self._session |
| 53 | + |
| 54 | + def handleError(self, record): |
| 55 | + super().handleError(record) |
| 56 | + if self._session is not None: |
| 57 | + self._session.close() |
| 58 | + self._session = None |
| 59 | + |
| 60 | + def emit(self, record: logging.LogRecord): |
| 61 | + """ |
| 62 | + Send log record to Loki. |
| 63 | + """ |
| 64 | + # noinspection PyBroadException |
| 65 | + try: |
| 66 | + labels = self.build_labels(record) |
| 67 | + ts = rfc3339.format(record.created) |
| 68 | + line = self.format(record) |
| 69 | + payload = {"streams": [{"labels": labels, "entries": [{"ts": ts, "line": line}]}]} |
| 70 | + resp = self.session.post(self.url, json=payload) |
| 71 | + if resp.status_code != 204: |
| 72 | + raise ValueError("Unexpected Loki API response status code: %s" % resp.status_code) |
| 73 | + except Exception: |
| 74 | + self.handleError(record) |
| 75 | + |
| 76 | + def build_labels(self, record: logging.LogRecord) -> str: |
| 77 | + """ |
| 78 | + Return Loki labels string. |
| 79 | + """ |
| 80 | + tags = self.build_tags(record) |
| 81 | + labels = ",".join(['%s="%s"' % (k, str(v).replace('"', '\\"')) for k, v in tags.items()]) |
| 82 | + return "{%s}" % labels |
| 83 | + |
| 84 | + def build_tags(self, record: logging.LogRecord) -> Dict[str, Any]: |
| 85 | + """ |
| 86 | + Return tags that must be send to Loki with a log record. |
| 87 | + """ |
| 88 | + tags = self.tags.copy() |
| 89 | + tags[self.level_tag] = record.levelname.lower() |
| 90 | + tags[self.logger_tag] = record.name |
| 91 | + |
| 92 | + extra_tags = getattr(record, "tags", {}) |
| 93 | + if isinstance(extra_tags, dict): |
| 94 | + tags.update(extra_tags) |
| 95 | + |
| 96 | + return tags |
0 commit comments