场景:
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