Bad*_*dUX 10 python sorting merge timestamp
我是python的新手,我遇到了一个我无法解决的严重问题.
我有一些结构相同的日志文件:
[timestamp] [level] [source] message
例如:
[Wed Oct 11 14:32:52 2000] [error] [client 127.0.0.1] error message
我需要用纯Python编写一个程序,它应该将这些日志文件合并到一个文件中,然后按时间戳对合并的文件进行排序.在此操作之后,我希望将此结果(合并文件的内容)打印到STDOUT(控制台).
我不明白该怎么做才有所帮助.这可能吗?
mhy*_*itz 12
你可以这样做
import fileinput
import re
from time import strptime
f_names = ['1.log', '2.log'] # names of log files
lines = list(fileinput.input(f_names))
t_fmt = '%a %b %d %H:%M:%S %Y' # format of time stamps
t_pat = re.compile(r'\[(.+?)\]') # pattern to extract timestamp
for l in sorted(lines, key=lambda l: strptime(t_pat.search(l).group(1), t_fmt)):
    print l,
首先,您将需要使用该fileinput模块从多个文件中获取数据,例如:
data = fileinput.FileInput()
for line in data.readlines():
    print line
然后将打印所有行.您还想排序,您可以使用sorted关键字进行排序.
假设你的线已经开始[2011-07-20 19:20:12],你就是金色的,因为这种格式不需要在alphanum之外进行任何排序,所以:
data = fileinput.FileInput()
for line in sorted(data.readlines()):
    print line
但是,您需要做一些更复杂的事情:
def compareDates(line1, line2):
   # parse the date here into datetime objects
   NotImplemented
   # Then use those for the sorting
   return cmp(parseddate1, parseddate2)
data = fileinput.FileInput()
for line in sorted(data.readlines(), cmp=compareDates):
    print line
对于奖励积分,你甚至可以做到
data = fileinput.FileInput(openhook=fileinput.hook_compressed)
这将使您能够读取gzip压缩日志文件.
那么用法是:
$ python yourscript.py access.log.1 access.log.*.gz
或类似的.