Simple solution that works
Logging functions convert the view '%s' to a string representation (and if the object turns out to be a container, then repr() will be used for the contained objects)
import logging logging.basicConfig(level=logging.DEBUG, filename='sample.log') logging.debug('Sample dict log: %s', {'name' : "John", 'age': 10})
How it appears in the log file:
DEBUG:root:Sample dict log: {'age': 10, 'name': 'John'}
If you have custom objects (for example, instances of your own classes), you should implement reasonable __str__ and / or __repr__ for it, and the above will work without hacks.
More on this here. Difference between __str__ and __repr__ in Python
JSON is not very good for this
For objects that are not JSON-like (object instances, datetime, etc.), json.dumps() will require a special serializer, for example. with datetime objects you get:
TypeError: datetime.datetime(...) is not JSON serializable
This applies to any type that is not supported by json.dumps()
While the logging module will determine a good view for the object
source share