我正在尝试从日志目录中解析大量日志文件,以在列表中搜索任意数量的字符串以及服务器名称。我觉得我已经尝试过一百万种不同的选择,而且我只使用一个日志文件就可以正常工作。但是当我尝试浏览目录中的所有日志文件时,我似乎无法到达任何地方。
if args.f:
logs = args.f
else:
try:
logs = glob("/var/opt/cray/log/p0-current/*")
except IndexError:
print "Something is wrong. p0-current is not available."
sys.exit(1)
valid_errors = ["error", "nmi", "CATERR"]
logList = []
for log in logs:
logList.append(log)
#theLog = open("logList")
#logFile = log.readlines()
#logFile.close()
#printList = []
#for line in logFile:
# if (valid_errors in line):
# printList.append(line)
#
#for item in printList:
# print item
# with open("log", "r") as tmp_log:
# open_log = tmp_log.readlines()
# for line in open_log:
# for down_nodes in open_log:
# if valid_errors in open_log:
# print valid_errors
down_nodes
是一个预填充的列表,进一步包含标记为停机的服务器列表。
注释掉的是我一直在努力完成的一些各种尝试。
logList = []
for log in logs:
logList.append(log)
我认为这可能是将每个单独的日志文件放在一个列表中的方法,然后遍历该列表并使用 open()
后跟 readlines()
但我在这里缺少某种逻辑……也许我的想法不正确。
请给我一些建议。
谢谢。
最佳答案
所以你的最后一个 for 循环是多余的,因为 logs
已经是一个字符串列表。有了这些信息,我们可以遍历 logs
并为每个 log
做一些事情。
for log in logs:
with open(log) as f:
for line in f.readlines():
if any(error in line for error in valid_errors):
#do stuff
行 if any(error in line for error in valid_errors):
检查 line
以查看 valid_errors
中是否有任何错误在行中。该语法是一个生成器,它为 valid_errors
中的每个 error
生成 error
。
要回答您涉及 down_nodes
的问题,我认为您不应将其包含在同一个 any()
中。你应该尝试像
if any(error in line for error in valid_errors) and \
any(node in line for node in down_nodes):
关于python - 解析字符串的多个日志文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42285449/