本文實(shí)例為大家分享了python定時(shí)提取實(shí)時(shí)日志的具體代碼,供大家參考,具體內(nèi)容如下
這是一個(gè)定時(shí)讀取 實(shí)時(shí)日志文件的程序。目標(biāo)文件是target_file. 它是應(yīng)用程序?qū)崟r(shí)寫入的。
我要做的是,每個(gè)5秒鐘,提取一次該日志文件中的內(nèi)容,然后生成另一個(gè)文件,最后把這些文件都匯總。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
#!/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 '當(dāng)前讀到了' , record_count #沒(méi)有日志文件,等待 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: #讀取整個(gè)文件 for eachline in fileinput. input (target_file): print eachline f_w.write(eachline) record_count + = 1 init_flag = False else : #如果總行數(shù)小于當(dāng)前行,那么認(rèn)為文件更新了,從第一行開始讀。 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) |
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/weixin_37887248/article/details/80727560