阅读日志文件并查找具体细节

时间:2016-04-26 10:43:38

标签: python-2.7 logfile

我有一个.txt格式的日志文件

现在我必须使用python找到特定时间帧之间的日志条目。

我尝试使用迭代和范围。

所以请接受任何建议。

日志文件如下所示:

  

2015-12-15 00:51:01,904 INFO restserver.py 113   v ........................等等

所以只在特定的时间范围内找到日志条目。

2 个答案:

答案 0 :(得分:0)

如果您将整个日志文件读成字符串,那么您可以使用:

import re
str = '2015-12-15 00:51:01,904 INFO restserver.py 113 .... 2015-12-16 00:51:01,904 INFO restserver.py 114 ....'
date1="2015-12-15 00:51:01"
date2="2015-12-16 00:51:01"
result = re.search(date1+'(.*)'+date2, str)
print result.group(1)
  

输出:,904 INFO restserver.py 113 ....

用例的编辑代码(通过OP):

 #!/usr/bin/env python
 #Import the regular expression
 import re
 #Set the begining time and name it as starttime
 starttime="03:00:00"
 #Set the ending time and name it as endtime
 endtime="03:59:59"
 #Specify the time format
 time_re = re.compile(r'(\d+:\d+:\d+)')
 #Using the condition with open("abc.log", "r") as fh:
 for line in fh.readlines():
    match = time_re.search(line)
    if match:
        matchDate = match.group(1)
        if matchDate >= starttime and matchDate <= endtime:
            print match.string.strip() 

答案 1 :(得分:0)

!/ usr / bin / env python

导入正则表达式

导入重新

打印“任务开始”

print“开始时间是03:00:00”

设置开始时间并将其命名为starttime

开始时间= “3时00分00秒”

打印“结束时间是03:59:59”

设置结束时间并将其命名为endtime

结束时间= “3点59分59秒”

指定时间格式

time_re = re.compile(r'(\ d +:\\ + +:\ d +)')

使用条件

以open(“abc.log”,“r”)为fh:

    for line in fh.readlines():
        match = time_re.search(line)
        if match:
           matchDate = match.group(1)
           if matchDate >= starttime and matchDate <= endtime:
               print match.string.strip()

打印“任务已完成”