I have a dictionary:
d = {name : "John", age: 10}.
And a log file setup as:
logging.basicConfig(level = logging.DEBUG, filename = "sample.log")
Is it possible to log this dictionary into the "sample.log" file? If yes, how can I do it?
How to make python save a dictionary to a file. These are small programs that allows you to create a dictionary and then, when running the program, it will create a file that contains the data in the original dictionary. We can save it to one of these formats: Comma seperated value file (.
Saving Dictionary to a File This method would include the following steps: Opening a file in write/append text mode. Converting the dictionary into a string. Entering the converted string into the file using write function.
The logging functions will convert the '%s'
to string representation (and if the object happens 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 shows in the log file:
DEBUG:root:Sample dict log: {'age': 10, 'name': 'John'}
If you have custom objects (e.g. instances of your own classes), you should implement a sensible __str__
and/or __repr__
for it, and the above will work without any hacks.
More on this here Difference between __str__ and __repr__ in Python
For objects that aren't JSON-like (object instances, datetime, etc), json.dumps()
would require a custom serializer e.g. with datetime
objects you get:
TypeError: datetime.datetime(...) is not JSON serializable
This goes for any type that isn't supported by json.dumps()
Whereas the logging
module would figure out a good representation for the object
Simple you can use
dict_data = {"test":"data"} logger.info("Loging dict ---> {0}".format(dict_data))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With