2010-11-02 66 views
1

我是新的蟒蛇...我想读取一个python日志文件,并作出字典。记录器如何处理?Python记录器到字典

+2

什么样的字典?什么样的日志文件?请显示您的输入样本和您的预期输出。 – 2010-11-02 09:39:04

+2

...... W时的T? – 2010-11-02 09:39:08

+1

可能重复[什么是解析日志文件的最佳工具?](http://stackoverflow.com/questions/1994355/whats-the-best-tool-to-parse-log-files) – 2010-11-02 09:58:46

回答

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}"