An example of python dynamically monitoring log content
- 2020-04-02 13:27:27
- OfStack
Log files are generally generated on a daily basis, then by determining the date and current time of file generation in the program, replace the monitored log files
The program is just a simple example of monitoring test1.log for 10 seconds and then moving on to monitoring test2.log
Program monitoring USES the Linux command tail-f to dynamically monitor newly appended logs
#!/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, then by determining the date and current time of file generation in the program, replace the monitored log files
# The program is just a simple example of monitoring test1.log 10 Seconds, turn to monitor test2.log
def monitorLog(logFile):
print ' Monitored log files is %s' % logFile
# The program runs 10 Second, monitor 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)
# The 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)