在實際工作中除了採用Notpad++進行日誌查找以外,還有一種更加簡單的方法就是之間將需要的關鍵字日誌進行提取的功能。該工具可以實現特定關鍵字提取和分析,該工具暫時實現功能點:
1.自動讀取文件夾下的所有日誌文件;
2.從日誌文件中提取出所需要的關鍵字;
3.自動將日誌文件解壓到文件夾中【暫未實現,下週補齊】
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
name = '日誌分析工具',
author = '$Mayongdong',
author_email = '[email protected]',
description = '$自動從日誌中提取關鍵字,用於問題定位'
date = '2020-03-07 15:54:00'
"""
import os
import re
import datetime
path = r"D:\CODE\LogAnalysis-master\SogouQ" #原始數據
target = open(r'D:\CODE\LogAnalysis-master\SogouQ\result.log', 'w') #結果輸出
files= os.listdir(path) #得到文件夾下的所有文件名稱
countX = []
for file in files: #遍歷文件夾
if not os.path.isdir(file): #判斷是否是文件夾,不是文件夾纔打開
f = open(path + "/" + file) #打開文件
iter_f = iter(f) #創建迭代器
print(iter_f) #輸出每個文件
for line in iter_f: #遍歷文件,一行行遍歷,讀取文本
if (line.find("error") > -1) or (line.find("fatal") > -1)or (line.find("exception") > -1)or (line.find("exception1") > -1):
result = re.findall(r'error|fatal|exception1|exception',line)
print(line)
target.writelines(line)
target.close()
now_time = datetime.datetime.now()
print(now_time,"自動化日誌分析完成,詳情請見result文件!!!")
上面代碼可以實現從日誌文件中將包含 error|fatal|exception1|exception幾個關鍵字的日誌所在行進行打印出來,實際效果如下:
代碼比較簡單,大佬請繞行,勿噴~~~~