[英]Python Regular Expression to find exception in log file
我正在編寫一個腳本來解析日志。 我需要一個正則表達式來查找日志文件中的 python 異常(如果有)。
例如,如果日志文件中有以下異常,則應以字符串格式返回以下異常。
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'klj' is not defined
我試過下面的代碼,它不會工作:
import urllib.request
import re
txt = urllib.request.urlopen(log_url).read().decode('utf-8')
exceptions = re.findall("(\w+)Error:", txt)
提前致謝
您的正則表達式只尋找以“錯誤”結尾的異常名稱,但許多以“異常”結尾。 而且您在捕獲組 1 中僅捕獲“錯誤”之前的字符,因此您不會獲得全名。
以下正則表達式將僅在行首查找異常名稱並捕獲全名:
import re
txt = """Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'klj' is not defined"""
exceptions = re.findall("""(?x) # Verbose mode
(?m) # Multiline mode (^ matches start of a line)
^ # Match start of a line
(?:\w+) # Match one or more word characters in a non-capturing group
(?:Error|Exception) # Match 'Error' or 'Exception':
(?=: ) # Lookahead assertion: next characters are ': '
""", txt)
print(exceptions)
印刷:
['NameError']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.