
这个问题的目标是:
目标是开发一个监视远程服务器上日志文件的系统,类似于 unix 命令 tail -f。日志文件不断添加新数据。该系统应包括:
一个服务器应用程序,用于跟踪同一服务器上指定日志文件的持续更改。该应用程序应该能够将新添加的数据实时传输给客户端。
基于 web 的客户端界面,可通过 url(例如 http://localhost/log)访问,旨在动态显示日志文件更新,而不需要用户重新加载页面。最初,在访问该页面时,用户应该会看到日志文件中的最新 10 行。
还处理了以下场景:
服务器必须主动向客户端推送更新,以确保最小延迟,实现尽可能接近实时的更新。
鉴于日志文件可能非常大(可能有几 gb),您需要制定一种策略来有效获取最后 10 行而不处理整个文件。
服务器应该仅将文件的新添加内容传输给客户端,而不是重新发送整个文件。
服务器支持来自多个客户端的并发连接而不降低性能至关重要。
客户端的网页应该立即加载,在初始请求后不会停留在加载状态,并且不应该需要重新加载来显示新的更新。
我创建了一个 flask 应用程序,它具有简单的 ui,可显示最后 10 条消息。
我使用了flask-socketio来形成连接,还使用了处理文件的一些基本概念,如fileobj.seek()、fileobj.tell()等
from flask import flask, render_templatefrom flask_socketio import socketio, emitfrom threading import lockapp = flask(__name__)socketio = socketio(app)thread = nonethread_lock = lock()log_file_path = "./static/client.txt"last_position = 0position_lock = lock()@app.route('/')def index(): return render_template('index.html')@socketio.on('connect')def test_connect(): global thread with thread_lock: if thread is none: print("started execution in background!") thread = socketio.start_background_task(target=monitor_log_file)def monitor_log_file(): global last_position while true: try: with open(log_file_path, 'rb') as f: f.seek(0, 2) file_size = f.tell() if last_position != file_size: buffer_size = 1024 if file_size < buffer_size: buffer_size = file_size f.seek(-buffer_size, 2) lines = f.readlines() last_lines = lines[-10:] content = b'n'.join(last_lines).decode('utf-8') socketio.sleep(1) # add a small delay to prevent high cpu usage socketio.emit('log_updates', {'content': content}) print("emitted new lines to client!") last_position = file_size else: pass except filenotfounderror: print(f"error: {log_file_path} not found.") except exception as e: print(f"error while reading the file: {e}")if __name__ == '__main__': socketio.run(app, debug=true, log_output=true, use_reloader=false)
Basics User Updated Files Display it over here:
var socket = io("http://127.0.0.1:5000"); socket.on('connect', function() { console.log('Connected to the server'); }); socket.on('disconnect', function() { console.log('Client disconnected'); }); socket.on('log_updates', function(data) { console.log("data", data); var div = document.getElementById('output'); var lines = data.content.split('n'); div.innerHTML = ''; lines.forEach(function(line) { var p = document.createElement('p'); p.textContent = line; div.appendChild(p); }); });
还在 flask 应用程序的 static 文件夹下创建一个 client.log 文件。
如果我做错了什么,请随时纠正我。有任何更正请在下面评论!
以上就是开发一个监视位于远程服务器上的日志文件的系统,类似于 Unix 命令 tail -f的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1350086.html
微信扫一扫
支付宝扫一扫