如何在Python Dash Textarea中高亮指定内容的日志行?
实现Dash日志行高亮的解决方案
核心思路
dcc.Textarea组件不支持行内文本高亮样式,所以改用html.Pre结合html.Span来实现——通过遍历日志行,给包含指定关键词的行添加高亮CSS样式。
完整代码实现
from dash import Dash, html, dcc, callback, Output, Input, State import dash_bootstrap_components as dbc import logging from datetime import datetime # 配置logging生成日志(模拟业务日志生成逻辑) logging.basicConfig( filename='app.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s' ) log = logging.getLogger(__name__) # 生成测试日志(模拟实际业务输出) t1 = datetime.now() n = 15 t2 = datetime.now() log.info(f"Process started on {t1}") log.info(f"Total number of files {n}") log.info(f"Process completed on {t2}") log.info("User authentication succeeded") log.info("Total number of files 20") # 初始化Dash应用 app = Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP]) app.layout = html.Div([ dcc.Location(id="location"), dbc.Row([ dbc.Col(html.H1("日志展示"), width=12) ]), dbc.Row([ dbc.Col( # 用Pre组件替代Textarea,支持自定义行样式 html.Pre( id='highlighted-log-content', style={'width': '100%', 'height': '500px', 'whiteSpace': 'pre-wrap', 'overflowY': 'auto'} ), width=10 ), ]), # 存储高亮关键词,方便后续动态修改 dcc.Store(id='highlight-keywords', data=["Total number of files", "authentication succeeded"]) ]) @callback( Output('highlighted-log-content', 'children'), Input('location', 'pathname'), # 页面加载时触发日志加载 State('highlight-keywords', 'data') ) def load_and_highlight_log(pathname, highlight_keywords): # 读取日志文件 try: with open('app.log', 'r', encoding='utf-8') as f: log_lines = f.readlines() except FileNotFoundError: return html.Span("日志文件不存在", style={'color': 'red'}) highlighted_elements = [] # 逐行处理高亮 for line in log_lines: line = line.strip('\n') # 判断当前行是否包含高亮关键词 is_highlight = any(keyword in line for keyword in highlight_keywords) if is_highlight: # 高亮样式:黄色背景+加粗 highlighted_elements.append( html.Span(f"{line}\n", style={'backgroundColor': '#ffff99', 'fontWeight': 'bold'}) ) else: highlighted_elements.append(html.Span(f"{line}\n")) return highlighted_elements if __name__ == '__main__': app.run_server(debug=True)
关键说明
- 组件替换:用
html.Pre替代dcc.Textarea,Pre组件既保留原始日志的格式,又支持嵌套html.Span来实现行内样式定制。 - 高亮逻辑:遍历每一行日志,匹配预设的关键词列表,对符合条件的行添加背景色和字体加粗样式。
- 可扩展性:通过
dcc.Store存储关键词列表,后续可轻松添加输入组件,让用户动态修改需要高亮的内容,无需改动核心渲染逻辑。
内容的提问来源于stack exchange,提问作者Madhu
相关产品推荐
相关产品推荐

