Skip to content

Commit

Permalink
Allow to pass custom loads and dumps to JSONFormatter
Browse files Browse the repository at this point in the history
  • Loading branch information
mahenzon committed Aug 5, 2021
1 parent 9edfad2 commit 42abb78
Showing 1 changed file with 29 additions and 3 deletions.
32 changes: 29 additions & 3 deletions jsonformatter/jsonformatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ class JsonFormatter(logging.Formatter):

def parseFmt(self, fmt):
if isinstance(fmt, str):
return json.loads(fmt, object_pairs_hook=dictionary)
return self.loads(fmt, object_pairs_hook=dictionary)
elif isinstance(fmt, dictionary):
return fmt
elif isinstance(fmt, dict):
Expand Down Expand Up @@ -216,7 +216,28 @@ def wrapper(*args, **kwargs):
else:
return

def __init__(self, fmt=BASIC_FORMAT, datefmt=None, style='%', record_custom_attrs=None, mix_extra=False, mix_extra_position='tail', skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, sort_keys=False, **kw):
def __init__(
self,
fmt=BASIC_FORMAT,
datefmt=None,
style='%',
record_custom_attrs=None,
mix_extra=False,
mix_extra_position='tail',
skipkeys=False,
ensure_ascii=True,
check_circular=True,
allow_nan=True,
cls=None,
indent=None,
separators=None,
encoding='utf-8',
default=None,
sort_keys=False,
dumps=json.dumps,
loads=json.loads,
**kw,
):
"""
If ``style`` not in ``['%', '{', '$']``, a ``ValueError`` will be raised.
Expand Down Expand Up @@ -269,6 +290,9 @@ def __init__(self, fmt=BASIC_FORMAT, datefmt=None, style='%', record_custom_attr
If *sort_keys* is true (default: ``False``), then the output of
dictionaries will be sorted by key.
``dumps`` custom function to use instead of json.dumps
``loads`` custom function to use instead of json.loads
To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
``.default()`` method to serialize additional types), specify it with
the ``cls`` kwarg; otherwise ``JSONEncoder`` is used.
Expand All @@ -290,6 +314,8 @@ def __init__(self, fmt=BASIC_FORMAT, datefmt=None, style='%', record_custom_attr
self, fmt='', datefmt=datefmt, style=style)
# compatible python2 end

self.dumps = dumps
self.loads = loads
self.json_fmt = self.parseFmt(fmt)
self.record_custom_attrs = record_custom_attrs
self._style = _STYLES[style](self.json_fmt)
Expand Down Expand Up @@ -424,7 +450,7 @@ def _set_fmt_to_result():
record.__extra = extra
# store __extra end

return json.dumps(
return self.dumps(
result,
skipkeys=self.skipkeys,
ensure_ascii=self.ensure_ascii,
Expand Down

0 comments on commit 42abb78

Please sign in to comment.