From c6b6745e3e0d5de63110511a8d04437924fa648a Mon Sep 17 00:00:00 2001 From: Your Name Date: Wed, 7 Jan 2026 19:06:10 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E4=BC=98=E5=8C=96=E6=97=A5=E5=BF=97?= =?UTF-8?q?=E8=AE=B0=E5=BD=95=E6=A0=BC=E5=BC=8F=EF=BC=8C=E5=A2=9E=E5=BC=BA?= =?UTF-8?q?=E5=BE=AA=E7=8E=AF=E6=AC=A1=E6=95=B0=E5=92=8C=E8=BF=90=E8=A1=8C?= =?UTF-8?q?=E6=97=B6=E9=97=B4=E9=99=90=E5=88=B6=E7=9A=84=E5=8F=AF=E8=AF=BB?= =?UTF-8?q?=E6=80=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/image/完整技术文档/1767745492884.png | Bin 0 -> 8930 bytes douyin/core/douyin_main_flow.py | 10 +- douyin/logging/douyin_logging.py | 54 +++-- gui/gui_app.py | 231 ++++++++++++---------- gui/web_gui.py | 40 ++-- webui/app.js | 95 ++++++++- webui/index.html | 25 ++- webui/styles.css | 10 + 8 files changed, 316 insertions(+), 149 deletions(-) create mode 100644 docs/image/完整技术文档/1767745492884.png diff --git a/docs/image/完整技术文档/1767745492884.png b/docs/image/完整技术文档/1767745492884.png new file mode 100644 index 0000000000000000000000000000000000000000..c3b03e367f610ea7cbeb931fcf7f59169c5fdd99 GIT binary patch literal 8930 zcmbVy1yoz#@^0Ev_!TL|3lwN^DaEBwpg@2U+}+(BiWiCnEfBOtOVAREORyGqg1Z(A z?h@o5Zr@w?-nHI(>#cWIWRje-vuDnpZ}xmMU}Z%aJZuVV004j|`vIs50AS3a<@f(Q zM87IZ-Pohw9=NH>NC04iFSgJhFs#HC!~uZvIGk&f$LP;boImKe0RT_i?w=33oC?hW z09r3upt$-+!`*p>4|+OxSO-~&3E9m5RM(~DDSmG!ukcs~e&$dk(0@zIAgP>Y{4xrr zZ!Kr0rsk(phosFGo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- a/douyin/core/douyin_main_flow.py +++ b/douyin/core/douyin_main_flow.py @@ -75,10 +75,11 @@ class MainFlowController: if loop_count > max_loops: try: analyser._log_kv( # type: ignore[attr-defined] - "流程", "达到最大循环次数限制,停止运行", + "流程", + "达到最大循环次数限制,停止运行", loop_count=loop_count, max_loops=max_loops, - run_time_seconds=round(time.time() - start_time, 1) + run_time_seconds=round(time.time() - start_time, 1), ) except Exception: pass @@ -88,8 +89,9 @@ class MainFlowController: if time.time() - start_time > 24 * 3600: try: analyser._log_kv( # type: ignore[attr-defined] - "流程", "达到最大运行时间限制,停止运行", - run_time_hours=round((time.time() - start_time) / 3600, 1) + "流程", + "达到最大运行时间限制,停止运行", + run_time_hours=round((time.time() - start_time) / 3600, 1), ) except Exception: pass diff --git a/douyin/logging/douyin_logging.py b/douyin/logging/douyin_logging.py index 2295e84..54e567f 100644 --- a/douyin/logging/douyin_logging.py +++ b/douyin/logging/douyin_logging.py @@ -714,16 +714,37 @@ def configure_logging( per_run=per_run, ) - # 启动时清理旧日志:始终以基础 base 名(不含运行时间戳)作为匹配前缀 + # 启动时检查总日志大小:若超过警告阈值则同步清理一次(仅在启动执行) if keep_days is not None: - cleanup_old_logs( - log_dir or path_config.get_logs_dir(), - os.path.basename(base_filename_base), - keep_days=keep_days, - max_total_size_gb=max_total_size_gb, - compress_after_days=compress_after_days, - compress=compress_logs if compress_logs is not None else True, - ) + try: + # 计算当前日志总大小(MB) + pattern = os.path.join( + log_dir or path_config.get_logs_dir(), f"{os.path.basename(base_filename_base)}_*.log*" + ) + total_size = 0 + for p in glob.glob(pattern): + try: + if os.path.exists(p): + total_size += os.path.getsize(p) + except Exception: + pass + total_size_mb = total_size / 1024.0 / 1024.0 + except Exception: + total_size_mb = 0.0 + + try: + if total_size_mb >= float(monitor_warning_mb or 500.0): + # 同步清理一次(仅在启动阶段) + cleanup_old_logs( + log_dir or path_config.get_logs_dir(), + os.path.basename(base_filename_base), + keep_days=keep_days, + max_total_size_gb=max_total_size_gb, + compress_after_days=compress_after_days, + compress=compress_logs if compress_logs is not None else True, + ) + except Exception: + pass # 启动日志监控器 if enable_monitor: @@ -1023,6 +1044,7 @@ class LogRotationMonitor: check_interval: int = 300, # 检查间隔(秒) rotation_threshold: int = 10, # 轮转频率阈值(每天) alert_callback: Optional[Callable[[str, str], None]] = None, + enable_runtime_cleanup: bool = False, ): """ 参数: @@ -1049,6 +1071,8 @@ class LogRotationMonitor: # 清理状态,避免并发触发大量清理操作 self._cleanup_lock = threading.Lock() self._cleanup_running = False + # 是否允许在运行过程中触发自动清理(默认不允许) + self.enable_runtime_cleanup = bool(enable_runtime_cleanup) def start(self) -> None: """启动监控器""" @@ -1105,11 +1129,7 @@ class LogRotationMonitor: self.alert_callback("WARNING", message) else: print(f"[日志监控] WARNING: {message}") - # 异步尝试触发清理以释放空间(非阻塞监控线程) - try: - self._schedule_cleanup_async() - except Exception: - pass + # 运行时不再自动触发清理,清理仅在启动阶段执行以避免中途 I/O 干扰 # 检查轮转频率 current_time = datetime.now() if ( @@ -1134,6 +1154,10 @@ class LogRotationMonitor: def _schedule_cleanup_async(self) -> None: """如果没有正在运行的清理任务,则在后台线程中启动一次清理。""" + # 如果未开启运行时清理功能,直接返回(清理仅限启动阶段) + if not getattr(self, "enable_runtime_cleanup", False): + return + # 用锁做“唯一运行”判定,避免竞态导致并发启动多个清理线程 with self._cleanup_lock: if self._cleanup_running: @@ -1191,6 +1215,7 @@ def start_log_monitor( critical_size_mb: float = 2000.0, check_interval: int = 300, alert_callback: Optional[Callable[[str, str], None]] = None, + enable_runtime_cleanup: bool = False, ) -> None: """启动日志轮转监控器 @@ -1214,6 +1239,7 @@ def start_log_monitor( critical_size_mb=critical_size_mb, check_interval=check_interval, alert_callback=alert_callback, + enable_runtime_cleanup=enable_runtime_cleanup, ) _log_monitor.start() diff --git a/gui/gui_app.py b/gui/gui_app.py index 9c72933..aac5292 100644 --- a/gui/gui_app.py +++ b/gui/gui_app.py @@ -2782,83 +2782,146 @@ def main(): ) log_search_entry.pack(side=LEFT, padx=(0, 5)) + def refresh_run_log(): + """从内存中读取最近若干运行日志并在界面中刷新(行为上与行为日志一致)""" + try: + tail_n = 1000 + # 读取 runner 内存日志(线程安全) + with runner._lock: + total = len(runner._log) + cand = runner._log[-tail_n:] if tail_n > 0 else runner._log[:] + + # 应用筛选关键词 + kw = log_filter_var.get().strip() + if kw: + cand = [ln for ln in cand if kw in (ln or "")] + + # 保存滚动位置 + try: + scroll_pos = log_text.yview()[0] + except Exception: + scroll_pos = 1.0 + + log_text.delete("1.0", "end") + if cand: + try: + current_theme = str(gui_theme_var.get() or "litera") + except Exception: + current_theme = "litera" + + for i, line in enumerate(cand): + start_pos = log_text.index("end-1c") + if i > 0: + log_text.insert("end", "\n") + log_text.insert("end", line) + end_pos = log_text.index("end") + try: + op_type = get_operation_type(line) + if op_type: + apply_operation_color(log_text, start_pos, end_pos, line, current_theme) + except Exception: + pass + else: + log_text.insert("1.0", "暂无匹配的运行日志") + + try: + log_text.yview_moveto(scroll_pos) + except Exception: + pass + except Exception as e: + try: + log_text.delete("1.0", "end") + log_text.insert("1.0", f"刷新运行日志失败:{e}") + except Exception: + pass + log_search_matches = [] # 存储所有匹配的位置 log_current_match_index = -1 # 当前匹配的索引 + def _generic_search_widget(widget, search_var, matches_list, current_index, direction=1): + """通用的文本控件搜索函数:在 widget 中根据 search_var 搜索并高亮。 - def search_in_log_text(direction=1): - """在运行日志中搜索文本""" - nonlocal log_search_matches, log_current_match_index - - search_text = log_search_var.get().strip() + - widget: 文本控件(ScrolledText) + - search_var: tk.StringVar (包含搜索词) + - matches_list: 可变列表,用来保存匹配区间 (start_index, end_index) + - current_index: 当前匹配的索引(整数),返回更新后的索引 + - direction: 1 为下一个,-1 为上一个 + """ + search_text = search_var.get().strip() if not search_text: - # 清除高亮 - log_text.tag_remove("search_highlight", "1.0", "end") - log_search_matches = [] - log_current_match_index = -1 - return + try: + widget.tag_remove("search_highlight", "1.0", "end") + widget.tag_remove("search_current", "1.0", "end") + except Exception: + pass + matches_list.clear() + return -1 - # 获取所有文本 - content = log_text.get("1.0", "end-1c") + content = widget.get("1.0", "end-1c") if not content: - return + return -1 - # 清除之前的高亮 - log_text.tag_remove("search_highlight", "1.0", "end") - log_text.tag_remove("search_current", "1.0", "end") + try: + widget.tag_remove("search_highlight", "1.0", "end") + widget.tag_remove("search_current", "1.0", "end") + except Exception: + pass - # 配置高亮样式 - log_text.tag_config("search_highlight", background="yellow") - log_text.tag_config("search_current", background="orange") + try: + widget.tag_config("search_highlight", background="yellow") + widget.tag_config("search_current", background="orange") + except Exception: + pass - # 查找所有匹配项(不区分大小写) - log_search_matches = [] - start_pos = 0 # 使用整数索引 + matches_list.clear() + start_pos = 0 search_text_lower = search_text.lower() content_lower = content.lower() while True: - # 在内容中查找 pos = content_lower.find(search_text_lower, start_pos) if pos == -1: break - # 计算行号和列号 line_start = content[:pos].rfind("\n") + 1 line_num = content[:pos].count("\n") + 1 col_num = pos - line_start - # 转换为 tkinter 索引格式 start_index = f"{line_num}.{col_num}" end_index = f"{line_num}.{col_num + len(search_text)}" - log_search_matches.append((start_index, end_index)) + matches_list.append((start_index, end_index)) start_pos = pos + 1 - if not log_search_matches: - # 没有找到匹配项 - log_current_match_index = -1 - return + if not matches_list: + return -1 - # 高亮所有匹配项 - for start_idx, end_idx in log_search_matches: - log_text.tag_add("search_highlight", start_idx, end_idx) + for s, e in matches_list: + try: + widget.tag_add("search_highlight", s, e) + except Exception: + pass - # 根据方向更新当前匹配索引 - if direction == 1: # 下一个 - log_current_match_index = (log_current_match_index + 1) % len( - log_search_matches - ) - else: # 上一个 - log_current_match_index = (log_current_match_index - 1) % len( - log_search_matches - ) + if direction == 1: + current_index = (current_index + 1) % len(matches_list) + else: + current_index = (current_index - 1) % len(matches_list) - # 高亮当前匹配项并滚动到该位置 - if log_current_match_index >= 0: - start_idx, end_idx = log_search_matches[log_current_match_index] - log_text.tag_add("search_current", start_idx, end_idx) - log_text.see(start_idx) - log_text.mark_set("insert", start_idx) + try: + s, e = matches_list[current_index] + widget.tag_add("search_current", s, e) + widget.see(s) + widget.mark_set("insert", s) + except Exception: + pass + + return current_index + + def search_in_log_text(direction=1): + """在运行日志中搜索文本(调用通用搜索实现)""" + nonlocal log_search_matches, log_current_match_index + log_current_match_index = _generic_search_widget( + log_text, log_search_var, log_search_matches, log_current_match_index, direction + ) def search_next_in_log(): """搜索下一个""" @@ -2887,6 +2950,9 @@ def main(): ttk.Button(log_search_frame, text="搜索", command=search_next_in_log).pack( side=LEFT, padx=(0, 2) ) + ttk.Button(log_search_frame, text="刷新", command=refresh_run_log).pack( + side=LEFT, padx=(0, 8) + ) ttk.Button(log_search_frame, text="上一个", command=search_prev_in_log).pack( side=LEFT, padx=(0, 2) ) @@ -4545,68 +4611,15 @@ def main(): actions_current_match_index = -1 def search_in_actions_log(direction=1): - """在行为日志中搜索文本""" + """在行为日志中搜索文本(使用通用搜索实现)""" nonlocal actions_search_matches, actions_current_match_index - - search_text = actions_search_var.get().strip() - if not search_text: - actions_log_text.tag_remove("search_highlight", "1.0", "end") - actions_log_text.tag_remove("search_current", "1.0", "end") - actions_search_matches = [] - actions_current_match_index = -1 - return - - content = actions_log_text.get("1.0", "end-1c") - if not content: - return - - actions_log_text.tag_remove("search_highlight", "1.0", "end") - actions_log_text.tag_remove("search_current", "1.0", "end") - - actions_log_text.tag_config("search_highlight", background="yellow") - actions_log_text.tag_config("search_current", background="orange") - - actions_search_matches = [] - start_pos = 0 # 使用整数索引 - search_text_lower = search_text.lower() - content_lower = content.lower() - - while True: - pos = content_lower.find(search_text_lower, start_pos) - if pos == -1: - break - - line_start = content[:pos].rfind("\n") + 1 - line_num = content[:pos].count("\n") + 1 - col_num = pos - line_start - - start_index = f"{line_num}.{col_num}" - end_index = f"{line_num}.{col_num + len(search_text)}" - - actions_search_matches.append((start_index, end_index)) - start_pos = pos + 1 - - if not actions_search_matches: - actions_current_match_index = -1 - return - - for start_idx, end_idx in actions_search_matches: - actions_log_text.tag_add("search_highlight", start_idx, end_idx) - - if direction == 1: - actions_current_match_index = (actions_current_match_index + 1) % len( - actions_search_matches - ) - else: - actions_current_match_index = (actions_current_match_index - 1) % len( - actions_search_matches - ) - - if actions_current_match_index >= 0: - start_idx, end_idx = actions_search_matches[actions_current_match_index] - actions_log_text.tag_add("search_current", start_idx, end_idx) - actions_log_text.see(start_idx) - actions_log_text.mark_set("insert", start_idx) + actions_current_match_index = _generic_search_widget( + actions_log_text, + actions_search_var, + actions_search_matches, + actions_current_match_index, + direction, + ) def search_next_in_actions(): search_in_actions_log(1) diff --git a/gui/web_gui.py b/gui/web_gui.py index 5adb892..85be1e3 100644 --- a/gui/web_gui.py +++ b/gui/web_gui.py @@ -1610,6 +1610,30 @@ class Handler(BaseHTTPRequestHandler): return self._send_json(RUNNER.get_high_value_rooms()) if u.path == "/api/logs": qs = parse_qs(u.query) + # 支持后端搜索模式:当提供 q 参数时,按最近若干条在后端过滤并返回(与 /api/actions 行为一致) + q = (qs.get("q") or [""])[0] + try: + tail_n = int((qs.get("lines") or [200])[0]) + except Exception: + tail_n = 200 + + # 如果提供了搜索关键词,则走后端过滤路径,忽略 since(前端会使用此接口做搜索) + if q: + try: + # 取最近 tail_n 条作为候选,然后按关键词过滤(不区分大小写) + with RUNNER._lock: + total = len(RUNNER._log) + cand = RUNNER._log[-tail_n:] if tail_n > 0 else RUNNER._log[:] + qlow = q.lower() + filtered = [l for l in cand if qlow in (l or "").lower()] + return self._send_json({"next": total, "lines": filtered, "running": RUNNER.is_running()}) + except Exception as e: + import traceback + + print(f"[WEB_GUI] logs search error: {e}\n{traceback.format_exc()}") + return self._send_json({"next": 0, "lines": [], "running": RUNNER.is_running()}) + + # 默认行为:按 since 增量返回日志(原有逻辑) since = 0 try: since = int((qs.get("since") or [0])[0]) @@ -1617,23 +1641,13 @@ class Handler(BaseHTTPRequestHandler): since = 0 try: next_idx, lines = RUNNER.get_logs_since(since) - return self._send_json( - { - "next": next_idx, - "lines": lines, - "running": RUNNER.is_running(), - } - ) + return self._send_json({"next": next_idx, "lines": lines, "running": RUNNER.is_running()}) except Exception as e: # 记录错误但不中断请求,返回空日志 import traceback - print( - f"[WEB_GUI] get_logs_since error: {e}\n{traceback.format_exc()}" - ) - return self._send_json( - {"next": 0, "lines": [], "running": RUNNER.is_running()} - ) + print(f"[WEB_GUI] get_logs_since error: {e}\n{traceback.format_exc()}") + return self._send_json({"next": 0, "lines": [], "running": RUNNER.is_running()}) if u.path == "/api/logfile-tail": # 返回统一日志文件的尾部若干行,便于在内存日志不同步时调试 qs = parse_qs(u.query) diff --git a/webui/app.js b/webui/app.js index 7487123..13285bd 100644 --- a/webui/app.js +++ b/webui/app.js @@ -5,6 +5,14 @@ let shotTimer = null; let lastLogUpdateTime = 0; // 最后成功获取日志的时间 let logErrorCount = 0; // 连续错误计数 let emptyResponseCount = 0; // 连续空响应计数(用于检测索引卡住) +// 双日志缓冲与过滤 +let runLogBuffer = []; +let runLogFilter = ""; +const runLogMaxLines = 50000; + +let actionsLogBuffer = []; +let actionsLogFilter = ""; +const actionsLogMaxLines = 5000; const DEFAULTS = { // 筛选 @@ -88,7 +96,7 @@ function initTabs() { } function appendLog(lines) { - const log = $("log"); + const log = $("runLog"); if (!lines || lines.length === 0) return; // 记录更新前与底部的距离,用于在非底部时保持视图位置 @@ -98,7 +106,18 @@ function appendLog(lines) { // 性能优化:批量追加文本,减少重排次数 const newText = lines.join("\n") + "\n"; - log.textContent += newText; + // 直接追加到 DOM,同时维护 runLogBuffer 以便支持搜索 + const toAppend = lines; + for (const ln of toAppend) runLogBuffer.push(ln); + // 限制缓冲 + if (runLogBuffer.length > runLogMaxLines) runLogBuffer = runLogBuffer.slice(-runLogMaxLines); + // 如果没有过滤器,直接将文本拼接(性能优先) + if (!runLogFilter) { + log.textContent += newText; + } else { + // 有过滤器时重渲染整个视图 + renderRunLog(); + } // 性能优化:限制日志长度,避免内存溢出(保留最近较多字符以便桌面端查看) const maxLength = 200000; @@ -118,6 +137,48 @@ function appendLog(lines) { } } +function renderRunLog() { + const el = $("runLog"); + if (!el) return; + const filter = (runLogFilter || "").toLowerCase(); + let lines = runLogBuffer; + if (filter) { + lines = runLogBuffer.filter(l => String(l || "").toLowerCase().includes(filter)); + } + const prevScrollBottom = el.scrollHeight - el.scrollTop - el.clientHeight; + el.textContent = lines.join("\n") + (lines.length ? "\n" : ""); + // 尽量保持原来滚动位置;若位于底部则滚到底部 + if (prevScrollBottom < 5) el.scrollTop = el.scrollHeight; else el.scrollTop = Math.max(0, el.scrollHeight - el.clientHeight - prevScrollBottom); +} + +function appendRunLogLines(lines) { + if (!Array.isArray(lines) || lines.length === 0) return; + // 使用 appendLog 让现有的 UI 消息也能写入缓冲并利用已有行为 + appendLog(lines); +} + +async function fetchActionsLog() { + try { + const data = await apiGet('/api/actions?lines=500'); + const lines = Array.isArray(data.lines) ? data.lines : []; + actionsLogBuffer = lines.slice(-actionsLogMaxLines); + renderActionsLog(); + } catch (e) { + console.error('fetchActionsLog error', e); + } +} + +function renderActionsLog() { + const el = $("actionsLog"); + if (!el) return; + const filter = (actionsLogFilter || "").toLowerCase(); + let lines = actionsLogBuffer; + if (filter) lines = actionsLogBuffer.filter(l => String(l || "").toLowerCase().includes(filter)); + el.textContent = lines.join("\n") + (lines.length ? "\n" : ""); + // 自动滚到底部 + el.scrollTop = el.scrollHeight; +} + function fmtTime(ts) { if (!ts) return "-"; try { @@ -609,12 +670,12 @@ async function startRun() { } } - // 重置本地日志索引并清空显示区域,然后立即拉取最新日志 + // 重置本地日志索引并清空显示区域,然后立即拉取最新日志 try { logIdx = 0; emptyResponseCount = 0; // 重置空响应计数 // 清空日志显示区域,准备显示新进程的日志 - const logEl = $("log"); + const logEl = $("runLog"); if (logEl) { logEl.textContent = ""; } @@ -685,8 +746,8 @@ async function pollLogs() { console.warn('[WEB_DBG] pollLogs: 检测到日志截断,重置索引', { oldIdx: logIdx, newIdx: nextIdx }); logIdx = 0; emptyResponseCount = 0; // 重置空响应计数 - // 清空日志显示区域,准备重新显示 - const log = document.getElementById('log'); + // 清空运行日志显示区域,准备重新显示 + const log = document.getElementById('runLog'); if (log) { log.textContent = ''; } @@ -695,7 +756,7 @@ async function pollLogs() { if (retryData && typeof retryData === 'object' && Array.isArray(retryData.lines)) { logIdx = typeof retryData.next === 'number' ? retryData.next : 0; if (retryData.lines.length > 0) { - appendLog(retryData.lines); + appendRunLogLines(retryData.lines); } } return; @@ -708,7 +769,7 @@ async function pollLogs() { // 追加日志 if (Array.isArray(data.lines) && data.lines.length > 0) { - appendLog(data.lines); + appendRunLogLines(data.lines); emptyResponseCount = 0; // 重置空响应计数 } else { // 没有新日志是正常的(比如脚本没有运行),不需要重置索引 @@ -1125,6 +1186,24 @@ window.addEventListener("DOMContentLoaded", async () => { } }); + // 日志搜索与动作日志相关交互绑定 + const runSearchEl = $("runLogSearch"); + if (runSearchEl) { + runSearchEl.addEventListener('input', (e) => { runLogFilter = String(e.target.value || ''); renderRunLog(); }); + } + const runClear = $("btnRunLogClear"); + if (runClear) runClear.addEventListener('click', () => { runLogBuffer = []; renderRunLog(); }); + + const actionsSearchEl = $("actionsLogSearch"); + if (actionsSearchEl) { + actionsSearchEl.addEventListener('input', (e) => { actionsLogFilter = String(e.target.value || ''); renderActionsLog(); }); + } + const actionsRefresh = $("btnActionsRefresh"); + if (actionsRefresh) actionsRefresh.addEventListener('click', () => { fetchActionsLog(); }); + + // 首次加载动作日志 + fetchActionsLog(); + await refreshDevices(); await loadConfig(); diff --git a/webui/index.html b/webui/index.html index 4c7e4a9..0e8507b 100644 --- a/webui/index.html +++ b/webui/index.html @@ -792,7 +792,30 @@ 日志 -

+
+        
+
+
+
运行日志
+
+ + +
+
+

+          
+ +
+
+
行为日志
+
+ + +
+
+

+          
+
diff --git a/webui/styles.css b/webui/styles.css index 30975b2..124cae3 100644 --- a/webui/styles.css +++ b/webui/styles.css @@ -244,6 +244,16 @@ body { max-width: 100%; } +/* 双日志面板布局与搜索框样式 */ +.logRow { display: flex; gap: 12px; } +.logSection { flex: 1 1 0; display: flex; flex-direction: column; } +.logHeader { display:flex; align-items:center; justify-content:space-between; margin-bottom:6px; } +.logTitle { font-weight:600; color:var(--text); } +.logHeaderActions { display:flex; gap:8px; align-items:center; } +.logSearchBox { border:1px solid var(--border); padding:6px 8px; border-radius:4px; min-width:220px; background:var(--card); color:var(--text); } +.logSearchBox:focus { outline:2px solid rgba(37,99,235,0.12); } +.btn.small { padding:4px 8px; font-size:12px; } + .preview { border: 1px solid var(--border); background: #f3f4f6;