在业务稳定性要求比较高的情况下,运维为能及时发现问题,有时需要对应用程序的日志进行实时分析,当符合某个条件时就立刻报警,而不是被动等待出问题后去解决,比如要监控nginx的$request_time和$upstream_response_time时间,分析出最耗时的请求,然后去改进代码,这时就要对日志进行实时分析了,发现时间长的语句就要报警出来,提醒开发人员要关注,当然这是其中一个应用场景,通过这种监控方式还可以应用到任何需要判断或分析文件的地方,所以今天我们就来看看如何用python实现实时监控文件,我给三个方法实例::
第一种:
这个是最简单的和容易理解的,因为大家都知道linux下有tail命令,所以你可以直接用Popen()函数去调用这个命令来执行获取输出,代码如下:
|
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()方法分别得到当前文件位置和要移动到的位置,代码如下:
|
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来实现一个生成器函数,然后调用这个生成器函数,这样当日志文件有变化时就打印新的行,代码如下:
|
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代表文件最末尾位置。
以上就是三个常用方法,具体日志分析的代码大家可以根据自己的业务逻辑去实现,完毕。
7260

被折叠的 条评论
为什么被折叠?



