我是 python 新手。我正在尝试编写一个快速而肮脏的python脚本来查找某些字符串日志文件并从该行中提取某些信息。日志文件中的行如下所示
2012-08-01 13:36:40,449 [PDispatcher: ] ERROR Fatal error DEF_CON encountered. Shutting down
2012-08-01 14:17:10,749 [PDispatcher: ] INFO Package 1900034442 Queued for clearance.
2012-08-01 14:23:06,998 [PDispatcher: ] ERROR Exception occurred attempting to lookup prod id 90000142
我有一个函数,其中输入参数将是文件名和要查找的模式数组。目前我可以找到文件中包含一个或多个指定模式的所有行(尽管不确定它是否是最有效的方法)并且我能够提取行号和行。
def searchLogs(fn, searchPatterns):
res = []
with open(fn) as f:
for lineNo, line in enumerate(f, 1):
#check if pattern strings exist in line
for sPattern in searchPatterns:
if sPattern in line:
fountItem = [fn, pattern, lineNo, line]
res.append(fountItem)
return res
searchLogs("c:\temp\app.log", ["ERROR", "DEF_CON"]) #this should return 3 elements based on the above log snipped (2 for the first line and 1 for the third line)
我还想做的是在搜索时提取日期和时间。因此,我正在考虑将搜索模式修改为带有分组的正则表达式字符串,以搜索和提取日期。只有一个问题,我不确定如何在 python 中做到这一点......任何帮助将不胜感激。
编辑(解决方案):在塞巴斯蒂安的帮助和乔尔提供的链接下,我想出了这个解决方案:
def search_logs(fn, searchPatterns):
res = []
with open(fn) as f:
for lineNo, line in enumerate(f, 1):
#check if pattern strings exist in line
for sPattern in searchPatterns:
#crude reg ex to match pattern and if matched, 'group' timestamp
rex = r'^(.+) \[.*' + pattern
ms = re.match(rex, line)
if ms:
time = ms.group(1)
item = Structs.MatchedItem(fn, pattern, lineNo, line, time)
res.append(item)
return res
search_logs("c:\temp\app.log", ["ERROR", "DEF_CON"]) #this should return 3 elements based on the above log snipped (2 for the first line and 1 for the third line)