【发布时间】:2021-07-20 12:54:21
【问题描述】:
我正在阅读一个巨大的日志文件并寻找特定的关键字。找到它们后,我需要打印具有 found 关键字的每一行。目前,我的代码打印的重复行与从我的列表中找到的行一样多。下面是我的代码。这是我所做的更新和修改的完整代码,基本上在这里我发现它发送带有关键字错误的行,带有结束行并且有点慢,我是否可以只使用打印第一行索引:
important = []
phrases = ['Error']
with open("mypath\\to\\my\\logfile.log") as file:
line = file.readline()
for line in file:
for phrase in phrases:
if phrase in line:
important.append(line)
pattern = 'ERROR*' or 'Warning*'
matching = fnmatch.filter(important, pattern)
myTeamsMessage = pymsteams.connectorcard("myTeamsWebhook")
if len(important) != 0:
# Add text to the message.
myTeamsMessage.text(str(matching))
# send the message.
myTeamsMessage.send()
# print(matching)
break
else:
# Add text to the message.
myTeamsMessage.text("Log has no error, proceed with deployment")
# send the message.
myTeamsMessage.send()
break
【问题讨论】:
-
您有日志文件内容的示例吗?这真的有助于了解问题可能来自哪里。
-
也许您只需要在
print()之后添加一个break,因为当您打印时,一个短语已经匹配,所以测试更多短语没有意义。 -
@Jonathon H,很遗憾,我无法共享包含机密数据的文件。
-
@quamrana 我试过了,它似乎有效,但我有一个条件可以进一步评估该列表是否不为空并向 MS Teams 发送通知警报,但它有点慢。
-
听起来您已经准备好提出不同的问题了。
标签: python python-3.x list logging