如何从日志文件';最后一次使用Python修改是什么?

如何从日志文件';最后一次使用Python修改是什么?,python,information-retrieval,last-modified,Python,Information Retrieval,Last Modified,我是Python新手,我正在尝试创建一个脚本来遍历我所有的日常日志文件以检查错误 我可以打开文件,打印上次修改日志文件的时间,并打印日志文件中的任何错误 然而,这些日志中有过去三年的每日信息。我只希望能够从日志的最后修改日期读取日志的部分(而不是获取过去三年中的所有错误,我只希望获取最后一天的错误) 以下是迄今为止我的脚本的内容: import sys, string, os, time from stat import * from datetime import datetime no

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

有没有办法做到这一点?我到处寻找,没有找到我问题的答案。请提供帮助。

如果您能提供更多信息,例如日志文件的格式,那就太好了

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

例如


我使用
filter()
-方法。这在Python3中是作为生成器实现的,但在Python2.x中不是。如果您使用2.x,我肯定会使用
itertools
-模块中的
ifilter

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

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

如果文件中的行按日期排序(仅附加日志比较合理),则可以按相反顺序读取文件(-如果系统上没有Python版本,请查找或实现该版本),如果日期太远,请停止阅读:

# ..
if 'error' in line.lower():
   if getdate(line) < today:
      break # stop processing
#。。
如果.lower()行中出现“error”:
如果getdate(行)<今天:
中断#停止处理

您可以使用seek函数到达文件末尾,并通过搜索新行字符或其他方式找到最后日期。一旦找到,您可以相应地继续。我已经编写了下面的脚本,以从每个文件中找到最后日期。此函数首先 此函数用于查找给定日志文件中最后一个条目的日期。若要查找该条目的起始日期,请返回2个字符,并检查下一个字符是否为新行字符。当存在新行字符时,它将读取前10个字符。但是,当日志中存在其他服务的异常时,lin的开头e可能不包含日期戳。因此,如果最后一行不包含日期戳,我们将使用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()

你记录的错误有时间戳吗?你确定你想要上次修改的时间吗?这不总是只会给你记录到文件中的最后一条消息吗?仅供参考,python中有一个日志模块。如果你不知道它存在,那么值得检查一下。ree,有一个每日日志,用脚本检查消息,然后将消息重新记录到historical文件,一旦您完成了日志消息所需的操作。
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()