python实时监控文件夹中的文件_使用Python实时查看文件夹中的日志

我正在尝试使用python为一个日志文件夹定制一个logwatcher。目标很简单,在日志中找到正则表达式,如果找到就在文本中写一行。在

问题是脚本必须针对一个文件夹不断运行,其中可能有多个未知名称的日志文件,而不是一个单独的,它应该动态地检测到文件夹中新日志文件的创建。在

我在python中做了一些tail-f(复制部分代码),它会不断地读取特定的日志文件,并在txt文件中写入一行(如果在其中找到regex),但是我不知道如何用一个文件夹而不是一个日志文件来完成它,以及脚本如何检测文件夹中新日志文件的创建,以便动态读取它们。在#!/usr/bin/env python

import time, os, re

from datetime import datetime

# Regex used to match relevant loglines

error_regex = re.compile(r"ERROR:")

start_regex = re.compile(r"INFO: Service started:")

# Output file, where the matched loglines will be copied to

output_filename = os.path.normpath("log/script-log.txt")

# Function that will work as tail -f for python

def follow(thefile):

thefile.seek(0,2)

while True:

line = thefile.readline()

if not line:

time.sleep(0.1)

continue

yield line

logfile = open("log/service.log")

loglines = follow(logfile)

counter = 0

for line in loglines:

if (error_regex.search(line)):

counter += 1

sttime = datetime.now().strftime('%Y%m%d_%H:%M:%S - ')

out_file=open(output_filename, "a")

out_file.write(sttime + line)

out_file.close()

if (start_regex.search(line)):

sttime = datetime.now().strftime('%Y%m%d_%H:%M:%S - ')

out_file=open(output_filename, "a")

out_file.write(sttime + "SERVICE STARTED\n" + sttime + "Number of errors detected during the startup = {}\n".format(counter))

counter = 0

out_file.close()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值