This article describes how to use the Python Dynamic Monitor program log content. the dynamic here refers to the constant addition of new log content to log files, dynamic Monitoring refers to the monitoring log new append log content log files are generally generated by day, by judging the file generation date and the current time in the program, change the monitoring log file
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
The 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)