diff --git a/README.md b/README.md index 54c7642..c74f63b 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,7 @@ 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"), version="1", ) @@ -58,6 +59,7 @@ handler = logging.handlers.QueueHandler(queue) handler_loki = 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"), version="1", ) diff --git a/logging_loki/emitter.py b/logging_loki/emitter.py index 949ceea..d4d86de 100644 --- a/logging_loki/emitter.py +++ b/logging_loki/emitter.py @@ -30,7 +30,7 @@ class LokiEmitter(abc.ABC): label_replace_with = const.label_replace_with session_class = requests.Session - def __init__(self, url: str, tags: Optional[dict] = None, auth: BasicAuth = None): + def __init__(self, url: str, tags: Optional[dict] = None, headers: Optional[dict] = None, auth: BasicAuth = None): """ Create new Loki emitter. @@ -42,6 +42,8 @@ def __init__(self, url: str, tags: Optional[dict] = None, auth: BasicAuth = None """ #: Tags that will be added to all records handled by this handler. self.tags = tags or {} + #: Headers that will be added to all requests handled by this emitter. + self.headers = headers or {} #: Loki JSON push endpoint (e.g `http://127.0.0.1/loki/api/v1/push`) self.url = url #: Optional tuple with username and password for basic authentication. @@ -52,7 +54,7 @@ def __init__(self, url: str, tags: Optional[dict] = None, auth: BasicAuth = None 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) + resp = self.session.post(self.url, json=payload, headers=self.headers) if resp.status_code != self.success_response_code: raise ValueError("Unexpected Loki API response status code: {0}".format(resp.status_code)) diff --git a/logging_loki/handlers.py b/logging_loki/handlers.py index 74a55cb..0f7d1da 100644 --- a/logging_loki/handlers.py +++ b/logging_loki/handlers.py @@ -40,6 +40,7 @@ def __init__( self, url: str, tags: Optional[dict] = None, + headers: Optional[dict] = None, auth: Optional[emitter.BasicAuth] = None, version: Optional[str] = None, ): @@ -67,7 +68,7 @@ def __init__( version = version or const.emitter_ver if version not in self.emitters: raise ValueError("Unknown emitter version: {0}".format(version)) - self.emitter = self.emitters[version](url, tags, auth) + self.emitter = self.emitters[version](url, tags, headers, auth) def handleError(self, record): # noqa: N802 """Close emitter and let default handler take actions on error."""