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

Optionally sends entire record as JSON instead of only message #28

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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 time
from logging.config import ConvertingDict
Expand Down Expand Up @@ -30,7 +31,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, auth: BasicAuth = None, as_json=False):
"""
Create new Loki emitter.

Expand All @@ -46,6 +47,8 @@ def __init__(self, url: str, tags: Optional[dict] = None, auth: BasicAuth = None
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

Expand Down Expand Up @@ -136,6 +139,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 @@ -42,6 +42,7 @@ def __init__(
tags: Optional[dict] = None,
auth: Optional[emitter.BasicAuth] = None,
version: Optional[str] = None,
as_json: Optional[bool] = False
):
"""
Create new Loki logging handler.
Expand All @@ -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, auth, as_json)

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