A program that Python periodically extracts real-time logs

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.