在日志文件更新时显示日志文件的内容

Display the contents of a log file as it is updated

本文关键字:日志 文件 更新 显示      更新时间:2023-09-26

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

我试图使用<object data="/out.log" type="text/plain">指向日志文件,但未能显示数据,或者浏览器告诉我需要一个插件。

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

使用 Flask 视图永久连续读取文件并流式传输响应。 使用 JavaScript 从流中读取并更新页面。 此示例发送整个文件,您可能希望在某个时候截断该文件以节省带宽和内存。 此示例在读取之间休眠,以减少无限循环的 CPU 负载,并允许其他线程有更多的活动时间。

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>

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

我正在使用 npm frontail包。

npm i frontail -g
frontail /var/log/syslog

访问 http://127.0.0.1:9001 以查看日志

资料来源:https://github.com/mthenw/frontail

这可能不是问题的确切答案(嵌入html页面),但它解决了许多专门寻找的用户的问题

在日志文件更新时显示其内容

对我来说

@davidism解决方案(接受的答案)仅适用于Firefox。它在Chrome,Brave,Vivaldi中不起作用。也许后端和前端循环中有某种不同步?我不知道。

无论如何,我使用了更简单的解决方案,后端没有循环,前端没有javascript循环。也许它"更丑陋",可能会给一些很长的日志带来麻烦,但至少它适用于我使用的每个浏览器。

@app.route('/stream')
def stream():
    with open("job.log", "r") as f:
            content = f.read()
    # as you see, file is loaded only once, no loop here, (loop is on frontend side)
    return app.response_class(content, mimetype='text/plain')
<!DOCTYPE html>
<html>
    <head>
        <!-- page auto-refresh every 10 seconds -->
        <meta http-equiv="refresh" content="10">
        <title>Some title</title>
    </head>
    <body>
        <h1>Log file ...</h1>
        <script>
           // function for adjusting iframe height to log size
            function resizeIframe(obj) {
              obj.style.height = obj.contentWindow.document.documentElement.scrollHeight + 'px';
            }
          </script>
        <!-- iframe pulls whole file -->
        <iframe src="{{ url_for('stream') }}" frameborder="0" style="overflow:hidden;width:100%" width="100%" frameborder="0" scrolling="no" onload="resizeIframe(this)"></iframe>
    </body>
</html>

如您所见,唯一的javascript代码用于将iframe高度调整为当前文本大小。