我有以下Python脚本(以下摘录),该脚本读取E:\ Data \ Production目录下的所有日志文件,并查找某些正则表达式匹配项。
errors, tr, warnings = [], [], []
rootdir = 'E:\\Data\\Production'
for folder, dirs, files in os.walk(rootdir):
for file in files:
if file.endswith('.log'):
fullpath = os.path.join(folder, file)
with open(fullpath, 'r') as f:
for line in f:
for match in re.finditer(r'.*' + daysdate + '(?!.*[->OK].*).*[Ee]rror.*', line):
errors.append(match.group(0))
for match in re.finditer(r'.*' + daysdate + '.*(?!.*deployed)(?!.*complete.*)(?!.*There are no.*)(?!.*disabled.*).*TR\d{4}.*', line):
warnings.append(match.group(0))
for match in re.finditer(r'.*' + daysdate + '.*(?!.*deployed)(?!.*[->OK])(?!.*complete.*)(?!.*There are no.*)(?!.*disabled.*).*TR\d{4}.*', line):
tr.append(match.group(0))
if errors == []:
errors.append("No errors found.")
[...]
sendmail():
"Errors:\n\n%s\n" % "\n".join(map(str, errors)) +
"\Faulty:\n\n%s\n" % "\n".join(map(str, tr)) +
"\Warnings:\n\n%s\n" % "\n".join(map(str, warnings))
sendmail()
此输出为:
Errors:
No errors found.
Faulty:
<the entire line containing the matched regex>
Warnings:
No errors found.
我想做的是添加发现错误的日志文件的完整路径,因此它将改为:
Errors:
No errors found.
Faulty:
<the entire line containing the matched regex>
Error found in file: E:\Data\Production\qwer\asdf\zxcv.log
Warnings:
No warnings found.
我假设我需要以某种方式附加fullpath变量,但是我对如何实现它感到茫然。
答案 0 :(得分:1)
我相信你需要。
for match in re.finditer(r'.*' + daysdate + '.*(?!.*deployed)(?!.*[->OK])(?!.*complete.*)(?!.*There are no.*)(?!.*disabled.*).*TR\d{4}.*', line):
tr.append(match.group(0) + "\n{0}".format(fullpath))