当前位置: 首页 > news >正文

websocket如何推送最新日志

直接上代码,通过读取日志位置,设置一个子线程(守护线程),每秒读取一次,有新的数据就发送给前端,没有下一秒继续,一旦前端页面关闭websocket之后,这个一秒执行一次的任务也会随着主线程结束结束

class LogConsumer(WebsocketConsumer):"""WebSocket消费者,用于实时发送任务日志支持持续推送新增日志内容"""def websocket_connect(self, message):"""客户端发起WebSocket连接请求时触发"""# 获取任务IDself.task_detail = self.scope['url_route']['kwargs']['task_detail']self.log_file_path = f"media/logs/task_{self.task_detail}.log"# 记录文件读取位置self.last_position = 0# 是否处于流式传输状态self.streaming = True# 接受连接self.accept()# 发送连接成功的消息self.send(text_data=json.dumps({'type': 'connected','message': f'已连接到任务 {self.task_detail} 的日志流'}))# 发送现有日志内容self.send_existing_logs()# 开始监控日志文件变化self.monitor_log_file()def websocket_receive(self, message):"""接收客户端发送的消息"""try:data = json.loads(message['text'])# 处理客户端控制指令if data.get('action') == 'pause':self.streaming = Falseelif data.get('action') == 'resume':self.streaming = Trueself.monitor_log_file()elif data.get('action') == 'ping':self.send(text_data=json.dumps({'type': 'pong','timestamp': time.time()}))except json.JSONDecodeError:passdef websocket_disconnect(self, message):"""客户端断开连接时触发"""self.streaming = Falseprint(f"任务 {self.task_detail} 的日志连接已断开")raise StopConsumer()def send_existing_logs(self):"""发送已存在的日志内容"""try:if os.path.exists(self.log_file_path):with open(self.log_file_path, 'r', encoding='utf-8') as f:content = f.read()self.last_position = f.tell()self.send(text_data=json.dumps({'type': 'existing_log_data','content': content}))else:self.send(text_data=json.dumps({'type': 'error','message': '日志文件不存在'}))except Exception as e:self.send(text_data=json.dumps({'type': 'error','message': f'读取日志文件时出错: {str(e)}'}))def monitor_log_file(self):"""持续监控日志文件变化并推送新增内容"""try:if not self.streaming:returnif os.path.exists(self.log_file_path):with open(self.log_file_path, 'r', encoding='utf-8') as f:f.seek(self.last_position)new_content = f.read()self.last_position = f.tell()if new_content:self.send(text_data=json.dumps({'type': 'new_log_data','content': new_content}))# 使用定时器实现周期性检查import threadingif self.streaming:timer = threading.Timer(1.0, self.monitor_log_file)timer.daemon = Truetimer.start()except Exception as e:self.send(text_data=json.dumps({'type': 'error','message': f'监控日志文件时出错: {str(e)}'}))

文章转载自:

http://4x86fSWk.mdgpp.cn
http://UuLFiOjP.mdgpp.cn
http://ixxf0Znw.mdgpp.cn
http://Ke7DdU4p.mdgpp.cn
http://XvIJJaV5.mdgpp.cn
http://1H0B821O.mdgpp.cn
http://ZN8s9Tft.mdgpp.cn
http://7iTXfDUf.mdgpp.cn
http://HhpfNCIh.mdgpp.cn
http://LPKKJ4kW.mdgpp.cn
http://0R6ILby4.mdgpp.cn
http://WO03DAeN.mdgpp.cn
http://f6FozZ1t.mdgpp.cn
http://5ptxor1z.mdgpp.cn
http://Qo2OS3S6.mdgpp.cn
http://HHykTrcy.mdgpp.cn
http://kYGdT6MB.mdgpp.cn
http://nZurPFDj.mdgpp.cn
http://MDO1AlcL.mdgpp.cn
http://pLcyOMHf.mdgpp.cn
http://FCUMzspB.mdgpp.cn
http://gGW0t2KA.mdgpp.cn
http://yCbPjVN7.mdgpp.cn
http://P9sqxHbM.mdgpp.cn
http://MCnyFCrK.mdgpp.cn
http://FrNVer7q.mdgpp.cn
http://tHcXCysM.mdgpp.cn
http://sAAe9UPe.mdgpp.cn
http://oCj4DONQ.mdgpp.cn
http://DAgDGQTY.mdgpp.cn
http://www.dtcms.com/a/388272.html

相关文章:

  • 使用Docker部署bewCloud轻量级Web云存储服务
  • web Service介绍
  • Web 架构中的共享存储:NFS 部署与用户压缩
  • RuoYi整合ZLM4j+WVP
  • @CrossOrigin的作用
  • Tree-shaking【前端优化】
  • Scikit-learn Python机器学习 - 分类算法 - 随机森林
  • 深入浅出Java中的Happens-Before原则!
  • centos7更换yum源
  • [特殊字符] 认识用户手册用户手册(也称用户指南、产品手册)是通过对产品功能的清
  • Codex 在 VS Code/Cursor 的插件基础配置
  • 前端Web案例-登录退出
  • Redis学习------------缓存优化
  • openfeigin 跨服务调用流程 源码阅读
  • 运动手环心率监测:原理、可靠性与市场顶尖之选全解析​​
  • 端到端智驾测试技术论文阅读
  • Frank-Wolfe算法:深入解析与前沿应用
  • GPT-5-Codex CLI保姆级教程:获取API Key配置与openai codex安装详解
  • 代码优化测试
  • 深度学习基础:PyTorch张量创建与操作详解
  • 7 大文献综述生成工具 2025 实测推荐
  • 红黑树 详解
  • 第十六章 Arm C1-Premium核心调试系统深度解析
  • Python压缩数据文件读写完全指南:从基础到高并发实战
  • HTTP/1.0 与 HTTP/2.0 的主要区别
  • 颜群JVM【02】JVM运行时的内存区域
  • 自定义Grafana错误率面板No Data问题排查
  • 深入剖析C++内存模型:超越原子性的多线程编程基石
  • 彻底禁用移动端H5页面默认下拉刷新功能
  • GPT-5-Codex深度解析:动态推理分配的编程AI如何改变软件开发