import logging import os import threading import time ''' ****************By WuXuechao 20200719******************* 功能:监控某个目录下日志文件,并且筛选关键字生成过滤日志,保存当前目录test文件夹下 变量说明: log_path:日志所在目录 log_file:日志文件(含后缀) keywords:搜索关键字用**隔开 ****************By WuXuechao 20200719******************* ''' log_path="F://" log_file="fileTest.log" keywords="DispatcherServlet**IOException**pipe" KW_list=keywords.split("**") def IsFileExist(fist=1):#first缺省为1表示不是第一次初始化,非1则是第一次初始化 if not os.path.exists(log_path + "test/" ): os.mkdir(log_path + "test") script_log = log_path + "test/" + "script.log" logging.basicConfig(format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s', level=logging.DEBUG, filename=script_log, filemode='a') if not os.path.exists(log_path + log_file): logging.error(log_path+"该目录没有目标日志文件"+log_file+"+++++脚本运行失败+++++") os._exit(0)#终止程序 if fist!=1 and os.path.exists(log_path + log_file): logging.debug("+++++脚本运行成功+++++") #实时筛选log_file日志内容 def refrash_keep(): n=0 if os.path.exists(log_path + "test/" + log_file + "_test"): os.remove(log_path + "test/" + log_file + "_test") while 1: time.sleep(2) IsFileExist() file = open(log_path + log_file, mode="r") file1 = open(log_path + "test/" + log_file + "_test", mode="a") li=file.readlines() if len(li) < n: file1.truncate(0) n=0 logging.debug(log_file+"日志文件从头刷新") continue elif len(li) > n: for j in li[n:]: for li_kw in KW_list: if li_kw in j: file1.write(j) break n = len(li) file.close() file1.close() #监控路径下的类似log_file文件,筛选内容并且刷新一次 def refrash(i): IsFileExist() file=open(log_path+i,"r") with open(log_path+"test/"+i+"_test", mode="w", encoding='utf-8')as file1: for j in file: for li in KW_list: if li in j: file1.write(j) break file1.close() #监控目录下日志文件数量是否变化 def path_ifnew(): cont=0 #统计监控目录下带关键字文件的个数 ch = log_file.replace(".log", "") while 1: time.sleep(1) list1 = os.listdir(log_path) #当前目录下所有文件 list2 = [x for x in list1 if ch in x and x!=log_file] #筛选含有关键字的文件 if len(list2)!=cont: #文件个数有新增 cont=len(list2) for i in list2: #各个日志文件都筛选刷新 logging.debug(log_path+"目录下日志文件数量更新,已经筛选保存为/test/"+i) refrash(i) if __name__ == '__main__': IsFileExist(0) threads = [threading.Thread(target=refrash_keep), threading.Thread(target=path_ifnew)] for t in threads: # 启动线程 t.start()
监控某个目录下日志文件,并且筛选关键字生成过滤日志
于 2020-07-19 19:32:30 首次发布