修剪大日志文件

时间:2012-03-11 08:25:18

标签: python performance bash sed logging

我为一些java应用程序执行性能测试。应用程序在测试期间会生成非常大的日志文件(可能是7-10 GB)。我需要在特定日期和时间之间修剪这些日志文件。目前,我使用python脚本,它解析datetime python对象中的日志时间戳并仅打印匹配的字符串。但这个解决方案非常缓慢。解析5 GB日志大约25分钟 显然日志文件中的条目是顺序的,我不需要逐行读取所有文件。 我考虑从开始和结束读取文件,直到条件匹配并在匹配的行数之间打印文件。但我不知道如何从后面读取文件,而不将其下载到内存中。

请你能否为我提出任何适用于此案的解决方案。

这是python脚本的一部分:

      lfmt = '%Y-%m-%d %H:%M:%S'
      file = open(filename, 'rU')
      normal_line = ''
      for line in file:
        if line[0] == '[':
          ltimestamp = datetime.strptime(line[1:20], lfmt)

          if ltimestamp >= str and ltimestamp <= end:
            normal_line = 'True'
        else:
          normal_line = ''

      if normal_line:
        print line,

4 个答案:

答案 0 :(得分:5)

如果感兴趣区域的起点和终点接近文件的开头,数据是顺序的,那么从文件末尾读取(找到匹配的终点)仍然是一个糟糕的解决方案!

我已经编写了一些代码,可以根据需要快速找到起点和终点,这种方法称为binary search,类似于clasic儿童的“更高或更低”的猜谜游戏!

该脚本在lower_boundsupper_bounds之间(最初是SOF和EOF)中间读取试用行,并检查匹配条件。如果所寻找的行更早,则通过读取lower_bound和先前读取试验之间的中间线来再次猜测(如果它更高,则它在其猜测和上限之间分开)。因此,您继续在上限和下限之间进行迭代 - 这会产生尽可能快的“平均”解决方案。

这应该是一个真正的快速解决方案(登录到行数的基数2 !!)。例如,在最糟糕的情况下(在1000行中找到999行),使用二进制搜索只需要9行读取! (从十亿行只需30 ...)

以下代码的假设:

  • 每一行都以时间信息开头。
  • 时间是唯一的 - 如果没有,当找到匹配时,您将必须向后或向前检查以包含或排除所有具有匹配时间的条目(如果需要)。
  • 有趣的是这是一个递归函数,因此文件的行数限制为2 ** 1000(幸运的是,这允许相当大的文件...)

此外:

  • 如果愿意,这可以适用于以任意块读取,而不是按行读取。正如J.F. Sebastian所建议的那样。
  • 在我原来的回答中我提出了这种方法,但使用linecache.getline,虽然这可能不适合大文件,因为它将整个文件读入内存(因此file.seek()更优越),这要归功于TerryE和JF塞巴斯蒂安指出了这一点。

导入日期时间

def match(line):
    lfmt = '%Y-%m-%d %H:%M:%S'
    if line[0] == '[':
        return datetime.datetime.strptime(line[1:20], lfmt)

def retrieve_test_line(position):
    file.seek(position,0)
    file.readline()  # avoids reading partial line, which will mess up match attempt
    new_position = file.tell() # gets start of line position
    return file.readline(), new_position

def check_lower_bound(position):
    file.seek(position,0)
    new_position = file.tell() # gets start of line position
    return file.readline(), new_position

def find_line(target, lower_bound, upper_bound):
    trial = int((lower_bound + upper_bound) /2)
    inspection_text, position = retrieve_test_line(trial)
    if position == upper_bound:
        text, position = check_lower_bound(lower_bound)
        if match(text) == target:
            return position
        return # no match for target within range
    matched_position = match(inspection_text)
    if matched_position == target:
        return position
    elif matched_position < target:
        return find_line(target, position, upper_bound)
    elif matched_position > target:
        return find_line(target, lower_bound, position)
    else:
        return # no match for target within range

lfmt = '%Y-%m-%d %H:%M:%S'
# start_target =  # first line you are trying to find:
start_target =  datetime.datetime.strptime("2012-02-01 13:10:00", lfmt)
# end_target =  # last line you are trying to find:
end_target =  datetime.datetime.strptime("2012-02-01 13:39:00", lfmt)
file = open("log_file.txt","r")
lower_bound = 0
file.seek(0,2) # find upper bound
upper_bound = file.tell()

sequence_start = find_line(start_target, lower_bound, upper_bound)

if sequence_start or sequence_start == 0: #allow for starting at zero - corner case
    sequence_end = find_line(end_target, sequence_start, upper_bound)
    if not sequence_end:
        print "start_target match: ", sequence_start
        print "end match is not present in the current file"
else:
    print "start match is not present in the current file"

if (sequence_start or sequence_start == 0) and sequence_end:
    print "start_target match: ", sequence_start
    print "end_target match: ", sequence_end
    print
    print start_target, 'target'
    file.seek(sequence_start,0)
    print file.readline()
    print end_target, 'target'
    file.seek(sequence_end,0)
    print file.readline()

答案 1 :(得分:2)

  

5 GB日志解析约25分钟

大约是3MB / s。甚至在Python can do much better (~500MB/s for wc-l.py)中进行顺序O(n)扫描,即性能应仅受I / O限制。

要对文件执行二进制搜索,您可以调整使用固定记录的FileSearcher代替使用行,使用类似于 tail -n implementation in Python(扫描O(n)'\n'

要避免O(n)(如果日期范围仅选择日志的一小部分),您可以使用使用大型固定块的近似搜索,并允许一些记录由于它们位于块边界而被遗漏例如,使用未经修改的FileSearcherrecord_size=1MB和自定义Query类:

class Query(object):

    def __init__(self, query):
        self.query = query # e.g., '2012-01-01'

    def __lt__(self, chunk):
        # assume line starts with a date; find the start of line
        i = chunk.find('\n')
        # assert '\n' in chunk and len(chunk) > (len(self.query) + i)
        # e.g., '2012-01-01' < '2012-03-01'
        return self.query < chunk[i+1:i+1+len(self.query)]

考虑到日期范围可以跨越多个块,您可以修改FileSearcher.__getitem__以返回(filepos, chunk)并搜索两次(bisect_left()bisect_right())以查找近似{ {1}},filepos_mindate。之后,您可以围绕给定的文件位置执行线性搜索(例如,使用filepos_maxdate方法),以查找确切的第一个和最后一个日志记录。

答案 2 :(得分:1)

7到10 GB是大量数据。如果我必须分析这种数据,我会将应用程序登录到数据库或将日志文件上载到数据库。然后,您可以在数据库上高效地进行大量分析。如果您使用像Log4J这样的标准日志记录工具,那么日志记录到数据库应该非常简单。只是建议一个替代解决方案。

有关数据库日志记录的更多信息,请参阅以下文章:

A good database log appender for Java?

答案 3 :(得分:0)

如果您可以访问Windows环境,则可以使用MS LogParser来读取文件并收集可能需要的任何信息。它使用SQL语法,这使得使用此工具成为一种乐趣。它还支持大量输入类型。

作为额外的奖励,它还支持iCheckPoint开关,该开关在处理顺序日志文件时会导致创建检查点文件。有关详细信息,请查看“高级功能 - &gt;增量分析输入”下的“日志分析帮助”

另见:

相关问题