From f6c774b37a6c39dab666a8c31839f68d2d874303 Mon Sep 17 00:00:00 2001 From: kernc Date: Fri, 5 May 2023 16:07:09 +0200 Subject: [PATCH] Prevent infinite recursion when posting messages Fixes https://github.com/GreyZmeem/python-logging-loki/issues/18 --- logging_loki/emitter.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/logging_loki/emitter.py b/logging_loki/emitter.py index 949ceea..e8e7a8e 100644 --- a/logging_loki/emitter.py +++ b/logging_loki/emitter.py @@ -4,6 +4,7 @@ import copy import functools import logging +import threading import time from logging.config import ConvertingDict from typing import Any @@ -48,13 +49,20 @@ def __init__(self, url: str, tags: Optional[dict] = None, auth: BasicAuth = None self.auth = auth self._session: Optional[requests.Session] = None + self._lock = threading.Lock() def __call__(self, record: logging.LogRecord, line: str): """Send log record to Loki.""" - payload = self.build_payload(record, line) - resp = self.session.post(self.url, json=payload) - if resp.status_code != self.success_response_code: - raise ValueError("Unexpected Loki API response status code: {0}".format(resp.status_code)) + # Prevent "recursion" when e.g. urllib3 logs debug messages on POST + if not self._lock.acquire(blocking=False): + return + try: + payload = self.build_payload(record, line) + resp = self.session.post(self.url, json=payload) + if resp.status_code != self.success_response_code: + raise ValueError("Unexpected Loki API response status code: {0}".format(resp.status_code)) + finally: + self._lock.release() @abc.abstractmethod def build_payload(self, record: logging.LogRecord, line) -> dict: