【发布时间】:2010-11-02 21:38:21
【问题描述】:
我是 python 新手...我正在尝试读取 python 日志文件并制作字典。记录器将如何完成?
【问题讨论】:
-
什么样的字典?什么样的日志文件?请展示您的输入和预期输出的示例。
标签: python
我是 python 新手...我正在尝试读取 python 日志文件并制作字典。记录器将如何完成?
【问题讨论】:
标签: python
读取 python 日志文件并制作字典。 logger 会怎么做呢?
不会的。
logging 写入日志。
file 读取日志。
你在问什么?
首先搜索【Python】日志解析:https://stackoverflow.com/search?q=%5Bpython%5D+log+parsing
其次,请发布一些示例代码。
【讨论】:
正如其他评论者所说,您不想使用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}"
【讨论】: