2013-02-22 35 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