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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32291361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:21:44  来源:igfitidea点击:

How can I log a dictionary into a log file?

pythonpython-2.7logging

提问by Adit Vira

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?

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

回答by bakkal

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)

日志函数将转换'%s'为字符串表示(如果对象恰好是一个容器,repr()则将用于包含的对象)

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.

如果您有自定义对象(例如您自己的类的实例),您应该实现一个合理的__str__和/或__repr__为它实现,并且上述内容将在没有任何黑客的情况下工作。

More on this here Difference between __str__ and __repr__ in Python

这里有更多关于Python 中 __str__ 和 __repr__ 的区别

JSON is not very good for this

JSON 不是很好

For objects that aren't JSON-like (object instances, datetime, etc), json.dumps()would require a custom serializer e.g. with datetimeobjects you get:

对于不是类似 JSON 的对象(对象实例、日期时间等),json.dumps()将需要自定义序列化程序,例如datetime您获得的对象:

TypeError: datetime.datetime(...) is not JSON serializable

TypeError: datetime.datetime(...) is not JSON serializable

This goes for any type that isn't supported by json.dumps()

这适用于不受支持的任何类型 json.dumps()

Whereas the loggingmodule would figure out a good representation for the object

logging模块会为对象找出一个很好的表示

回答by Amr Magdy

you can convert it to string:

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

string_dictionary = str(d)

and then log the string dictionary variable to the file

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

using JSON

使用 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)

回答by Gaurav

Simple you can use

简单你可以使用

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

回答by Martin Thoma

I came to this question when I wanted to log JSON lines for Cloudwatch.

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

I ended up using python-json-logger.

我最终使用了python-json-logger.

Install it: pip install python-json-logger

安装它: pip install python-json-logger

Use pythonjsonlogger.jsonlogger.JsonFormatteras the formatter class.

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