如何遍历日志文件中的特定时间范围? [英] How to to iterate through a specific time range in a logfile?

查看:53
本文介绍了如何遍历日志文件中的特定时间范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如: [2017-04-14 03:56:22,085109]

如果这是事件A发生的时间,我想在日志文件中的这一行之前15分钟,它将有成千上万行,并且我想遍历这段时间的每一行并查找特定的关键字.日志文件中的每一行都有相同格式的时间戳.

If this is the time where event A happens, I want to go 15 minutes before this line in the logfile which will have thousands of line and I want to iterate through everyline in that period and look for specific keywords. Every line in the logfile has the time stamp with the same format.

推荐答案

您可以使用开始时间和结束时间过滤所需的行.

You can filter the desired lines with a start and end time.

main.py

from datetime import datetime, timedelta

event_time = datetime.strptime('2017-04-14 03:56:22,085109', '%Y-%m-%d %X,%f')
event_start = event_time - timedelta(minutes=15)


def line_date(line):
    return datetime.strptime(line[1:27], '%Y-%m-%d %X,%f')


with open('example.log', 'r') as myfile:
    lines = filter(lambda x: event_start <= line_date(x) <= event_time,
                   myfile.readlines())


print(lines)

example.log

[2017-04-13 03:56:22,085109] My old log
[2017-04-14 03:55:22,085109] My log in less than 15 minutes ago
[2017-04-14 03:56:22,085109] My important event
[2017-04-14 03:57:22,085109] Log after my important event

但是我建议您使用 python3 (而不是python2). filter 返回一个迭代器,而不是完整列表.

But I recommend you to use python3 (instead of python2). filter returns an iterator, instead of the full list.

这篇关于如何遍历日志文件中的特定时间范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆