簡體   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