Python dynamic monitoring of log content sample _python

Source: Internet
Author: User
Tags current time

Log files are usually generated by day, then replace the monitored log files by judging the file's date of production and the current time in the program
The program is just a simple example, monitor test1.log 10 seconds, turn to monitor Test2.log

Program monitoring uses Linux's command tail-f to dynamically monitor newly appended logs

Copy Code code as follows:

#!/usr/bin/python
# Encoding=utf-8
# Filename:monitorLog.py
Import OS
Import Signal
Import subprocess
Import time


LogFile1 = "Test1.log"
LogFile2 = ' Test2.log '

#日志文件一般是按天产生, replace the monitored log file by judging the file's date of production and the current time in the program
#程序只是简单的示例一下, monitor test1.log 10 seconds, turn to monitor Test2.log
def monitorlog (logFile):
print ' Monitored log file is%s '% LogFile
# program runs for 10 seconds, monitors another log
StopTime = Time.strftime ('%y-%m-%d%h:%m:%s ', Time.localtime (time.time () + 10))
Popen = subprocess. Popen (' tail-f ' + logFile, stdout=subprocess. PIPE, Stderr=subprocess. PIPE, Shell=true)
PID = Popen.pid
Print (' popen.pid: ' + str (PID))
While True:
line = Popen.stdout.readline (). Strip ()
# Determine if the content is empty
If line:
Print (line)
# Current Time
Thistime = Time.strftime ('%y-%m-%d%h:%m:%s ', Time.localtime (Time.time ()))
If Thistime >= stoptime:
# Terminate child process
Popen.kill ()
print ' Kill subprocess '
Break
Time.sleep (2)
Monitorlog (LogFile2)

if __name__ = = ' __main__ ':
Monitorlog (LogFile1)

Related Article

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.