[英]How can I log date and datetime as strings with structlog?
Structlog seems to use __repr__
when creating log messages, which leads to date
and datetime
objects looking like 'datetime.datetime(2018, 9, 20, 10, 1, 52, 414750)'
where '2018-09-20 10:01:52.414750'
would be preferable. Structlog 在创建日志消息时似乎使用
__repr__
,这导致date
和datetime
对象看起来像'datetime.datetime(2018, 9, 20, 10, 1, 52, 414750)'
where '2018-09-20 10:01:52.414750'
会更可取。
I would have thought there would be an off the shelf processor to handle this, but I can't find one.我原以为会有现成的处理器来处理这个问题,但我找不到。
This is the solution I came up with, but I'm concerned about the performance given the highly recursive nature of it, and the unnecessary rebuilding of list
and dict
objects.这是我想出的解决方案,但考虑到它的高度递归性质,以及
list
和dict
对象的不必要重建,我担心性能。
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)
Then include dates_to_str_filter
in processors
for the structlog.configure
call.然后包括
dates_to_str_filter
在processors
的structlog.configure
电话。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.