本文目录


python3 实时监控获取日志文件的增量内容进行分析

场景:

python写一个脚本,用来实时监控日志文件中的增量内容,每隔十分钟会生成一个新的log文件(单个文件大小2G左右),还需要自动切换需要查询的目标文件(按照时间日期不同切换,递归实现),需求是实现了,如果有更好的建议,欢迎大佬指点。

直接上代码,以txt文本为测试目标:

import time

def run(log_path):
    count = 0
    position = 0
    with open(log_path, mode='r', encoding='utf8') as f1:
        while True:
            line = f1.readline().strip()
            if line:
                count += 1
                print("count %s line %s" % (count, line))
                cur_position = f1.tell()  # 记录上次读取文件的位置
            if cur_position == position:
                time.sleep(0.1)
                continue
            else:
                position = cur_position
                time.sleep(0.1)

原文地址 www.hotbak.net

文章作者:  BigYoung
版权声明:  本网站所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 BigYoung !