以相反的顺序处理这些行

时间:2016-06-05 08:11:52

标签: python nginx logfile logfile-analysis

如何以相反的顺序处理日志文件(在我的情况下是nginx access.log)?

背景 我正在开发一个日志文件分析器脚本,我只是无法了解如何从最终处理大型日志文件,所以我可以从我需要的最新日期开始整理时间框架。

1 个答案:

答案 0 :(得分:0)

一种方法是使用seek访问文件末尾,然后从那里反向扫描文件。例如:

def Tail(filepath, nol=10, read_size=1024):
  """
  This function returns the last line of a file.
  Args:
    filepath: path to file
    nol: number of lines to print
    read_size:  data is read in chunks of this size (optional, default=1024)
  Raises:
    IOError if file cannot be processed.
  """
  f = open(filepath, 'rU')    # U is to open it with Universal newline support
  offset = read_size
  f.seek(0, 2)
  file_size = f.tell()
  while 1:
    if file_size < offset:
      offset = file_size
    f.seek(-1*offset, 2)
    read_str = f.read(offset)
    # Remove newline at the end
    if read_str[offset - 1] == '\n':
      read_str = read_str[:-1]
    lines = read_str.split('\n')
    if len(lines) >= nol:  # Got nol lines
      return "\n".join(lines[-nol:])
    if offset == file_size:   # Reached the beginning
      return read_str
    offset += read_size
  f.close()

然后用作

Tail('/etc/httpd/logs/access.log', 100)

这将为您提供access.log文件的最后100行。

引用的代码: http://www.manugarg.com/2007/04/real-tailing-in-python.html