如何使用 structlog 将日期和日期时间记录为字符串?

How can I log date and datetime as strings with structlog?

Structlog 在创建日志消息时似乎使用 __repr__,这导致 datedatetime 对象看起来像 'datetime.datetime(2018, 9, 20, 10, 1, 52, 414750)',其中 '2018-09-20 10:01:52.414750' 更可取.

我原以为会有现成的处理器来处理这个问题,但我找不到。

这是我想出的解决方案,但考虑到它的高度递归性质,以及 listdict 对象的不必要重建,我担心性能。

def _convert_dates(obj):
    if isinstance(obj, datetime.date):
        # all datetimes are also dates
        return str(obj)
    elif isinstance(obj, dict):
        # Assume dates won't be keys
        return {k: _convert_dates(v) for k, v in obj.items()}
    elif isinstance(obj, list):
        return [_convert_dates(v) for v in obj]
    return obj


def dates_to_str_filter(_, __, event):
    return _convert_dates(event)

然后在 processors 中包含 dates_to_str_filter 用于 structlog.configure 调用。