How can I write a dictionary to a log file?

I have a dictionary:

d = {name : "John", age: 10}. 

And the log file settings as:

 logging.basicConfig(level = logging.DEBUG, filename = "sample.log") 

Is it possible to register this dictionary in the file "sample.log"? If so, how can I do this?

+9
source share
4 answers

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

+18
source

Simple you can use

 dict_data = {"test":"data"} logger.info("Loging dict ---> {0}".format(dict_data)) 
+4
source

you can convert it to string:

 string_dictionary = str(d) 

and then write the string dictionary variable to a file

using json

 import json d = {"name":"John","age":10} json_string = json.dumps(d) 

and if you want to convert the string back:

 d = json.loads(json_string) 
+2
source

I came up with this question when I wanted to register JSON strings for Cloudwatch.

I ended up using python-json-logger .

Install it: pip install python-json-logger

Use pythonjsonlogger.jsonlogger.JsonFormatter as a formatter class.

0
source

All Articles