日志分析

View Code
 1 #coding:utf-8
 2 logpath='D:/temp2.log'
 3 destinationPath='d:/temp.xml'
 4 log=open(logpath)
 5 # status={}#行数:{节点名:状态(1:不可用,2:可用)}
 6 status={}#行数:{节点名:状态(1:不成对begin,2:不成对end,3:成对begin,4:成对end)}
 7 content=[]
 8 begins=[]
 9 index=0
10 exist={}
11 for r in log.readlines():
12     index=index+1;
13     if '[Begin]' in r:
14         real=r[24:r.rfind('.')]
15         begins.append(real)
16         status.__setitem__(index,{real:1})
17     elif '[End]' in r:
18         real=r[16:r.find('[',16)]
19         # print real
20         # print begins
21         lastindex=-1#最近与end匹配的begin节点
22         for oriindex,rc in status.items():
23             if rc.get(real,0)==1:#如果有与该end对应的begin节点
24                 lastindex=oriindex#最近的begin行号
25         if lastindex>-1:
26             status.__setitem__(lastindex,{real:3})
27             status.__setitem__(index,{real:4})
28         else:
29             status.__setitem__(index,{real:2})
30     else:continue
31 index=0
32 log=open(logpath)
33 for r in log.readlines():
34     index=index+1;
35     if status.get(index,0)!=0 and status[index].values()[0]>2:
36         row=status[index]
37         for k,v in row.items():
38             if v==3:
39                 content.append('<%s>\n'%k)
40             elif v==4:
41                 content.append('</%s>\n'%k)
42             # if exist.get(k,0)%2==0:#第1,3,5...次出现为begin节点
43             #     content.append('<%s>\n'%k)
44             # else:
45             #     content.append('</%s>\n'%k)#第2,4,6...次出现为end节点
46             # exist[k]=exist.get(k,0)+1
47     else:
48         content.append(r)
49 record=open(destinationPath,'w')
50 record.write(''.join(content))
51 record.close()
52 # print content
53 print status

 

posted @ 2012-12-06 18:05  hhhyde  阅读(138)  评论(0编辑  收藏  举报