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 opencv实现gif图片分解的示例代码

python opencv实现gif图片分解的示例代码

案例:将和当前脚本同目录下的gif图片分解成png图片,并将分解后的图片保存到pics目录下,将其从0开始命名。 GIF 动图的分解可以利用 PIL模块的Image类来实现。 fr...

python覆盖写入,追加写入的实例

追加写入: # -*- coding:utf-8 -*- # a 指定打开文件的模式,a为追加 r为只读 a=open('test.txt', 'a') a.write('追...

Python实现合并字典的方法

本文实例讲述了Python实现合并字典的方法。分享给大家供大家参考。具体实现方法如下: # 将两个字典合并 #!/usr/bin/python def adddict(dict1,d...

python 实现将文件或文件夹用相对路径打包为 tar.gz 文件的方法

默认情况下,tarfile 打包成的 tar.gz 文件会带绝对路径,而很多情况下,我们需要的是相对打包文件夹的路径。 代码: <pre name="code" class="...

python 在屏幕上逐字显示一行字的实例

如下所示: #-*- coding: utf-8 -*- #code:myhaspl@qq.com #12-1.py import sys reload(sys) sys.setde...