Python作为字典或JSON登录文件 [英] Python logging into file as a dictionary or JSON
问题描述
我正在尝试设置日志记录,我可以在其中登录stdout并登录到文件.我使用以下代码完成了此任务:
I am trying to set up logging where I can log in both stdout and on to a file. This i have accomplished using the following code:
logging.basicConfig(
level=logging.DEBUG, format='%(asctime)-15s %(levelname)-8s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S', handlers=[logging.FileHandler(path), logging.StreamHandler()])
类似这样的输出:
2018-05-02 18:43:33,295 DEBUG Starting new HTTPS connection (1): google.com
2018-05-02 18:43:33,385 DEBUG https://google.com:443 "GET / HTTP/1.1" 301 220
2018-05-02 18:43:33,389 DEBUG Starting new HTTPS connection (1): www.google.com
2018-05-02 18:43:33,490 DEBUG https://www.google.com:443 "GET / HTTP/1.1" 200 None
我要完成的工作是将此输出记录到文件中,而不是像打印到stdout一样,而是将其记录为类似于此类的字典或JSON对象(同时保持当前的stdout不变):
What I am trying to accomplish is logging this output to a file not as it is printing to stdout, but as a dictionary or JSON object similar to something like this (while keeping the stdout as it is at the moment):
[{'time': '2018-05-02 18:43:33,295', 'level': 'DEBUG', 'message': '开始新的 HTTPS 连接 (1): google.com'},{...},{...}]
这可行吗?我知道我可以在过程完成后对这个日志文件进行处理,但是我正在寻找一种更优雅的解决方案,因为我记录的某些内容本身就是很大的对象.
Is this doable? I understand that I can post process this log file after my process is finished, but I am looking for a more elegant solution because certain things i am logging are quite big objects themselves.
推荐答案
So based on @abarnert, i found this Link which provided a good path to making this concept work for the most part. The code as it stands is:
logger=logging.getLogger()
logger.setLevel(logging.DEBUG)
file_handler=logging.FileHandler('foo.log')
stream_handler=logging.StreamHandler()
stream_formatter=logging.Formatter(
'%(asctime)-15s %(levelname)-8s %(message)s')
file_formatter=logging.Formatter(
"{'time':'%(asctime)s', 'name': '%(name)s', \
'level': '%(levelname)s', 'message': '%(message)s'}"
)
file_handler.setFormatter(file_formatter)
stream_handler.setFormatter(stream_formatter)
logger.addHandler(file_handler)
logger.addHandler(stream_handler)
尽管它不能完全满足要求,但它不需要任何预处理,并允许我创建两个日志处理程序.
Although it does not fully meet the requirement, it doesnt require any pre processing, and allows me to create two log handlers.
然后,我可以使用类似的东西:
Afterwards, i can use something like:
with open('foo.log') as f:
logs = f.read().splitlines()
for l in logs:
for key, value in eval(l):
do something ...
拉取 dict
对象,而不是使用格式不正确的 JSON 来完成我打算完成的任务.
to pull dict
objects instead of fighting with improperly formatted JSON to accomplish what i had set out to accomplish.
仍然希望有一个更优雅的解决方案.
Still am hoping for a more elegant solution.
这篇关于Python作为字典或JSON登录文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!