python动态监控日志内容的示例

yipeiwu_com6年前Python基础

日志文件一般是按天产生,则通过在程序中判断文件的产生日期与当前时间,更换监控的日志文件
程序只是简单的示例一下,监控test1.log 10秒,转向监控test2.log

程序监控使用是linux的命令tail -f来动态监控新追加的日志

复制代码 代码如下:

#!/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)

相关文章

基于wxPython的GUI实现输入对话框(2)

基于wxPython的GUI实现输入对话框(2)

接着上一篇基于wxPython的GUI输入对话框1,继续学习。 在程序输入中,有时会要求同时改变多个参数值,而且类型也不尽相同, 这时TextEntryDialog就显得不适用了.WxI...

Python解析网页源代码中的115网盘链接实例

本文实例讲述了python解析网页源代码中的115网盘链接的方法。分享给大家供大家参考。具体方法分析如下: 其中的1.txt,是网页http://bbs.pediy.com/showth...

Python图像处理模块ndimage用法实例分析

Python图像处理模块ndimage用法实例分析

本文实例讲述了Python图像处理模块ndimage用法。分享给大家供大家参考,具体如下: 一 原始图像 1 代码 from scipy import misc from scipy...

python 多进程共享全局变量之Manager()详解

Manager支持的类型有 list,dict,Namespace,Lock,RLock,Semaphore,BoundedSemaphore,Condition,Event,Queue...

Python面向对象程序设计类的多态用法详解

本文实例讲述了Python面向对象程序设计类的多态用法。分享给大家供大家参考,具体如下: 多态 1、多态使用 一种事物的多种体现形式,举例:动物有很多种 注意: 继承是多态的前提 函数重...