2015-05-29 81 views
0

我正在寫一個腳本,分析日誌文件和某些字符串,如「INFO」,「WARN」,「嚴重」火柴等在日誌文件中搜索唯一的日期(蟒蛇)

我可以做這使用下面的代碼時遇到了很多麻煩。

from sys import argv 
from collections import OrderedDict 

# Find and catalog each log line that matches these strings 
match_strings = ["INFO", "WARN", "SEVERE"] 

if len(argv) > 1: 
    files = argv[1:] 
else: 
    print "ERROR: You must provide at least one log file to be processed." 
    print "Example:" 
    print "%s my.log" % argv[0] 
    exit(2) 

for filename in files: 
    with open(filename) as f: 
     data = f.read().splitlines() 
     # Create data structure to handle results 
     matches = OrderedDict() 
     for string in match_strings: 
      matches[string] = [] 

    for i, s in enumerate(data, 1): 
     for string in match_strings: 
      if string in s: 
       matches[string].append('Line %03d: %s' % (i, s,)) 
for string in matches: 
    print "\"%s\": %d" % (string, len(matches[string])) 

日誌文件看起來像:

2014-05-26T15:06:14.597+0000 INFO... 
2014-05-26T15:06:14.597+0000 WARN... 
2014-05-27T15:06:14.597+0000 INFO... 
2014-05-28T15:06:14.597+0000 SEVERE... 
2014-05-29T15:06:14.597+0000 SEVERE... 

電流輸出的樣子:

"INFO": 2 
"WARN": 1 
"SEVERE": 2 

不過,我寧願做的是有日期的腳本整理和打印輸出格式。因此,而不是打印一個簡單的列表(上圖),我們可以得到類似下面的使用示例從上面:

Category 2014-05-26 2014-05-27 2014-05-28 2014-05-29 

"INFO":   1   1   0   0 
"WARN":   1   0   0   0 
"SEVERE":  0   0   1   1 

是否有任何想法/建議,如何做到這一點?

+0

那麼你真的*嘗試過*在這個方向上的任何事情嗎? – jonrsharpe

+0

@jonrsharpe,是的 - 我嘗試使用替換字段幫助格式化輸出,但是我很難理解如何使日期成爲每列的標題等。 – FunnyChef

+0

考慮到可能會有更多日期類別,將後者作爲列是否有意義?看看例如['collections.Counter'](https://docs.python.org/2/library/collections.html#collections.Counter)來簡化計數。 – jonrsharpe

回答

0

這樣做的一種方法是創建一個具有變量信息,警告和嚴重的類。然後創建一個字典,其中每個元素都是這個類的關鍵是日期。然後當你解析你的日誌文件時,你可以找到日期並將其作爲字典的索引,並根據需要增加信息,警告和嚴重。

+0

感謝您的提示,我會給它一個。 – FunnyChef