博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python动态监控日志的内容
阅读量:7225 次
发布时间:2019-06-29

本文共 1213 字,大约阅读时间需要 4 分钟。

     日志文件一般是按天产生,则通过在程序中判断文件的产生日期与当前时间,更换监控的日志文件

程序只是简单的示例一下,监控test1.log 10秒,转向监控test2.log

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

     Github上有一个项目,使用Python实现的类似unix系统的tail -f(Unix tail follow implementation in Python) 项目地址是:

     代码可以参考以下:

#!/usr/bin/python# encoding=utf-8# Filename: monitorLog.pyimport osimport signalimport subprocessimport timelogFile1 = "test1.log"logFile2 = 'test2.log'#日志文件一般是按天产生,则通过在程序中判断文件的产生日期与当前时间,更换监控的日志文件#程序只是简单的示例一下,监控test1.log 10秒,转向监控test2.logdef 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)

转载地址:http://mdufm.baihongyu.com/

你可能感兴趣的文章
数据强转
查看>>
Latest crack software ftp download
查看>>
OpenStack 的防火墙规则流程
查看>>
Overloading Django Form Fields
查看>>
03.MyBatis的核心配置文件SqlMapConfig.xml
查看>>
python学习笔记(9)-python编程风格
查看>>
博客作业04--树
查看>>
自适应网页设计(Responsive Web Design)
查看>>
Python打开新世界的大门-入门篇1
查看>>
详解Oracle数据字典
查看>>
演示:OSPF的邻居关系故障分析与排除
查看>>
Apache HTTP Server搭建虚拟主机
查看>>
Ntop性能提升方案
查看>>
用PowerDesigner将DB2数据字典导成WORD
查看>>
(译).NET4.X 并行任务中Task.Start()的FAQ
查看>>
git log显示
查看>>
Java-抽象类定义构造方法
查看>>
Android 短信模块分析(二) MMS中四大组件核心功能详解
查看>>
poj 3615(floyd变形)
查看>>
分享45个设计师应该见到的新鲜的Web移动设备用户界面PSD套件
查看>>