python統(tǒng)計錯誤日志

python統(tǒng)計錯誤日志示例:從日志文件中讀取內(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)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容