Skip to content

Commit

Permalink
Merge pull request #101 from radimsuckr/feature/logging-hostname-filt…
Browse files Browse the repository at this point in the history
…er-json-handler

Logging filter for hostname and extra JSON handler
  • Loading branch information
matllubos committed May 12, 2020
2 parents 54a6044 + 7e42333 commit cd96585
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions chamber/utils/logging.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
import json
import logging
import platform

from django.core.serializers.json import DjangoJSONEncoder
from django.http import UnreadablePostError


Expand All @@ -7,3 +12,31 @@ def skip_unreadable_post(record):
if isinstance(exc_value, UnreadablePostError):
return False
return True


class AppendExtraJSONHandler(logging.StreamHandler):

DEFAULT_STREAM_HANDLER_VARIABLE_KEYS = {
'name', 'msg', 'args', 'levelname', 'levelno', 'pathname', 'filename', 'module', 'exc_info', 'exc_text',
'stack_info', 'lineno', 'funcName', 'created', 'msecs', 'relativeCreated', 'thread', 'threadName',
'processName', 'process',
}
CUSTOM_STREAM_HANDLER_VARIABLE_KEYS = {'hostname'}

def emit(self, record):
extra = {
k: v
for k, v in record.__dict__.items()
if k not in self.DEFAULT_STREAM_HANDLER_VARIABLE_KEYS.union(self.CUSTOM_STREAM_HANDLER_VARIABLE_KEYS)
}
record.msg = '{} --- {}'.format(record.msg, json.dumps(extra, cls=DjangoJSONEncoder))
super().emit(record)


class HostnameFilter(logging.Filter):

hostname = platform.node()

def filter(self, record):
record.hostname = self.hostname
return True

0 comments on commit cd96585

Please sign in to comment.