简体   繁体   中英

Logging dictionaries with datetime objects without Serialization error

I'm trying to log python dictionary as JSON like so logging.info(dict(msg="foo", data=obj)) . However in some cases, obj may contain datetime objects and in those cases I get a JSON serialization error.

Is there a simple way to log dictionaries where objects (such as datetime objects) are serialized automatically, such as having it call the "str" function on these objects?

You may define your own serializer for datetime object:

def to_json(python_object):
    if isinstance(python_object, datetime.datetime):
        return {'__class__': 'datetime.datetime',
                '__value__': time.asctime(python_object.timetuple())}
    if isinstance(python_object, time.struct_time):
        return {'__class__': 'time.asctime',
                '__value__': time.asctime(python_object)}
    if isinstance(python_object, bytes):
        return {'__class__': 'bytes',
                '__value__': list(python_object)}
    raise TypeError(repr(python_object) + ' is not JSON serializable')

def from_json(json_object):
    if '__class__' in json_object:
        if json_object['__class__'] == 'datetime.datetime':
            return datetime.datetime.fromtimestamp(time.mktime(time.strptime(json_object['__value__'])))
        if json_object['__class__'] == 'time.asctime':
            return time.strptime(json_object['__value__'])
        if json_object['__class__'] == 'bytes':
            return bytes(json_object['__value__'])
    return json_object

and then call it this way:

json.dump(entry, f, default=to_json)

or for reading back

entry = json.load(f, object_hook=from_json)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM