Skip to content
Merged
Show file tree
Hide file tree
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
8 changes: 7 additions & 1 deletion logging_loki/emitter.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import abc
import copy
import functools
import json
import logging
import threading
import time
Expand Down Expand Up @@ -31,7 +32,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, headers: Optional[dict] = None, auth: BasicAuth = None):
def __init__(self, url: str, tags: Optional[dict] = None, headers: Optional[dict] = None, auth: BasicAuth = None, as_json: bool = False):
"""
Create new Loki emitter.

Expand All @@ -49,6 +50,8 @@ def __init__(self, url: str, tags: Optional[dict] = None, headers: Optional[dict
self.url = url
#: Optional tuple with username and password for basic authentication.
self.auth = auth
#: Optional bool, send record as json?
self.as_json = as_json

self._session: Optional[requests.Session] = None
self._lock = threading.Lock()
Expand Down Expand Up @@ -146,6 +149,9 @@ def build_payload(self, record: logging.LogRecord, line) -> dict:
labels = self.build_tags(record)
ns = 1e9
ts = str(int(time.time() * ns))

line = json.dumps(record, default=lambda obj: obj.__dict__) if self.as_json else line

stream = {
"stream": labels,
"values": [[ts, line]],
Expand Down
3 changes: 2 additions & 1 deletion logging_loki/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ def __init__(
headers: Optional[dict] = None,
auth: Optional[emitter.BasicAuth] = None,
version: Optional[str] = None,
as_json: Optional[bool] = False
):
"""
Create new Loki logging handler.
Expand All @@ -68,7 +69,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, headers, auth)
self.emitter = self.emitters[version](url, tags, headers, auth, as_json)

def handleError(self, record): # noqa: N802
"""Close emitter and let default handler take actions on error."""
Expand Down