python脚本编程:实时监控日志文件

用python可以很小巧轻便的实时监控日志文件增量刷新,根据某些关键字进行匹配,方便做运维异常告警

代码

import time
import re

# specify log file path
log_path = "my.log"

# open file and monitor newst line
number = 0
position = 0

with open(log_path, mode='r') as f:
    while True:
        line = f.readline().strip()
        if line:
            number += 1
            print("[number %s] %s" % (number, line))

            # TODO: check the kewword and do sth with line

        cur_position = f.tell() # record last time file read position

        if cur_position == position:
            time.sleep(0.1) # currently no line udpated, wait a while
            continue
        else:
            position = cur_position
  • 适用于python2和python3,在python3种还可以指定读取的文件编码
  • 每次启动脚本都从头过一遍文件内容至当前的最新行,之后都会一直监控最新行
  • 可以引入正则表达式做更精准的字符串匹配和查询

你可能感兴趣的:(python)