python统计错误日志

python统计错误日志示例:从日志文件中读取内容,正常日志为时间戳开头,发生错误则打印错误。
代码逻辑:
按行读取日志文件,正则匹配开头是日期格式的行,如果没有匹配到说明发生了错误,记录错误信息,存入字典


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)

你可能感兴趣的:(python统计错误日志)