1

我正在尝试从 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

我的脚本似乎没有这样做,我做错了什么?

4

2 回答 2

3

这些是制表符,而不是空格:

ip, date, method, path, status, _ = line.split('\t')
于 2013-02-22T11:28:28.600 回答
1

您做错的是使用通用编程语言,其中可以使用专门的日志文件解析器语言:awk ;)

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

当然它可以用 python/php/perl/YOUR AD HERE/ 但 awk 总是会胜过它们^^

编辑:甚至可能将结果通过管道传输到一个新文件,然后您的 python 脚本将使用该文件:

awk '{ print $5 }' /path/to/slow-queries.txt > /tmp/queries.txt
于 2013-02-22T11:36:53.767 回答