Python動態監控日志的內容
本文介紹如何使用Python動態監控程序日志的內容,這里的動態指的是日志文件不斷的追加新的日志內容,動態監控是指監控日志新追加的日志內容
日志文件一般是按天產生,則通過在程序中判斷文件的產生日期與當前時間,更換監控的日志文件
程序只是簡單的示例一下,監控test1.log 10秒,轉向監控test2.log
程序監控使用是linux的命令tail -f來動態監控新追加的日志,
Github上有一個項目,使用Python實現的類似unix系統的tail -f(Unix tail follow implementation in Python) 項目地址是:https://github.com/kasun/python-tail
代碼可以參考以下:
#!/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)
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!