0

There are two threads in my Python program, one is for flask, and the other one is for the background task and it will dynamically generate some logs strings into a log file when it is running.

I've tried streaming the file with yield like this:

@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"})

But when Chrome loads /task_status, it just hangs there and wait until the line Foo: process finished come out, instead of show me the content line by line. I've also tried removing the Content-Disposition header and it stays the same.

Meanwhile I've also tried using send_file() but it can only returns a partial log file when I access it from Chrome.

What should I do then?

Jackson Ming Hu
  • 1,681
  • 2
  • 14
  • 23

1 Answers1

2

Check out pygtail on github.

Pygtail reads log file lines that have not been read. It will even handle log files that have been rotated.

From their example:

from pygtail import Pygtail

for line in Pygtail("some.log"):
    sys.stdout.write(line)
abybaddi009
  • 1,014
  • 9
  • 22