【问题标题】:Flask: how to serve an updating log file line by line? [duplicate]Flask:如何逐行提供更新的日志文件? [复制]
【发布时间】:2018-06-11 19:33:16
【问题描述】:

我的Python程序中有两个线程,一个是flask,一个是后台任务,运行时会动态生成一些日志字符串到日志文件中。

我尝试使用yield 像这样流式传输文件:

@app.route('/task_status')
def get_background_task_log():
    def read_task_log():

        # Try load log files
        log_file = open("/tmp/task_log.log", "r")

        # Stream file to the client
        while True:
            new_line = log_file.readline()

            # Stream the file to the client until it ends.
            if "Foo: process finished!" in new_line:
                yield new_line.encode("utf-8")  # Flush the last line
                break

            yield new_line.encode("utf-8")

    return Response(read_task_log(), mimetype="text/plain",
                    headers={"Content-Disposition": "inline; filename=task_log.log"})

但是当 Chrome 加载 /task_status 时,它只是挂在那里等到 Foo: process finished 出现,而​​不是逐行显示内容。我还尝试删除 Content-Disposition 标头,它保持不变。

同时我也尝试过使用send_file(),但是当我从 Chrome 访问它时它只能返回部分日志文件。

那我该怎么办?

【问题讨论】:

    标签: python python-3.x web flask


    【解决方案1】:

    查看 github 上的 pygtail。

    Pygtail 读取尚未读取的日志文件行。它甚至会 处理已轮换的日志文件。

    从他们的例子中:

    from pygtail import Pygtail
    
    for line in Pygtail("some.log"):
        sys.stdout.write(line)
    

    【讨论】:

      猜你喜欢
      • 2017-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-23
      • 2018-05-14
      • 2014-04-30
      • 1970-01-01
      相关资源
      最近更新 更多