2013-02-22 39 views
1

我試圖從一個nginx的日誌文件中解析以下格式:解析用空格作爲分隔符nginx的日誌數據

10.0.0.1 [02/Oct/2012:10:21:46 +0000] GET /api/123/test.json?stop=2012-09-29 502 0 

我的Python腳本:

#!/usr/bin/env python 

f = file('slow-queries.txt', 'r') 

# iterate over the lines in the file 
for line in f: 
    # split the line into a list of column values 
    columns = line.split(' ') 
    # clean any whitespace off the items 
    # columns = [col.strip() for col in columns] 

    # ensure the column has at least one value before printing 
    if columns: 
     print "first =>", columns[0] # print the first column 
     print "second =>", columns[1] 

基本上所有我從日誌要文件是發送的查詢,所以在上面的例子中,我正在尋找提取/api/123/test.json?stop=2012-09-29

我的腳本似乎沒有這樣做,我做錯了什麼?

回答

3

這些都是標籤,不是空格:

ip, date, method, path, status, _ = line.split('\t') 
1

你在做什麼錯誤是使用通用編程語言,其中一個專門的日誌文件解析器語言可供選擇:AWK)

awk '{ print $5 }' /path/to/slow-queries.txt 

當然它可能與Python/PHP /的Perl /你的廣告/但awk將總是出執行這些^^

編輯: 甚至可能管結果到一個新的文件有這些將被你的python腳本使用:

awk '{ print $5 }' /path/to/slow-queries.txt > /tmp/queries.txt