我是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