Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent infinite recursion when posting messages #32

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions logging_loki/emitter.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import copy
import functools
import logging
import threading
import time
from logging.config import ConvertingDict
from typing import Any
Expand Down Expand Up @@ -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:
Expand Down