python實現定時提取實時日志程序
更新時間:2018年06月22日 11:41:09 作者:墨飏韶年
這篇文章主要為大家詳細介紹了python實現定時提取實時日志程序,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了python定時提取實時日志的具體代碼,供大家參考,具體內容如下
這是一個定時讀取 實時日志文件的程序。目標文件是target_file. 它是應用程序實時寫入的。
我要做的是,每個5秒鐘,提取一次該日志文件中的內容,然后生成另一個文件,最后把這些文件都匯總。
#!/usr/local/bin/python # coding:utf-8 import fileinput import time import os target_file = 'user.log' init_flag = True # 初次加載程序 time_kick = 5 record_count = 0 while True: print '當前讀到了', record_count #沒有日志文件,等待 if not os.path.exists(target_file): print 'target_file not exist' time.sleep(time_kick) continue try: ip = '10.10.1.100' easytime = time.strftime('%Y%m%d_%H%M%S', time.localtime()) file_name = '%s_user_%s.log' % (ip,easytime) f_w = open(file_name, 'w') if init_flag: #讀取整個文件 for eachline in fileinput.input(target_file): print eachline f_w.write(eachline) record_count += 1 init_flag = False else: #如果總行數小于當前行,那么認為文件更新了,從第一行開始讀。 total_count = os.popen('wc -l %s' % target_file).read().split()[0] total_count = int(total_count) if total_count < record_count: record_count = 0 for eachline in fileinput.input(target_file): line_no = fileinput.filelineno() if line_no > record_count: print eachline f_w.write(eachline) record_count += 1 f_w.close() except: pass time.sleep(time_kick)
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
在python中實現調用可執(zhí)行文件.exe的3種方法
今天小編就為大家分享一篇在python中實現調用可執(zhí)行文件.exe的3種方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07使用Python集合顯著優(yōu)化算法性能的實戰(zhàn)案例
掌握?Python?中的?set?數據結構,是算法和數據結構的基本功,今天我們從一個實戰(zhàn)案例出發(fā),探討如何利用Python集合顯著優(yōu)化算法性能,感興趣的同學跟著小編一起來探討吧2023-06-06