python - 以相反的顺序处理行

标签 python nginx logfile logfile-analysis

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

背景 我正在开发一个日志文件分析器脚本,但我无法理解如何从头开始处理巨大的日志文件,因此我可以从我需要的最新日期开始整理时间范围。

最佳答案

一种方法是使用 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

关于python - 以相反的顺序处理行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37639789/

相关文章:

Python:使用 shutil.move 或 os.rename 移动文件夹

python - OpenCV imread 透明度消失了

javascript - Nginx 不传递自定义 header 来访问后端(Node js)

java - 在 Eclipse 中,如何使用 "Workspace..."语法指定文件(例如 ${workspace_loc :/myworkspace} ) (for a console log)?

linux - 从用户代理字符串确定哪个浏览器发出请求

python - 如何将日志文件中的特定列提取到csv文件

python - 使用 glob 查找任意长度的数字

python - 在 Tensorflow 1.2 中恢复经过训练的模型

php - 调试 php 7 Xdebug 2.4.0RC3 mac os 时出现 502 Bad Gateway

django - 使用 Nginx 和 fastcgi 部署的 Django 为空 'current url'