4

打印与日期时间范围匹配的日志行的最佳方法是什么。例如:

我只想打印日期从:2012/09/30-00:00:10 到:2012/09/30-00:00:13 的行

2012/09/30-00:00:08.773 log error
2012/09/30-00:00:09.034 log warning
2012/09/30-00:00:09.352 log info
2012/09/30-00:00:10.526 log info
2012/09/30-00:00:10.995 log warning
2012/09/30-00:00:12.014 log warning
2012/09/30-00:00:18.035 log error
2012/09/30-00:00:21.733 log fatal
2012/09/30-00:00:21.981 log info

它应该打印:

2012/09/30-00:00:10.526 log line
2012/09/30-00:00:10.995 log line
2012/09/30-00:00:12.014 log line

由于我正在使用生产服务器,因此我想以一种具有成本效益的方式来做到这一点。请只使用Python。谢谢!

4

5 回答 5

7

Actullay,日志格式允许比较日期字符串而无需将其转换为datetime.

with open('mylog.log','r') as f:
    for line in f:
        d = line.split(" ",1)[0] 
        if d >= '2012/09/30-00:00:10' and d <= '2012/09/30-00:00:13':
            print line
于 2012-09-30T10:33:21.510 回答
1

我不确定性能影响(我怀疑蒂姆的回答可能更快),但这种方法适用于任何日期范围:

>>> def dates(start,end):
...     for i in range(int((end-start).seconds)):
...         yield start + datetime.timedelta(seconds=i)
...
>>> fmt = '%Y/%m/%d-%H:%M:%S'
>>> from_date = datetime.datetime.strptime('2012/09/30-00:00:10',fmt)
>>> till_date = datetime.datetime.strptime('2012/09/30-00:00:13',fmt)
>>> with open('file.log') as f:
...     for line in f:
...         if datetime.datetime.strptime(line.split()[0][:-4],fmt) in dates(fro
m_date,till_date):
...              print line
...
2012/09/30-00:00:10.526 log info
2012/09/30-00:00:10.995 log warning
2012/09/30-00:00:12.014 log warning
于 2012-09-30T09:50:13.617 回答
1

假设您正在逐行阅读日志:

import re
for line in log:
    if re.match("2012/09/30-00:00:1[0-3]", line):
        print line
于 2012-09-30T09:41:51.200 回答
0

根据 Tim 的假设,您正在逐行读取日志文件,然后使用itertools.

from itertools import dropwhile, takewhile

from_dt, to_td = '2012/09/30-00:00:10', '2012/09/30-00:00:13'
with open('logfile') as fin:
    of_interest = takewhile(lambda L: L <= to_td, dropwhile(lambda L: L < from_dt, fin))
    for line in of_interest:
        print line
于 2012-09-30T12:20:17.677 回答
0

.startswith()示例

prefixes = tuple("2012/09/30-00:00:1%d" % i for i in range(3))
with open('mylog.log', 'rb') as file:
    print ''.join(line for line in file if line.startswith(prefixes)),

您可以通过使用单个静态前缀来优化它,然后稍后使用正则表达式或日期时间对象测试预选的行。

如果行在输入中按日期排序;您可以在不阅读整个文件的情况下提前中断。

于 2012-09-30T11:53:47.753 回答