我正在尝试使用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()