Display the contents of a log file as it is updated

前端 未结 2 999
借酒劲吻你
借酒劲吻你 2020-11-27 04:13

I have external programs such as ffmpeg and gstreamer running in the background and writing to a log file. I want to display the contents of this log with my Flask applicat

2条回答
  •  独厮守ぢ
    2020-11-27 05:17

    Use a Flask view to continuously read from the file forever and stream the response. Use JavaScript to read from the stream and update the page. This example sends the entire file, you may want to truncate that at some point to save bandwidth and memory. This example sleeps between reads to reduce cpu load from the endless loop and allow other threads more active time.

    from time import sleep
    from flask import Flask, render_template
    
    app = Flask(__name__)
    
    @app.route('/')
    def index():
        return render_template('index.html')
    
    @app.route('/stream')
    def stream():
        def generate():
            with open('job.log') as f:
                while True:
                    yield f.read()
                    sleep(1)
    
        return app.response_class(generate(), mimetype='text/plain')
    
    app.run()
    
    
    
    

    This is almost the same as this answer, which describes how to stream and parse messages, although reading from an external file forever was novel enough to be it's own answer. The code here is simpler because we don't care about parsing messages or ending the stream, just tailing the file forever.

提交回复
热议问题