使用Python 2.7解析Apache日志

时间:2015-02-07 19:25:50

标签: python python-2.7 parsing logging

我正在尝试从github url读取日志文件,使用IP作为查找键添加一些地理信息,然后将一些日志信息和地理信息写入文件。我从日志中读取和写入文件,但我不确定用于从IP地址查找坐标等的lib,以及如何真正去做这部分。我找到了正则表达式模块,当我开始理解它时,我发现它已经被弃用了。这就是我所拥有的,任何帮助都会很棒。

import urllib2 
apacheLog = 'https://raw.githubusercontent.com/myAccessLog.log'

data = urllib2.urlopen(apacheLog)
for line in data:
    with open('C:\LogCopy.txt','a') as f:
        f.write(line)

2 个答案:

答案 0 :(得分:1)

  1. {@ 3}}不推荐使用,是标准库的一部分。对于2.7模块
  2. 修改 re module
  3. 您的for循环在每次迭代时打开和关闭文件。可能不是什么大问题但是大文件打开文件一次并写下需要写的内容可能会更快。只需交换forwith行的位置。
  4. 所以

    data = urllib2.urlopen(apacheLog)
    for line in data:
        with open('C:\LogCopy.txt','a') as f: # probably need a double backslash
            f.write(line)
    

    变为

    data = urllib2.urlopen(apacheLog)
    with open('C:\LogCopy.txt','a') as f: # probably need a double backslash
        for line in data.splitlines():
            f.write(line) # might need a newline character
            # f.write(line + '\n')
    
    1. here's the link
    2. 祝你好运!

      修改:在阅读了Piotr Kempa的回答后添加了data.splitlines()来电

答案 1 :(得分:1)

那么第一部分很简单。假设行以正常换行结束(他们应该),只需使用for line in data.split('\n')

然后你使用re模块(import re) - 我希望它仍然在python 2.7中使用...你可以用re.search(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", line)之类的东西提取IP地址,查找re.search()功能详细说明如何使用它。

至于在地理位置定位IP,我已经问过这个问题,试试这个问题:What python libraries can tell me approximate location and time zone given an IP address?