日誌文件通常是按天產生,則經過在程序中判斷文件的產生日期與當前時間,更換監控的日誌文件
程序只是簡單的示例一下,監控test1.log 10秒,轉向監控test2.log python
程序監控使用是linux的命令tail -f來動態監控新追加的日誌, linux
Github上有一個項目,使用Python實現的相似unix系統的tail -f(Unix tail follow implementation in Python) 項目地址是:https://github.com/kasun/python-tail git
代碼能夠參考如下: github
#!/usr/bin/python # encoding=utf-8 # Filename: monitorLog.py import os import signal import subprocess import time logFile1 = "test1.log" logFile2 = 'test2.log' #日誌文件通常是按天產生,則經過在程序中判斷文件的產生日期與當前時間,更換監控的日誌文件 #程序只是簡單的示例一下,監控test1.log 10秒,轉向監控test2.log def monitorLog(logFile): print '監控的日誌文件 是%s' % logFile # 程序運行10秒,監控另外一個日誌 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() # 判斷內容是否爲空 if line: print(line) # 當前時間 thistime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) if thistime >= stoptime: # 終止子進程 popen.kill() print '殺死subprocess' break time.sleep(2) monitorLog(logFile2) if __name__ == '__main__': monitorLog(logFile1)