2013-07-05 55 views
1

我有一個日誌文件,其文本看起來像這樣。python:使用正則表達式從日誌文件中讀取日期時間

Jul 1 03:27:12 syslog: [m_java][ 1/Jul/2013 03:27:12.818][j:[SessionThread <]^Iat com/avc/abc/magr/service/find.something(abc/1235/locator/abc;Ljava/lang/String;)Labc/abc/abcd/abcd;(bytecode:7) 

該文件中有兩種時間格式。我需要根據[]中的日期時間格式對此日誌文件進行排序。

這是我正在嘗試使用的正則表達式。但它不會返回任何東西。

t_pat = re.compile(r".*\[\d+/\D+/.*\]") 

我想去過每一行的文件,能夠應用這種模式,並根據日期&時間線排序。

有人可以幫助我嗎?謝謝!

+0

會不會反而easer在行首使用日期和時間? – Ronnie

+0

'['和'1'之間是否有空格? –

+0

[]內的時間以秒爲單位更精確。我確實在一秒鐘內獲得了很多日誌,需要進行排序。 –

回答

1

你不符合最初的空間;你也想組,便於提取的日期,並限制\D.*模式,以非貪婪:

t_pat = re.compile(r".*\[\s?(\d+/\D+?/.*?)\]") 

演示:

>>> re.compile(r".*\[\s?(\d+/\D+?/.*?)\]").search(line).group(1) 
'1/Jul/2013 03:27:12.818' 

可以縮小模式的更多一些;你只需要符合3個字母月例如:

t_pat = re.compile(r".*\[\s?(\d{1,2}/[A-Z][a-z]{2}/\d{4} \d{2}:\d{2}:[\d.]{2,})\]") 
+0

我也認爲你需要使最後一個量詞lazy:\ [\ s?\ d +/\ D + /。*?\] – Ronnie

2

你在那裏,需要添加到正則表達式

text = "Jul 1 03:27:12 syslog: [m_java][ 1/Jul/2013 03:27:12.818][j:[SessionThread <]^Iat com/avc/abc/magr/service/find.something(abc/1235/locator/abc;Ljava/lang/String;)Labc/abc/abcd/abcd;(bytecode:7)" 
matches = re.findall(r"\[\s*(\d+/\D+/.*?)\]", text) 
print matches 
['1/Jul/2013 03:27:12.818'] 

下一頁空間使用下面的函數解析時間

http://docs.python.org/2/library/time.html#time.strptime

最後用這個作爲重點成字典和行作爲值,並根據密鑰對這些條目進行排序。

+0

回答需要更多詳細信息 –

+1

添加更多詳細信息。 :) – beiller

1

Read all the lines of the file和使用sort功能和函數傳遞parses out the date,並將其用作the key for sorting

import re 
import datetime 

def parse_date_from_log_line(line): 
    t_pat = re.compile(r".*\[\s?(\d+/\D+?/.*?)\]") 
    date_string = t_pat.search(line).group(1) 
    format = '%d/%b/%Y %H:%M:%S.%f' 
    return datetime.datetime.strptime(date_string, format) 

log_path = 'mylog.txt' 
with open(log_path) as log_file: 
    lines = log_file.readlines() 
    lines.sort(key=parse_date_from_log_line) 
+0

我得到以下錯誤:date_string = t_pat.search(line).group(1 ) AttributeError:'NoneType'對象沒有屬性'group' –

+0

@SupriyaK這是假設行不是無,在代碼中沒有錯誤檢查,如果有它將不得不處理None情況並且如果沒有日期時間需要決定是否跳過它。 –

相關問題