Skip to content
Merged
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
1 change: 1 addition & 0 deletions newsfragments/746.changed.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
:meth:`LogRecord.to_dict(json_safe=True) <logbook.LogRecord.to_dict>` is faster, and so are handlers that send records as JSON, such as :class:`~logbook.queues.ZeroMQHandler`.
37 changes: 17 additions & 20 deletions src/logbook/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,26 +127,23 @@ def to_safe_json(data):
objects from nested structures. This also converts dates.
"""

def _convert(obj):
if obj is None:
return None
elif isinstance(obj, _JSON_SIMPLE_TYPES):
return obj
elif isinstance(obj, datetime):
return format_iso8601(obj)
elif isinstance(obj, list):
return [_convert(x) for x in obj]
elif isinstance(obj, tuple):
return tuple(_convert(x) for x in obj)
elif isinstance(obj, dict):
rv = {}
for key, value in obj.items():
if not isinstance(key, str):
key = str(key)
rv[key] = _convert(value)
return rv

return _convert(data)
if data is None:
return None
elif isinstance(data, _JSON_SIMPLE_TYPES):
return data
elif isinstance(data, datetime):
return format_iso8601(data)
elif isinstance(data, list):
return [to_safe_json(x) for x in data]
elif isinstance(data, tuple):
return tuple(to_safe_json(x) for x in data)
elif isinstance(data, dict):
rv = {}
for key, value in data.items():
if not isinstance(key, str):
key = str(key)
rv[key] = to_safe_json(value)
return rv


if sys.version_info >= (3, 12):
Expand Down
2 changes: 2 additions & 0 deletions tests/test_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ def __str__(self):
1,
datetime(2000, 1, 1),
{"jäger1": 1, "jäger2": 2, Bogus(): 3, "invalid": object()},
(1, object()),
object(), # invalid
]
)
Expand All @@ -29,6 +30,7 @@ def __str__(self):
1,
"2000-01-01T00:00:00Z",
{"jäger1": 1, "jäger2": 2, "bogus": 3, "invalid": None},
(1, None),
None,
]

Expand Down
Loading