【发布时间】:2017-02-21 22:39:24
【问题描述】:
我刚刚开始使用 Python,我正在尝试对我的环境进行一些测试......我的想法是尝试创建一个简单的脚本来查找给定时间段内重复出现的错误。
基本上,我想在我的日常日志中计算服务器失败的次数,如果在给定的时间段内(比如 30 天)发生的故障超过给定的次数(比如 10 次),我应该能够在日志上发出警报,但是,我不想只计算 30 天间隔内的错误重复次数......我真正想要做的是计算错误发生的次数,恢复并且它们再次发生,这样如果问题持续数天,我将避免多次报告。
比如说:
file_2016_Oct_01.txt@hostname@YES
file_2016_Oct_02.txt@hostname@YES
file_2016_Oct_03.txt@hostname@NO
file_2016_Oct_04.txt@hostname@NO
file_2016_Oct_05.txt@hostname@YES
file_2016_Oct_06.txt@hostname@NO
file_2016_Oct_07.txt@hostname@NO
鉴于上述情况,我希望脚本将其解释为 2 次故障而不是 4 次,因为有时服务器可能会在恢复前几天呈现相同的状态,并且我希望能够识别问题的重现而不是只是计算失败的总数。
为了记录,这就是我浏览文件的方式:
# Creates an empty list
history_list = []
# Function to find the files from the last 30 days
def f_findfiles():
# First define the cut-off day, which means the last number
# of days which the scritp will consider for the analysis
cut_off_day = datetime.datetime.now() - datetime.timedelta(days=30)
# We'll now loop through all history files from the last 30 days
for file in glob.iglob("/opt/hc/*.txt"):
filetime = datetime.datetime.fromtimestamp(os.path.getmtime(file))
if filetime > cut_off_day:
history_list.append(file)
# Just included the function below to show how I'm going
# through the files, this is where I got stuck...
def f_openfiles(arg):
for file in arg:
with open(file, "r") as file:
for line in file:
clean_line = line.strip().split("@")
# Main function
def main():
f_findfiles()
f_openfiles(history_list)
我正在使用“with”打开文件并从“for”中的所有文件中读取所有行,但我不确定如何浏览数据以比较与一个文件相关的值较旧的文件。
我尝试将所有数据放入字典、列表或只是枚举和比较,但我在所有这些方法上都失败了 :-(
关于这里最好的方法的任何提示?谢谢!
【问题讨论】:
-
我在这里有点困惑......日志中的行看起来像
file_2016_Oct_01.txt@hostname@YES还是你说有名为file_2016_Oct_01.txt的文件里面有东西?部分解决方案是确保从最旧到最新读取记录,以便跟踪状态。 -
有多个文件,每个文件在每个服务器(大约 400 个服务器)都有一行显示当天的状态。
-
好的...文件名称是
file_2016_Oct_01.txt吗?文件中的行是否类似于hostname@YES\n?我想知道是否有按日期读取文件的好方法。我不明白你所说的file_2016_Oct_01.txt@hostname@YES是什么意思,实际上打破它或告诉我们完整的东西是一个文件名会很有帮助。 -
是的,所有文件的名称中都包含日期,例如:“hc.
. - .
.txt”。例如:hc.10.12.16.txt - .
标签: python scripting string-iteration