Python实时监控文件方法

在业务稳定性要求比较高的情况下,运维为能及时发现问题,有时需要对应用程序的日志进行实时分析,当符合某个条件时就立刻报警,而不是被动等待出问题后去解决,比如要监控nginx的$request_time和$upstream_response_time时间,分析出最耗时的请求,然后去改进代码,这时就要对日志进行实时分析了,发现时间长的语句就要报警出来,提醒开发人员要关注,当然这是其中一个应用场景,通过这种监控方式还可以应用到任何需要判断或分析文件的地方,所以今天我们就来看看如何用python实现实时监控文件,我给三个方法实例::

第一种:

这个是最简单的和容易理解的,因为大家都知道linux下有tail命令,所以你可以直接用Popen()函数去调用这个命令来执行获取输出,代码如下:

Python
logfile='access.log' command='tail -f '+logfile+'|grep "timeout"' popen=subprocess.Popen(command,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True) while True: line=popen.stdout.readline().strip() print line
1
2
3
4
5
6
7
logfile = 'access.log'
command = 'tail -f ' + logfile + '|grep "timeout"'
popen = subprocess . Popen ( command , stdout = subprocess . PIPE , stderr = subprocess . PIPE , shell = True )
while True :
     line = popen . stdout . readline ( ) . strip ( )
     print line
 

第二种:

采用python对文件的操作来实现,用文件对象的tell(), seek()方法分别得到当前文件位置和要移动到的位置,代码如下:

Python
import time file = open('access.log') while 1: where = file.tell() line = file.readline() if not line: time.sleep(1) file.seek(where) else: print line,
1
2
3
4
5
6
7
8
9
10
11
12
import time
 
file = open ( 'access.log' )
while 1 :
     where = file . tell ( )
     line = file . readline ( )
     if not line :
         time . sleep ( 1 )
         file . seek ( where )
     else :
         print line ,
 

第三种:

利用python的 yield来实现一个生成器函数,然后调用这个生成器函数,这样当日志文件有变化时就打印新的行,代码如下:

Python
import time def follow(thefile): thefile.seek(0,2) while True: line = thefile.readline() if not line: time.sleep(0.1) continue yield line if __name__ == '__main__': logfile = open("access-log","r") loglines = follow(logfile) for line in loglines: print line,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import time
def follow ( thefile ) :
     thefile . seek ( 0 , 2 )
     while True :
         line = thefile . readline ( )
         if not line :
             time . sleep ( 0.1 )
             continue
         yield line
 
if __name__ == '__main__' :
     logfile = open ( "access-log" , "r" )
     loglines = follow ( logfile )
     for line in loglines :
         print line ,
 

最后解释下seek()函数的用法,这个函数接收2个参数:file.seek(off, whence=0),从文件中移动off个操作标记(文件指针),正数往结束方向移动,负数往开始方向移动。如果设定了whence参数,就以whence设定的起始位为准,0代表从头开始,1代表当前位置,2代表文件最末尾位置。

以上就是三个常用方法,具体日志分析的代码大家可以根据自己的业务逻辑去实现,完毕。




  • zeropython 微信公众号 5868037 QQ号 5868037@qq.com QQ邮箱
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值