将Python日志记录到字典中
我刚开始学习Python...我想读取一个Python的日志文件,并把它做成一个字典。请问怎么用logger来实现这个呢?
2 个回答
1
读取一个Python日志文件并制作一个字典。用logger怎么做呢?
这不可能。
logging
是用来写日志的。
file
是用来读取日志的。
你到底在问什么呢?
首先,搜索一下 [Python] 日志解析: https://stackoverflow.com/search?q=%5Bpython%5D+log+parsing
其次,请提供一些示例代码。
1
正如其他评论者所说,你不应该用 logging
来读取文件,而是应该用 file
。下面是一个示例,展示了如何写入一个日志文件,然后再把它读回来。
#!/usr/bin/env python
# logger.py -- will write "time:debug:A:1" "time:debug:B:2" "time:debug:A:3" etc. log entries to a file
import logging, random
logging.basicConfig(filename='logfile.log',level=logging.DEBUG)
for i in range(1,100): logging.debug("%s:%d" % (random.choice(["a", "b"]), i))
# logfile.log now contains --
# 100.1:debug:A:1
# 100.5:debug:B:2
# 100.8:debug:B:3
# 101.3:debug:A:4
# ....
# 130.3:debug:B:100
#!/usr/bin/env/python
# reader.py -- will read aformentioned log files and sum up the keys
handle = file.open('logfile.log', 'r')
sums = {}
for line in handle.readlines():
time, debug, key, value = line.split(':')
if not key in sums: sums[key] = 0
sums[key] += value
print sums
# will output --
# "{'a': 50, 'b': 50}"