Skip to content

Instantly share code, notes, and snippets.

@yml
Created October 3, 2016 15:59
Show Gist options
  • Save yml/4f54957ffd52f361a6f45609ca09bf6c to your computer and use it in GitHub Desktop.
Save yml/4f54957ffd52f361a6f45609ca09bf6c to your computer and use it in GitHub Desktop.
import json
from logging import Formatter
class JSONStreamFormatter(Formatter):
def format(self, record):
"""
Format the specified record as text.
The record's attribute dictionary is used as the operand to a
string formatting operation which yields the returned string.
Before formatting the dictionary, a couple of preparatory steps
are carried out. The message attribute of the record is computed
using LogRecord.getMessage(). If the formatting string uses the
time (as determined by a call to usesTime(), formatTime() is
called to format the event time. If there is exception information,
it is formatted using formatException() and appended to the message.
"""
WHITE_LIST = [
'threadName', 'name', 'thread', 'created', 'process',
'processName', 'module', 'filename', 'levelno',
'exc_text', 'pathname', 'lineno', 'message',
'funcName', 'relativeCreated', 'levelname', 'msecs']
record.message = record.getMessage()
if self.usesTime():
record.asctime = self.formatTime(record, self.datefmt)
obj = {k:getattr(record, k) for k in WHITE_LIST}
if record.exc_info:
# Cache the traceback text to avoid converting it multiple times
# (it's constant anyway)
if not record.exc_text:
record.exc_text = self.formatException(record.exc_info)
if record.exc_text:
try:
obj["traceback"] = record.exc_text + ""
except UnicodeError:
# Sometimes filenames have non-ASCII chars, which can lead
# to errors when s is Unicode and record.exc_text is str
# See issue 8924.
# We also use replace for when there are multiple
# encodings, e.g. UTF-8 for the filesystem and latin-1
# for a script. See issue 13232.
obj["traceback"] = record.exc_text.decode(
sys.getfilesystemencoding(), 'replace')
return json.dumps(obj)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment