显示日志文件更新时的内容 [英] Display the contents of a log file as it is updated

查看:177
本文介绍了显示日志文件更新时的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有外部程序,如ffmpeg和gstreamer在后台运行并写入日志文件。我想用我的Flask应用程序显示这个日志的内容,以便用户可以看到日志更新,如终端中的 tail -f job.log

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.

我尝试使用< object data =/ out.logtype =text / plain> 指向日志文件,但没有显示数据,或浏览器告诉我,我需要一个插件。

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.

如何嵌入和更新日志文件在HTML页面?

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

推荐答案

使用Flask视图从文件中不断读取并传输响应。使用JavaScript从流中读取并更新页面。这个例子发送整个文件,你可能想截断某些点来节省带宽和内存。这个例子在读取之间休眠,以减少无限循环的CPU负载,并允许其他线程更多的活动时间。

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



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

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

    setInterval(function() {
        output.textContent = xhr.responseText;
    }, 1000);
</script>

这几乎与这个答案,它描述了如何流式传输和解析消息,虽然从外部文件永远读取是足够新颖的,是自己的答案。这里的代码更简单,因为我们不关心解析消息或结束流,只是永远拖尾文件。

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.

这篇关于显示日志文件更新时的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆