Display the contents of a log file as it is updated


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 application, so that the user can watch the log update, like tail -f job.log would do in the terminal.

I tried to use <object data="/out.log" type="text/plain"> to point at the log file, but that failed to show the data, or the browser told me I needed a plugin.

How can I embed and update the log file in an HTML page?


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__)

def index():
    return render_template('index.html')

def stream():
    def generate():
        with open('job.log') as f:
            while True:
                yield f.read()

    return app.response_class(generate(), mimetype='text/plain')

<pre id="output"></pre>
    var output = document.getElementById('output');

    var xhr = new XMLHttpRequest();
    xhr.open('GET', '{{ url_for('stream') }}');

    setInterval(function() {
        output.textContent = xhr.responseText;
    }, 1000);

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.

Answered By – davidism

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published