繁体   English   中英

最近5分钟读取日志文件python 2.6

[英]Reading log file last 5 minutes python 2.6

我用python编写了一个脚本来读取日志文件的最后5分钟,这是到目前为止的代码

from datetime import datetime, timedelta

now = datetime.now()
before = timedelta(minutes=5)
now = now.replace(microsecond=0)
before = (now-before)
now = (now.strftime("%b %d %X"))
before = (before.strftime("%b %d %X"))
print(before)
print(now)

with open('user.log','r') as f:
    for line in f:
        if before in line:
            break

    for line in f:
        if now in line:
            break
        print (line.strip())

输出是Sep 03 11:47:25 Sep 03 11:52:25这是检查时间是否正确的打印,日志中有近100行有时间,但是如果我把ifs取出,请不要带我什么然后打印所有行,证明问题出在...

有任何想法吗?

这是我的日志文件内容的一个示例:

Sep 03 10:18:47 bni..........teagagfaesa.....
Sep 03 10:18:48 bni..........teagagfaesa.....2

我设法找到了一个比您还老的Python。

#!/usr/bin/env python

from __future__ import with_statement
from datetime import datetime, timedelta

before = timedelta(minutes=5)
now = datetime.now().replace(microsecond=0, year=1900)
before = (now-before)

with open('user.log','r') as f:
    for line in f:
        if datetime.strptime(line[0:15], '%b %d %X') < before:
            continue
        print line.strip()

与您的代码相比,所做的更改是我们将文件中的每个时间戳转换为datetime对象; 然后我们可以按照您期望的方式对这些正确的机器可读表示形式进行比较(而如果不解析日期,它将无法正常工作,除非偶然- "Sep""Aug""Sep""Oct"也是如此;因此,如果您在合适的月份运行它似乎可以正常工作,但是在下个月休息!)

year=1900 hack是因为strptime()对于没有year的输入默认为1900年

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM