454 lines
15 KiB
Python
454 lines
15 KiB
Python
"""douyin_logging_wrapper_pkg.enhanced - enhanced_log_kv 主入口。
|
||
|
||
按 verbose 配置决定走 simple / detailed 实现。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import inspect
|
||
import os
|
||
import re
|
||
import sys
|
||
import time
|
||
import traceback
|
||
from datetime import datetime
|
||
from typing import Any, Dict, Optional
|
||
|
||
from ._common import (
|
||
COLORAMA_AVAILABLE,
|
||
Fore,
|
||
LOGGING_MODULES_AVAILABLE,
|
||
Style,
|
||
_action_logger,
|
||
_debug_logger,
|
||
_error_logger,
|
||
_performance_tracker,
|
||
)
|
||
|
||
|
||
from .simple import _enhanced_log_kv_simple
|
||
from .simple import _format_simple_stdout_line
|
||
from .detailed import _enhanced_log_kv_detailed
|
||
from .detailed import _format_detailed_stdout_line
|
||
|
||
|
||
_ANSI_RE = re.compile(r"\x1b\[[0-9;]*m")
|
||
|
||
|
||
def _strip_ansi(text: str) -> str:
|
||
return _ANSI_RE.sub("", str(text or ""))
|
||
|
||
|
||
def _dated_log_path(base_path: str, timestamp: str) -> str:
|
||
root, ext = os.path.splitext(base_path)
|
||
try:
|
||
day = str(timestamp or "")[:10]
|
||
if re.fullmatch(r"\d{4}-\d{2}-\d{2}", day):
|
||
return f"{root}_{day}{ext or '.log'}"
|
||
except Exception:
|
||
pass
|
||
return base_path
|
||
|
||
|
||
def _append_line(path: str, line: str) -> None:
|
||
try:
|
||
log_dir = os.path.dirname(path)
|
||
if log_dir:
|
||
os.makedirs(log_dir, exist_ok=True)
|
||
with open(path, "a", encoding="utf-8-sig", errors="replace") as f:
|
||
f.write(_strip_ansi(line).replace("\r", " ").replace("\n", " ") + "\n")
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def _append_dual_format_logs(timestamp: str, simple_line: str, detail_line: str) -> None:
|
||
"""磁盘始终保留 simple/detail 两份,GUI 显示模式不影响留存。"""
|
||
try:
|
||
from douyin.core import path_config
|
||
|
||
simple_path = _dated_log_path(path_config.get_simple_log_path(), timestamp)
|
||
detail_path = _dated_log_path(path_config.get_detail_log_path(), timestamp)
|
||
except Exception:
|
||
log_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "..", "logs"))
|
||
day = str(timestamp or "")[:10]
|
||
suffix = f"_{day}" if re.fullmatch(r"\d{4}-\d{2}-\d{2}", day) else ""
|
||
simple_path = os.path.join(log_dir, f"simple{suffix}.log")
|
||
detail_path = os.path.join(log_dir, f"detail{suffix}.log")
|
||
|
||
_append_line(simple_path, simple_line)
|
||
_append_line(detail_path, detail_line)
|
||
|
||
|
||
def enhanced_log_kv(analyser: Any, *args: Any, **fields: Any) -> None:
|
||
"""增强的日志记录方法:始终输出到 stdout(供 GUI 捕获),同时可选输出到标准 logging
|
||
|
||
参数:
|
||
analyser: 分析器对象
|
||
*args: 位置参数,第一个是tag,第二个是msg
|
||
**fields: 关键字参数字典
|
||
"""
|
||
# 解析参数:优先使用位置参数,避免与关键字参数冲突
|
||
if len(args) >= 1:
|
||
tag = args[0]
|
||
# 如果位置参数提供了 tag,从 fields 中移除 tag 避免冲突
|
||
fields.pop("tag", None)
|
||
else:
|
||
tag = fields.get("tag", "日志")
|
||
|
||
if len(args) >= 2:
|
||
msg = args[1]
|
||
# 如果位置参数提供了 msg,从 fields 中移除 msg 避免冲突
|
||
fields.pop("msg", None)
|
||
else:
|
||
msg = fields.get("msg", "")
|
||
|
||
# 获取日志级别
|
||
log_level = fields.get("level", "INFO").upper()
|
||
if log_level not in ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"):
|
||
log_level = "INFO"
|
||
|
||
# 获取颜色设置
|
||
color = fields.get("color", None)
|
||
if color:
|
||
fields.pop("color", None) # 从 fields 中移除,避免在日志中显示
|
||
|
||
# 支持可选的 log_type 字段,用于区分行为日志类型(OP/ERR/DEBUG/SCREENSHOT/PERF)
|
||
# 优先使用 fields 中的 `log_type` 或 `type`,并从 fields 中移除以避免重复输出
|
||
raw_log_type = None
|
||
if "log_type" in fields:
|
||
raw_log_type = fields.pop("log_type")
|
||
elif "type" in fields:
|
||
raw_log_type = fields.pop("type")
|
||
|
||
log_type = None
|
||
if raw_log_type:
|
||
try:
|
||
log_type_str = str(raw_log_type).strip().upper()
|
||
# 归一化常见类型
|
||
if log_type_str in ("ERROR", "ERR", "E"):
|
||
log_type = "ERR"
|
||
elif log_type_str in ("DEBUG", "DBG", "D"):
|
||
log_type = "DEBUG"
|
||
elif log_type_str in ("SCREENSHOT", "PIC", "IMG"):
|
||
log_type = "SCREENSHOT"
|
||
elif log_type_str in ("PERF", "性能"):
|
||
log_type = "PERF"
|
||
else:
|
||
log_type = "OP"
|
||
except Exception:
|
||
log_type = "OP"
|
||
# 如果没有显式提供 log_type,尝试根据 tag 推断(保持向后兼容)
|
||
if not log_type:
|
||
try:
|
||
tag_str = str(tag or "").lower()
|
||
if any(k in tag_str for k in ("错", "异常", "error", "err")):
|
||
log_type = "ERR"
|
||
elif any(k in tag_str for k in ("调试", "debug", "dbg")):
|
||
log_type = "DEBUG"
|
||
elif any(
|
||
k in tag_str for k in ("截图", "图像", "screenshot", "pic", "img")
|
||
):
|
||
log_type = "SCREENSHOT"
|
||
elif any(k in tag_str for k in ("性能", "耗时", "步骤耗时", "perf")):
|
||
log_type = "PERF"
|
||
else:
|
||
log_type = "OP"
|
||
except Exception:
|
||
log_type = "OP"
|
||
|
||
# 递增日志序号
|
||
try:
|
||
analyser._log_seq += 1
|
||
except Exception:
|
||
analyser._log_seq = 1
|
||
|
||
# 获取时间戳(使用系统时间)
|
||
try:
|
||
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
|
||
except Exception:
|
||
# 如果无法导入 datetime(极少见),回退为 time.strftime
|
||
try:
|
||
timestamp = time.strftime("%H:%M:%S")
|
||
except Exception:
|
||
timestamp = ""
|
||
|
||
# 获取调用者信息(模块名:函数名:行号)
|
||
caller_info = ""
|
||
try:
|
||
# 获取调用栈:跳过 _enhanced_log_kv 本身,找到真正的调用者
|
||
frame = inspect.currentframe()
|
||
if frame:
|
||
# frame.f_back 是调用 _enhanced_log_kv 的帧(可能是 _log_kv 或其他)
|
||
# 需要再往上找一层,找到实际调用 _log_kv 的代码
|
||
caller_frame = frame.f_back
|
||
if caller_frame:
|
||
# 检查是否是 _log_kv 的调用(属性赋值的情况)
|
||
if (
|
||
caller_frame.f_code.co_name == "_log_kv"
|
||
or "log_kv" in caller_frame.f_code.co_name
|
||
):
|
||
caller_frame = caller_frame.f_back
|
||
# 如果找到了调用者,提取信息
|
||
if caller_frame:
|
||
filename = caller_frame.f_code.co_filename
|
||
funcname = caller_frame.f_code.co_name
|
||
lineno = caller_frame.f_lineno
|
||
# 只取文件名,不包含路径
|
||
filename = os.path.basename(filename)
|
||
# 如果文件名是 <string> 或类似,说明是测试代码,跳过
|
||
if filename and filename not in ("<string>", "<stdin>"):
|
||
caller_info = f"{filename}:{funcname}:{lineno}"
|
||
except Exception:
|
||
pass
|
||
|
||
# 字段映射(中文 key)
|
||
key_map: Dict[str, str] = {
|
||
"rid": "运行",
|
||
"seq": "序号",
|
||
"msg": "说明",
|
||
"stage": "阶段",
|
||
"seen": "识别",
|
||
"ok": "成功",
|
||
"text": "文本",
|
||
"action": "动作",
|
||
"result": "结果",
|
||
"mode": "模式",
|
||
"reason": "原因",
|
||
"wait_seconds": "等待秒",
|
||
"value_yuan": "价值元",
|
||
"future": "开奖时间",
|
||
"pos_seen": "发现位置",
|
||
"qsize": "队列数量",
|
||
"room_pos": "当前位置",
|
||
"content": "内容",
|
||
"countdown": "倒计时",
|
||
"participants": "参与人数",
|
||
"copies": "份数",
|
||
"seconds": "耗时秒",
|
||
"error": "错误",
|
||
"error_type": "错误类型",
|
||
"fudai_x": "福袋X坐标",
|
||
"attempt": "尝试次数",
|
||
"room_title": "直播间名",
|
||
"back_times": "需回退次数",
|
||
"elapsed_ms": "耗时",
|
||
"分数": "分数",
|
||
"置信度": "置信度",
|
||
"阈值": "阈值",
|
||
"红色比例": "红色比例",
|
||
"匹配分数": "匹配分数",
|
||
"模板匹配分数": "模板匹配分数",
|
||
"平均分": "平均分",
|
||
"检测结果": "检测结果",
|
||
"检测方法": "检测方法",
|
||
"耗时(ms)": "耗时",
|
||
# 筛选相关字段映射
|
||
"配置_最小价值": "最小价值",
|
||
"配置_最小参与人数": "最小参与人数",
|
||
"配置_最大参与人数": "最大参与人数",
|
||
"配置_倒计时大于秒数": "倒计时大于阈值",
|
||
"配置_倒计时小于秒数": "倒计时小于阈值",
|
||
"实际_价值": "实际价值",
|
||
"实际_参与人数": "实际参与人数",
|
||
"实际_份数": "实际份数",
|
||
"实际_剩余秒数": "剩余秒数",
|
||
"实际_内容": "福袋内容",
|
||
"配置阈值秒数": "阈值秒数",
|
||
"实际剩余秒数": "剩余秒数",
|
||
"判断条件": "判断条件",
|
||
"说明": "说明",
|
||
"是否有倒计时数据": "有倒计时数据",
|
||
"按钮文本": "按钮文本",
|
||
}
|
||
|
||
# 构建简洁的日志行:时间 [级别] [标签] 消息 关键字段
|
||
log_parts: list[str] = []
|
||
if timestamp:
|
||
log_parts.append(f"[{timestamp}]")
|
||
log_parts.append(f"[{log_level}]")
|
||
if tag and tag != "日志":
|
||
log_parts.append(f"[{tag}]")
|
||
|
||
if msg:
|
||
m = str(msg).replace("\r", " ").replace("\n", " ").strip()
|
||
if len(m) > 150:
|
||
m = m[:150] + "..."
|
||
log_parts.append(m)
|
||
|
||
# 只添加最重要的字段,避免日志过长
|
||
important_fields = []
|
||
for k, v in fields.items():
|
||
if k in ("tag", "msg", "level", "exc_info", "_show_caller", "_caller"):
|
||
continue
|
||
if v is None:
|
||
continue
|
||
# 只显示关键字段:耗时、价值、错误等
|
||
if k in (
|
||
"elapsed_seconds",
|
||
"value_yuan",
|
||
"error",
|
||
"room_pos",
|
||
"future_ts",
|
||
"elapsed_ms",
|
||
"分数",
|
||
"置信度",
|
||
"阈值",
|
||
"红色比例",
|
||
"匹配分数",
|
||
"模板匹配分数",
|
||
"平均分",
|
||
"检测结果",
|
||
"检测方法",
|
||
"耗时(ms)",
|
||
"福袋内容",
|
||
"任务列表",
|
||
"倒计时分钟",
|
||
"倒计时秒",
|
||
"奖品价值",
|
||
"按钮文本",
|
||
"直播间标题",
|
||
"fudai_content_raw",
|
||
"task_list_raw",
|
||
"countdown_mm_raw",
|
||
"countdown_ss_raw",
|
||
"value_raw",
|
||
"button_text_raw",
|
||
"live_room_title_raw",
|
||
# 筛选相关字段
|
||
"配置_最小价值",
|
||
"配置_最小参与人数",
|
||
"配置_最大参与人数",
|
||
"配置_倒计时大于秒数",
|
||
"配置_倒计时小于秒数",
|
||
"实际_价值",
|
||
"实际_参与人数",
|
||
"实际_份数",
|
||
"实际_剩余秒数",
|
||
"实际_内容",
|
||
"配置阈值秒数",
|
||
"实际剩余秒数",
|
||
"判断条件",
|
||
"说明",
|
||
"原因",
|
||
"是否有倒计时数据",
|
||
"按钮文本",
|
||
):
|
||
key_cn = key_map.get(str(k), k)
|
||
if isinstance(v, float):
|
||
# 优先检测毫秒字段(例如 elapsed_ms、total_elapsed_ms),避免被 "elapsed" 关键字误判为秒
|
||
if "ms" in k:
|
||
v_str = f"{v:.0f}ms"
|
||
elif "seconds" in k or "elapsed" in k:
|
||
v_str = f"{v:.1f}s"
|
||
elif "yuan" in k:
|
||
v_str = f"{v:.0f}元"
|
||
elif "分数" in k or "置信度" in k or "比例" in k or "阈值" in k:
|
||
v_str = f"{v:.3f}"
|
||
else:
|
||
v_str = f"{v:.1f}"
|
||
else:
|
||
v_str = str(v)[:20] # 限制字段值长度
|
||
important_fields.append(f"{key_cn}={v_str}")
|
||
|
||
if important_fields:
|
||
log_parts.append(" ".join(important_fields))
|
||
|
||
# simple 模式需要这个类型来决定是否静默 DEBUG/PERF/SCREENSHOT。
|
||
fields["_log_type"] = log_type
|
||
|
||
# 构建完整日志行
|
||
log_line = " ".join(log_parts)
|
||
|
||
# 简化分隔符逻辑,只在真正重要的阶段变化时添加,且使用更简洁的分隔符
|
||
need_separator = False
|
||
separator_reason = ""
|
||
last_tag = getattr(analyser, "_last_log_tag", None)
|
||
tag_changed = bool(tag) and tag != last_tag
|
||
|
||
# 只在错误或非常重要的阶段变化时添加分隔符,避免日志过于冗余
|
||
if log_level in ("ERROR", "CRITICAL"):
|
||
need_separator = True
|
||
separator_reason = f"错误: {tag or '系统'}"
|
||
elif tag_changed and tag in ("运行", "启动", "完成"):
|
||
need_separator = True
|
||
separator_reason = tag
|
||
|
||
# 输出分隔符(如果需要)- 使用更简洁的分隔符
|
||
if need_separator:
|
||
try:
|
||
separator = f"=== {separator_reason} ==="
|
||
print(separator, flush=True)
|
||
except Exception:
|
||
pass
|
||
|
||
# 更新上一个日志标签
|
||
analyser._last_log_tag = tag
|
||
|
||
# 获取日志格式模式配置(simple 或 detailed)
|
||
log_format_mode = "simple" # 默认简洁模式
|
||
try:
|
||
from douyin.core import path_config
|
||
import json
|
||
|
||
config_path = path_config.get_config_path()
|
||
if os.path.exists(config_path):
|
||
with open(config_path, "r", encoding="utf-8") as f:
|
||
config = json.load(f)
|
||
log_format_mode = config.get("logging", {}).get(
|
||
"log_format_mode", "simple"
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
file_fields = dict(fields)
|
||
file_fields.pop("_log_type", None)
|
||
try:
|
||
simple_file_line = _format_simple_stdout_line(
|
||
tag,
|
||
msg,
|
||
log_level,
|
||
timestamp,
|
||
fields,
|
||
log_line,
|
||
)
|
||
detail_file_line = _format_detailed_stdout_line(
|
||
log_parts,
|
||
caller_info,
|
||
file_fields,
|
||
)
|
||
_append_dual_format_logs(timestamp, simple_file_line, detail_file_line)
|
||
except Exception:
|
||
pass
|
||
|
||
# 根据模式决定日志格式
|
||
if log_format_mode == "detailed":
|
||
# 详细模式:保留之前的复杂格式
|
||
fields.pop("_log_type", None)
|
||
return _enhanced_log_kv_detailed(
|
||
analyser,
|
||
tag,
|
||
msg,
|
||
log_level,
|
||
log_type,
|
||
log_parts,
|
||
timestamp,
|
||
caller_info,
|
||
fields,
|
||
need_separator,
|
||
separator_reason,
|
||
color,
|
||
)
|
||
else:
|
||
# 简洁模式:使用优化后的格式
|
||
return _enhanced_log_kv_simple(
|
||
analyser,
|
||
tag,
|
||
msg,
|
||
log_level,
|
||
log_parts,
|
||
timestamp,
|
||
fields,
|
||
need_separator,
|
||
separator_reason,
|
||
color,
|
||
)
|