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)

相关文章

python中class的定义及使用教程

类的定义 class classname[(父类名)]: – 成员函数及成员变量 _ init _ 构造函数:初始化对象 _ del_ 析构函数:销毁对象 定义类的成员函数时,必须默认一...

把pandas转换int型为str型的方法

今天在数据分析时遇到了一个小问题,这时才发现自己的基础知识真的不牢固,所以这里记录一下解决方法 问题: 我在处理完数据后得到的是一个列表,其中放入的是很多的元组,这时需要从元组中筛选数据...

django框架forms组件用法实例详解

django框架forms组件用法实例详解

本文实例讲述了django框架forms组件用法。分享给大家供大家参考,具体如下: 在django中forms组件有其强大的功能,里面集合和众多的函数和方法:下面来看一下它的源码 "...

python取数作为临时极大值(极小值)的方法

编程中有时候需要一个初始极大值(或极小值)作为temp,当然可以自定义设置为10000(whatever),不过python中有一个值可以代替之: 在python2.7中可以用这个(不...

python3.8与pyinstaller冲突问题的快速解决方法

python3.8与pyinstaller冲突问题的快速解决方法

安装pyinstaller 安装的时候 进入cmd pip install pyinstaller 发现安装报错! 解决办法: # 自主下载pyinstaller包,进行手动安装...