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)