python統(tǒng)計(jì)錯誤日志示例:從日志文件中讀取內(nèi)容,正常日志為時間戳開頭,發(fā)生錯誤則打印錯誤倒彰。
代碼邏輯:
按行讀取日志文件疟游,正則匹配開頭是日期格式的行呼畸,如果沒有匹配到說明發(fā)生了錯誤,記錄錯誤信息颁虐,存入字典
image.png
import re
import json
findstr = {}
detail = []
regx = re.compile(r'\[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}.\d{3}\]')
tag = 0
with open('20190812.txt', 'r', encoding='utf-8') as log:
for line in log:
ret = regx.match(line)
if ret:
if tag == 1:
# s = str(detail)
findstr[tmp]=detail
# print(s)
tag = 0
tmp = line.replace('\n','')
detail = []
else:
tag = 1
detail.append(line.replace('\n',''))
for key in findstr:
print(key)
s = '\n'.join(findstr[key])
print(s)
with open('error_log.json','w') as log:
json.dump(findstr,log,indent=4)