Generally, log files are generated on a daily basis. The program judges the file generation date and current time, and replaces the monitored log files.
The program is just a simple example, monitoring test1.log 10 seconds, to monitoring test2.log
Program monitoring uses the linux Command tail-f to dynamically monitor new append logs
Copy codeThe Code is 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'
# Log files are generally generated on a daily basis. The program judges the file generation date and current time and replaces the monitored log files.
# The program is just a simple example, monitoring test1.log for 10 seconds, turning to monitoring test2.log
Def monitorLog (logFile ):
Print 'monitoring log file is % s' % logFile
# The program runs for 10 seconds and 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 whether 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:
# Killing sub-Processes
Popen. kill ()
Print 'Kill subprocess'
Break
Time. sleep (2)
MonitorLog (logFile2)
If _ name _ = '_ main __':
MonitorLog (logFile1)