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

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

问题描述

我有外部程序,例如 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.log" type="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 answer 几乎相同,后者描述了如何流式传输和解析消息,尽管是从外部读取文件永远是新颖的,足以成为它自己的答案.这里的代码更简单,因为我们不关心解析消息或结束流,只是永远拖尾文件.

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天全站免登陆