我是python新手。我试图编写一个快速而脏的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)
http://docs.python.org/howto/regex.html – 2012-08-02 03:55:46
你应该改善你的问题,缺乏一些研究的问题在堆栈溢出中被认为是粗鲁的。 – 2012-08-02 03:59:49
我的道歉......这是我写的第一个python代码,正如我所说的那样,它是一个快速而肮脏的脚本,意味着可以短期解决监控问题。 – mike01010 2012-08-02 04:05:54