我是python中的新手......我正在尝试阅读python日志文件并制作字典。如何用记录器完成?
答案 0 :(得分:1)
读取python日志文件并制作字典。如何用记录器完成?
不会。
logging
写日志。
file
读取日志。
首先,搜索[Python]日志解析:https://stackoverflow.com/search?q=%5Bpython%5D+log+parsing
其次,请发布一些示例代码。
答案 1 :(得分: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}"