我有外部程序,例如 ffmpeg 和 gstreamer 在后台运行并写入日志文件。我想用我的 Flask 应用程序显示此日志的内容,以便用户可以查看日志更新,例如 tail -f job.log
会在终端做。
我尝试使用 <object data="/out.log" type="text/plain">
指向日志文件,但未能显示数据,或者浏览器告诉我我需要一个插件。
如何在 HTML 页面中嵌入和更新日志文件?
最佳答案
使用 Flask View 从文件中持续读取并流式传输响应。使用 JavaScript 从流中读取并更新页面。此示例发送整个文件,您可能希望在某个时候 chop 该文件以节省带宽和内存。此示例在读取之间休眠以减少无限循环的 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>
这与this answer 几乎相同,它描述了如何流式传输和解析消息,尽管永远从外部文件中读取足够新颖,足以成为它自己的答案。这里的代码更简单,因为我们不关心解析消息或结束流,只关心永远拖尾文件。
关于javascript - 在更新时显示日志文件的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35540885/