運(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)