如何将字典记录到日志文件中?

时间:2015-08-29 22:36:15

标签: python python-2.7 logging

我有一本字典:

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

并将日志文件设置为:

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

是否可以将此词典记录到“sample.log”文件中?如果是,我该怎么做?

5 个答案:

答案 0 :(得分:18)

简单的解决方案

日志记录函数会将$_ = "ou"; s toutest; print 转换为字符串表示形式(如果对象恰好是容器,则'%s'将用于包含的对象)

repr()

它在日志文件中的显示方式:

import logging
logging.basicConfig(level=logging.DEBUG, filename='sample.log')
logging.debug('Sample dict log: %s', {'name' : "John", 'age': 10})

如果你有自定义对象(例如你自己的类的实例),你应该为它实现一个明智的DEBUG:root:Sample dict log: {'age': 10, 'name': 'John'} 和/或__str__,并且上面的工作没有任何黑客。

此处有更多相关内容Difference between __str__ and __repr__ in Python

JSON对此

不是很好

对于非JSON类型的对象(对象实例,日期时间等),__repr__需要自定义序列化程序,例如使用json.dumps()个对象:

datetime

这适用于TypeError: datetime.datetime(...) is not JSON serializable

不支持的任何类型

json.dumps()模块会找出对象的良好表示

答案 1 :(得分:4)

简单你可以使用

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

答案 2 :(得分:2)

您可以将其转换为字符串:

logging

然后将字符串字典变量记录到文件

使用JSON

string_dictionary = str(d)

如果你想将字符串转换回来:

import json

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

答案 3 :(得分:1)

str(dictionary)json.dumps(dictionary) 的问题在于输出可能对人类不友好,尤其是在字典很大并且具有嵌套结构的情况下。

如果是这种情况,您可以在记录之前使用 Python 的内置 pprint 对字典进行漂亮的格式化:

import pprint

my_complex_dict = pprint.pformat(my_complex_dict)
logger.info(f"My complex dict:\n{my_complex_dict}")

答案 4 :(得分:0)

当我想为Cloudwatch记录JSON行时遇到了这个问题。

我最终使用了python-json-logger

安装:pip install python-json-logger

使用pythonjsonlogger.jsonlogger.JsonFormatter作为格式化程序类。