Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I log a dictionary into a log file?

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?

like image 534
Adit Vira Avatar asked Aug 29 '15 22:08

Adit Vira


People also ask

Can you store a dictionary in a file Python?

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

How do you store a dictionary?

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.


2 Answers

Simple solution that works

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

JSON is not very good for this

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

like image 172
bakkal Avatar answered Sep 26 '22 12:09

bakkal


Simple you can use

dict_data = {"test":"data"} logger.info("Loging dict ---> {0}".format(dict_data)) 
like image 31
Wagh Avatar answered Sep 23 '22 12:09

Wagh