2013-02-04 14 views
0

我是新来的Python,我正在尝试创建一个脚本来检查我所有的每日日志文件以检查错误。如何从日志文件的上次使用Python修改信息?

我可以打开文件,打印最后一次日志文件被修改,并打印出日志文件中的任何错误。

但是,这些日志中包含过去三年的日常信息。我希望能够只从日志的最后修改日期读取日志的部分(而不是从过去三年中获取所有错误,我只希望从最后一天开始发生错误。)

这里是到目前为止,我对我的剧本有什么要求:

import sys, string, os, time 

from stat import * 

from datetime import datetime 

now = datetime.now() 

f3 = 'C:\Path\filename.txt' 

seconds = os.path.getmtime(f3) 
print "Last Date Ran: ", time.strftime('%m/%d/%Y %H:%M:%S' , time.localtime(seconds)) 

for line in open(f3 , 'r'): 
    if 'error' in line: 
     print ">>> " , line 
    elif 'Error' in line: 
     print ">>> " , line 
    elif 'ERROR' in line: 
     print ">>> " , line 

有没有办法做到这一点?我搜索了高和低,没有找到我的问题的答案。请帮忙。

+0

您记录的错误是否有时间戳记? –

+0

您确定要修改上次修改时间吗?是不是总是只给你登录到文件的最后一条消息? –

+0

只是FYI,python中有一个日志记录模块。值得检查,如果你不知道它存在 –

回答

0

如果您提供更多信息,例如您的日志文件的格式,那将是可能的。

看看方法datetime.datetime.strptime。你会发现你需要的一切。

E.g.

import os.path 
from datetime import datetime 

filename = "my.log" 

def log_entry_is_interesting(line, reference_time): 
    date_str = line.split()[0] 
    date = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S") 
    return timedelta(current_datetime, date).days > reference_time: 


last_time_opened = os.path.getmtime(filename) 
with open(filename) as f: 
    for line in filter(lambda x: log_entry_is_interesting(x, last_time_opened), f): 
     do_something() 

我使用filter() -method。这在Python 3中作为生成器实现,但不在Python 2.x中实现。如果你使用2.x,我肯定会使用itertools-模块中的ifilter

1

简答题,没有。较长的答案是,你必须要么有很多浪费的解析,要么追踪文件外部的一些数据。您可以遍历整个文件,解析日志消息的时间戳,然后仅在给定时间后打印这些日志消息。尽管对于具有3年数据的文件,但您最好跟踪脚本读取的最后一行,然后每次打开文件以便每天解析该文件时寻找该行。另一种替代方法是,如果您有权访问流程中的相关部分,则可以修改日志记录机制;您可以将消息复制到第二个文件中,每次脚本运行时刷新它,或者基本上通过第二个文件缓冲日志记录,并将其作为脚本的责任将日志归档到历史文件中。

+0

同意,有一个日志记录器,与您的脚本检查消息,并重新日志消息记录到一个历史文件,一旦你已经完成你所需要的日志消息。 –

0

如果您想要从上次运行脚本时得到错误,请尝试将日志文件的上次读取位置存储在另一个文件中,并在下次读取日志文件时查找该位置。

0

如果文件中的行按日期排序(这对于仅追加日志来说是合理的),那么你可以按照相反的顺序读取文件(tac utility - 查找或实现Python版本,如果它不可用您的系统),并停止阅读,如果日期是过去太远

# .. 
if 'error' in line.lower(): 
    if getdate(line) < today: 
     break # stop processing 
0

您可以使用搜索功能,以达到文件的末尾,并通过搜索新行字符或以其他方式找出最后日期。一旦找到,你可以相应地进行。我写了下面的脚本来找出每个文件的最后日期。这个函数第一个 这个函数找出给定日志文件中最后一个条目的日期。要发现它从文件的末尾开始并继续前进2个字符并检查下一个字符是否为新行字符。当有新的一行字符时,它读取前10个字符。但是,如果日志中存在其他服务的例外,则行首可能不包含日期标记。因此,我们使用除了循环以外的try循环,以防止最后一行不包含日期戳。

list= glob.glob("DebugLogFile.log*") 

start_time = time.time() 


def end_date(file): 
count=0; 
with open(file, "rb") as f: 
    first = f.readline() 
    # Read the first line. 
    `enter code here`f.seek(-2, os.SEEK_END) 
    #print f.tell() # Jump to the second last byte. 
    #print f.read(1) 
    flag=True; 
    while (flag) : 
     try : 
      #print f.tell() 
      f.seek(-2, os.SEEK_CUR) 
      while f.read(1) != b"\n": # Until EOL is found... 
       try: 
        f.seek(-2, os.SEEK_CUR) 
        #print f.tell()    
       except: 
        f.seek(0,os.SEEK_SET) 
        print "test" 
        break 

      #Remembering the current pointer in case we have to re-evaluate the date in case of exception 
      last_pos = f.tell() 
      last = f.readline() 
      date=last[:10] 
      datetime.datetime.strptime(date, '%Y-%m-%d').date() 
      flag=False 
      return datetime.datetime.strptime(date, '%Y-%m-%d').date() 

     except Exception, err_msg: 

      f.seek(last_pos) 





def threshold(file): 
base_date=end_date(file) 
print("Base date is ", base_date) 
print("Computing the threshold.......") 
#convert the string to date object 
#base_date_ob=datetime.datetime.strptime(base_date, '%Y-%m-%d').date() 
threshold=base_date-timedelta(days=14) 
return threshold 

if __name__ == "__main__": 
thresh=threshold("DebugLogFile.log") 
print thresh 

#list =['DebugLogFile.log.100'] 
#print list 
for file in list : 
    tmp=end_date(file) 
    if(tmp>=thresh): 

     print ("Process file :", file, "Which has end date as ", tmp) 
    else: 
     print ("Do Not Process file :", file, "Which has end date as ", tmp) 
time=time.time() 
相关问题