如何使用Flask读取日志文件内容并以结构化表格形式在网页端展示
Flask USB状态上报日志结构化表格展示改造
改造思路
- 保留原有POST上报接口、日志文件写入逻辑不动,仅替换首页路由的日志读取与渲染逻辑
- 通过正则规则匹配固定格式的日志行,提取主机名、客户端IP、连接状态三个结构化字段
- 将拼接div的无序展示替换为语义化HTML表格,搭配基础样式实现清晰的列布局
关键实现细节
- 日志匹配规则完全对齐现有日志格式:
「[客户端主机名] Connected/Disconnected USB from IP: [客户端IP]」,正则分别捕获三个字段值,匹配失败的行直接过滤,避免脏数据导致渲染异常 - 表格固定三列表头:CLIENT(客户端主机名)、IP(客户端地址)、STATUS(连接状态)
- 为不同状态配置色彩区分:USB接入(Connected)用绿色字体标注,拔出(Disconnected)用红色字体标注,提升可读性
参考实现代码
from flask import Flask, request, Response import re app = Flask(__name__) # 日志匹配正则:三个捕获组依次为 主机名、连接状态、客户端IP LOG_PATTERN = re.compile(r'^\[(\S+)\] (Connected|Disconnected) USB from IP: (\d{1,3}(?:\.\d{1,3}){3})$') LOG_FILE_PATH = "logs.log" # 原有POST上报接口保持不变 @app.route('/report', methods=['POST']) def receive_usb_event(): event_info = request.json # 按固定格式追加写入日志 log_content = f"[{event_info['hostname']}] {event_info['status']} USB from IP: {event_info['client_ip']}\n" with open(LOG_FILE_PATH, 'a', encoding='utf-8') as f: f.write(log_content) return {"code": 0, "msg": "上报成功"} # 改造后的首页展示路由 @app.route('/') def render_event_table(): event_list = [] # 逐行读取日志并做结构化解析 try: with open(LOG_FILE_PATH, 'r', encoding='utf-8') as f: for line in f: clean_line = line.strip() if not clean_line: continue match_result = LOG_PATTERN.match(clean_line) if match_result: client_host, conn_status, client_ip = match_result.groups() event_list.append({ "client": client_host, "ip": client_ip, "status": conn_status }) except FileNotFoundError: # 日志文件未生成时返回空表格 event_list = [] # 生成带基础样式的表格HTML page_template = """ <style> .usb-event-table { width: 70%; margin: 3rem auto; border-collapse: collapse; font-family: sans-serif; } .usb-event-table th, .usb-event-table td { border: 1px solid #e2e8f0; padding: 0.8rem 1.2rem; text-align: left; } .usb-event-table th { background: #f1f5f9; font-weight: 600; } .tag-connect { color: #16a34a; } .tag-disconnect { color: #dc2626; } </style> <table class="usb-event-table"> <thead> <tr> <th>CLIENT</th> <th>IP</th> <th>STATUS</th> </tr> </thead> <tbody> """ # 逐行填充事件数据 for event in event_list: status_class = "tag-connect" if event["status"] == "Connected" else "tag-disconnect" page_template += f""" <tr> <td>{event['client']}</td> <td>{event['ip']}</td> <td class="{status_class}">{event['status']}</td> </tr> """ page_template += "</tbody></table>" return Response(page_template, mimetype="text/html") if __name__ == '__main__': app.run(host="0.0.0.0", port=5000)
注意事项
- 不需要修改原有客户端采集、上报的代码逻辑,完全兼容现有日志格式
- 解析逻辑会自动跳过格式不匹配的日志行,不会因为异常内容导致页面报错
- 表格样式全部内联实现,无外部资源依赖
内容的提问来源于stack exchange,提问作者nifty khan
相关产品推荐
相关产品推荐

