【问题标题】:How do I get Information from log file's last modified using Python?如何从使用 Python 上次修改的日志文件中获取信息?
【发布时间】:2013-02-04 14:41:16
【问题描述】:

我是 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

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

【问题讨论】:

  • 您记录的错误是否有时间戳?
  • 您确定要上次修改时间吗?那不是总是只给你记录到文件中的最后一条消息吗?
  • 仅供参考,python 中有一个日志记录模块。如果您不知道它的存在,值得一试

标签: python information-retrieval last-modified


【解决方案1】:

简短的回答,不。更长的答案是,您要么必须进行大量浪费的解析,要么在文件外部跟踪一些数据。您可以遍历整个文件,解析日志消息的时间戳,然后仅在给定时间后打印。尽管对于具有 3 年数据的文件,您最好跟踪脚本读取的最后一行,然后在每次打开文件以每天解析时查找该行。如果您可以访问流程中的相关部分,另一种选择是修改日志记录机制;您可以将消息复制到每次脚本运行时刷新的第二个文件,或者基本上通过第二个文件缓冲日志记录,并让脚本负责将日志存档到历史文件。

【讨论】:

  • 同意,拥有一个每日记录器,使用您的脚本检查消息,并在您完成所需的日志消息后将消息重新记录到历史文件中。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    如果您提供更多信息,例如日志文件的格式,就可以了。

    查看方法datetime.datetime.strptime。在那里你会找到你需要的一切。

    例如

    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()-方法。这在 Python 3 中作为生成器实现,但在 Python 2.x 中没有。如果你使用 2.x,我肯定会使用来自 itertools-module 的 ifilter

    【讨论】:

      【解决方案4】:

      如果文件中的行按日期排序(仅附加日志是合理的),那么您可以以相反的顺序读取文件(tac utility - 如果 Python 版本不可用,则查找或实现在您的系统上)并在日期过早时停止阅读:

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

      【讨论】:

        【解决方案5】:

        您可以使用搜索功能到达文件末尾并通过搜索换行符或其他方式找出最后日期。找到后,您可以进行相应的操作。我写了下面的脚本来找出每个文件的最后日期。这个功能先 此函数查找给定日志文件中最后一个条目的日期。发现它从文件末尾开始并继续返回 2 个字符并检查下一个字符是否是换行符。当有换行符时,读取前 10 个字符。但是,当日志中有其他服务的异常时,行首可能不包含日期戳。因此,如果最后一行不包含日期戳,我们使用 try except 循环进一步迭代。

        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()
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-03-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多