Skip to content

Commit 42abb78

Browse files
committed
Allow to pass custom loads and dumps to JSONFormatter
1 parent 9edfad2 commit 42abb78

File tree

1 file changed

+29
-3
lines changed

1 file changed

+29
-3
lines changed

jsonformatter/jsonformatter.py

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,7 @@ class JsonFormatter(logging.Formatter):
162162

163163
def parseFmt(self, fmt):
164164
if isinstance(fmt, str):
165-
return json.loads(fmt, object_pairs_hook=dictionary)
165+
return self.loads(fmt, object_pairs_hook=dictionary)
166166
elif isinstance(fmt, dictionary):
167167
return fmt
168168
elif isinstance(fmt, dict):
@@ -216,7 +216,28 @@ def wrapper(*args, **kwargs):
216216
else:
217217
return
218218

219-
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):
219+
def __init__(
220+
self,
221+
fmt=BASIC_FORMAT,
222+
datefmt=None,
223+
style='%',
224+
record_custom_attrs=None,
225+
mix_extra=False,
226+
mix_extra_position='tail',
227+
skipkeys=False,
228+
ensure_ascii=True,
229+
check_circular=True,
230+
allow_nan=True,
231+
cls=None,
232+
indent=None,
233+
separators=None,
234+
encoding='utf-8',
235+
default=None,
236+
sort_keys=False,
237+
dumps=json.dumps,
238+
loads=json.loads,
239+
**kw,
240+
):
220241
"""
221242
If ``style`` not in ``['%', '{', '$']``, a ``ValueError`` will be raised.
222243
@@ -269,6 +290,9 @@ def __init__(self, fmt=BASIC_FORMAT, datefmt=None, style='%', record_custom_attr
269290
If *sort_keys* is true (default: ``False``), then the output of
270291
dictionaries will be sorted by key.
271292
293+
``dumps`` custom function to use instead of json.dumps
294+
``loads`` custom function to use instead of json.loads
295+
272296
To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
273297
``.default()`` method to serialize additional types), specify it with
274298
the ``cls`` kwarg; otherwise ``JSONEncoder`` is used.
@@ -290,6 +314,8 @@ def __init__(self, fmt=BASIC_FORMAT, datefmt=None, style='%', record_custom_attr
290314
self, fmt='', datefmt=datefmt, style=style)
291315
# compatible python2 end
292316

317+
self.dumps = dumps
318+
self.loads = loads
293319
self.json_fmt = self.parseFmt(fmt)
294320
self.record_custom_attrs = record_custom_attrs
295321
self._style = _STYLES[style](self.json_fmt)
@@ -424,7 +450,7 @@ def _set_fmt_to_result():
424450
record.__extra = extra
425451
# store __extra end
426452

427-
return json.dumps(
453+
return self.dumps(
428454
result,
429455
skipkeys=self.skipkeys,
430456
ensure_ascii=self.ensure_ascii,

0 commit comments

Comments
 (0)