This is a program that reads real-time log files on a timed basis. The target file is target_file. It is written by the application in real time.
What I'm going to do is, every 5 seconds, extract the contents of the log file once, and then generate another file. Finally, the files are summarized. Please give me a lot of advice.
#!/usr/local/bin/python# Coding:utf-8Import Fileinputimport TimeImport Ostarget_file =' User.log 'Init_flag = True# First Load programTime_kick =5Record_count =0 whileTrue:Print ' currently read ', Record_count#没有日志文件, wait. if notOs.path.exists(target_file):Print ' target_file not exist ' Time.Sleep(Time_kick)ContinueTry: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 ')ifInit_flag:#读取整个文件 forEachline in Fileinput.input (target_file):PrintEachline F_w.Write(eachline) Record_count + =1Init_flag = FalseElse:#如果总行数小于当前行, you think the file is updated and read from the first line. Total_count = Os.popen (' wc-l%s '% target_file).Read().Split()[0] Total_count =int(Total_count)ifTotal_count < Record_count:record_count =0 forEachline in Fileinput.input (target_file): Line_no = Fileinput.filelineno ()ifLine_no > Record_count:PrintEachline F_w.Write(eachline) Record_count + =1F_w.Close() Except:pass Time.Sleep(Time_kick)
A program that Python periodically extracts real-time logs