python 讀取ng日志并根據(jù)關(guān)鍵字分離出相關(guān)行數(shù)據(jù)

運(yùn)維時(shí)需要分析ng的log日志, 然后根據(jù)關(guān)鍵字讀取相關(guān)行數(shù)據(jù)出來分析, 避免打開整個(gè)文件太大導(dǎo)致緩慢.


代碼如下


'''

讀取keyWordName關(guān)鍵字的出現(xiàn)次數(shù)

'''

# 計(jì)數(shù)

count =0

# 每次讀取文件內(nèi)容大小

sizeInt =1000000

matchList = []

# 查詢關(guān)鍵字

def findWordCount(f, sizeInt, keyWordName):

global count

count =0;

while True:

line = f.readline(sizeInt)

if not line:

break

pass

? ? ? ? lineStr =str(line)

if lineStr.find(keyWordName) > -1:

matchList.append(lineStr)

count +=1

? ? ? ? ? ? # print(lineStr)

? ? return count

# 打印

def printKeywordCount(f, sizeInt, keyWordName):

count = findWordCount(f, sizeInt, keyWordName)

print(count)

print(keyWordName +"出現(xiàn)次數(shù): " +str(count))

# 查詢文件里關(guān)鍵字出現(xiàn)次數(shù)

def findTheKeyWordCount(fileName, keyWordName):

with open(fileName, "r", encoding="utf-8", errors='ignore')as f:

printKeywordCount(f, sizeInt, keyWordName)

def saveMatchList(saveFileName, matchList):

contents =""

? ? for iin range(0, len(matchList)):

contents += matchList[i] +"\n"

? ? save2File(saveFileName, contents)

# 保存文件

def save2File(fileName, content):

f =open(fileName, "w")

num = f.write(content)

print(num)

# 關(guān)閉打開的文件

? ? f.close()

# 執(zhí)行工作

def doMyJob(fileName, keyWordName, saveFileName):

# 查詢關(guān)鍵字

? ? findTheKeyWordCount(fileName, keyWordName)

# 打印

# print(matchList)

# 保存文件

? ? saveMatchList(saveFileName, matchList)

if __name__ =='__main__':

# 文件所在目錄

? ? fileName ="D:/code/workspace/python/test1/test/files/error.log"

? ? # 需要查詢的關(guān)鍵字

? ? keyWordName ="[error]"

? ? # 解析后的內(nèi)容保存文件

? ? saveFileName ="D:/code/workspace/python/test1/test/files/error_logs_20180704.txt"

? ? doMyJob(fileName, keyWordName, saveFileName)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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