Search code examples
pythondatetimestructlog

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.

I would have thought there would be an off the shelf processor to handle this, but I can't find one.


Solution

  • 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.

    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.