362 lines
12 KiB
Python
362 lines
12 KiB
Python
"""douyin_logging_wrapper_pkg.detailed - _enhanced_log_kv_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,
|
||
)
|
||
|
||
|
||
def _enhanced_log_kv_detailed(
|
||
analyser: Any,
|
||
tag: str,
|
||
msg: str,
|
||
log_level: str,
|
||
log_type: str,
|
||
log_parts: list[str],
|
||
timestamp: str,
|
||
caller_info: str,
|
||
fields: Dict[str, Any],
|
||
need_separator: bool,
|
||
separator_reason: str,
|
||
color: Optional[str] = None,
|
||
) -> None:
|
||
"""详细模式的日志记录(保留之前的复杂格式用于debug)"""
|
||
# 字段映射(中文 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": "需回退次数",
|
||
}
|
||
# 输出分隔符(如果需要)- 详细模式使用更明显的分隔符
|
||
if need_separator:
|
||
try:
|
||
separator = "=" * 50
|
||
separator_line = f"{separator} {separator_reason} {separator}"
|
||
print(separator_line, flush=True)
|
||
except Exception:
|
||
pass
|
||
|
||
# 更新上一个日志标签
|
||
analyser._last_log_tag = tag
|
||
|
||
# 构建详细的日志行(包含更多信息)
|
||
detailed_log_parts = log_parts.copy()
|
||
|
||
# 在详细模式下添加更多字段信息
|
||
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
|
||
# 详细模式显示更多字段
|
||
key_cn = key_map.get(str(k), k)
|
||
if isinstance(v, float):
|
||
if "seconds" in k or "elapsed" in k:
|
||
v_str = f"{v:.2f}s"
|
||
elif "yuan" in k:
|
||
v_str = f"{v:.0f}元"
|
||
else:
|
||
v_str = f"{v:.2f}"
|
||
else:
|
||
v_str = str(v)[:30] # 详细模式允许稍长
|
||
important_fields.append(f"{key_cn}={v_str}")
|
||
|
||
if important_fields:
|
||
detailed_log_parts.append(" ".join(important_fields))
|
||
|
||
# 添加调用者信息(详细模式)
|
||
if caller_info:
|
||
detailed_log_parts.append(f"[调用:{caller_info}]")
|
||
|
||
log_line = " ".join(detailed_log_parts)
|
||
|
||
# 应用颜色(如果指定了颜色)
|
||
if color:
|
||
try:
|
||
if hasattr(Fore, color.upper()):
|
||
color_code = getattr(Fore, color.upper())
|
||
log_line = f"{color_code}{log_line}{Style.RESET_ALL}"
|
||
elif color.startswith("\033["): # ANSI 转义序列
|
||
log_line = f"{color}{log_line}{Style.RESET_ALL}"
|
||
except Exception:
|
||
pass # 如果颜色应用失败,使用原始日志行
|
||
|
||
# 始终输出到 stdout(供 GUI 捕获)
|
||
try:
|
||
print(log_line, flush=True)
|
||
except Exception:
|
||
pass
|
||
|
||
# 详细的行为日志记录(保留之前的复杂逻辑)
|
||
try:
|
||
# 记录所有操作到行为日志(详细模式)
|
||
should_log = True
|
||
|
||
# 过滤一些不需要记录的日志(避免噪音)
|
||
if tag:
|
||
skip_tags = ["[调试图像]", "[步骤耗时]"]
|
||
for skip_tag in skip_tags:
|
||
if tag.startswith(skip_tag):
|
||
should_log = False
|
||
break
|
||
|
||
if should_log:
|
||
# 提取关键信息:做了什么、耗时、分数
|
||
def _shorten(value: Any, max_len: int = 60) -> str:
|
||
s = str(value).strip()
|
||
if len(s) > max_len:
|
||
return s[: max_len - 3] + "..."
|
||
return s
|
||
|
||
if msg:
|
||
action_desc = _shorten(str(msg), max_len=120)
|
||
# 移除函数名:匹配 "函数名:" 或 "函数名 " 格式
|
||
action_desc = re.sub(
|
||
r"^[a-zA-Z_][a-zA-Z0-9_]*\s*[::]\s*", "", action_desc
|
||
)
|
||
action_desc = re.sub(
|
||
r"^[a-zA-Z_][a-zA-Z0-9_]*\s+(?=[^a-zA-Z_])", "", action_desc
|
||
)
|
||
if not action_desc.strip():
|
||
action_desc = _shorten(str(msg), max_len=120)
|
||
else:
|
||
if tag:
|
||
tag_clean = tag.strip("[]").strip()
|
||
if tag_clean:
|
||
action_desc = tag_clean
|
||
else:
|
||
action_desc = "操作"
|
||
else:
|
||
action_desc = "操作"
|
||
|
||
# 提取耗时
|
||
elapsed_str = ""
|
||
fields_clean: Dict[str, Any] = {}
|
||
for k, v in fields.items():
|
||
kk = str(k)
|
||
if kk.startswith("字段_"):
|
||
kk = kk[len("字段_") :]
|
||
fields_clean[kk] = v
|
||
|
||
if "elapsed_ms" in fields_clean:
|
||
elapsed_seconds = float(fields_clean.get("elapsed_ms", 0)) / 1000.0
|
||
elapsed_str = f"耗时:{elapsed_seconds:.2f}s"
|
||
elif "total_elapsed_ms" in fields_clean:
|
||
elapsed_seconds = (
|
||
float(fields_clean.get("total_elapsed_ms", 0)) / 1000.0
|
||
)
|
||
elapsed_str = f"耗时:{elapsed_seconds:.2f}s"
|
||
elif "total_ms" in fields_clean:
|
||
elapsed_seconds = float(fields_clean.get("total_ms", 0)) / 1000.0
|
||
elapsed_str = f"耗时:{elapsed_seconds:.2f}s"
|
||
elif "seconds" in fields_clean:
|
||
elapsed_seconds = float(fields_clean.get("seconds", 0))
|
||
elapsed_str = f"耗时:{elapsed_seconds:.2f}s"
|
||
elif "elapsed_seconds" in fields_clean:
|
||
elapsed_seconds = float(fields_clean.get("elapsed_seconds", 0))
|
||
elapsed_str = f"耗时:{elapsed_seconds:.2f}s"
|
||
|
||
# 提取分数
|
||
score_str = ""
|
||
if "score" in fields_clean and fields_clean.get("score") is not None:
|
||
try:
|
||
score_val = float(fields_clean.get("score", 0))
|
||
score_str = f"分数:{score_val:.3f}"
|
||
except (ValueError, TypeError):
|
||
pass
|
||
|
||
# 构建详细的行为日志行
|
||
action_parts = [timestamp, "-", "[GUI]", "-"]
|
||
if tag:
|
||
action_parts.append(tag)
|
||
else:
|
||
action_parts.append("[日志]")
|
||
|
||
if log_type:
|
||
action_parts.append(f"[{log_type}]")
|
||
|
||
action_parts.append(action_desc)
|
||
|
||
if elapsed_str:
|
||
action_parts.append(elapsed_str)
|
||
|
||
if score_str:
|
||
action_parts.append(score_str)
|
||
|
||
action_log_line = " ".join(action_parts)
|
||
|
||
# 写入 actions.log 文件
|
||
try:
|
||
from douyin.core import path_config
|
||
|
||
actions_log_path = path_config.get_actions_log_path()
|
||
log_dir = path_config.get_logs_dir()
|
||
except Exception:
|
||
actions_log_path = os.path.join(
|
||
os.path.dirname(__file__), "logs", "actions.log"
|
||
)
|
||
log_dir = os.path.dirname(actions_log_path)
|
||
|
||
if log_dir:
|
||
os.makedirs(log_dir, exist_ok=True)
|
||
|
||
# 检测标签变化
|
||
if not hasattr(analyser, "_last_action_tag"):
|
||
analyser._last_action_tag = None
|
||
|
||
current_tag = tag or "[日志]"
|
||
try:
|
||
import logging
|
||
|
||
action_logger = logging.getLogger("action_logger")
|
||
if (
|
||
analyser._last_action_tag is not None
|
||
and analyser._last_action_tag != current_tag
|
||
):
|
||
action_logger.info("=" * 80)
|
||
action_logger.info(action_log_line)
|
||
analyser._last_action_tag = current_tag
|
||
except Exception:
|
||
if log_dir:
|
||
with open(
|
||
actions_log_path,
|
||
"a",
|
||
encoding="utf-8-sig",
|
||
errors="replace",
|
||
) as f:
|
||
if (
|
||
analyser._last_action_tag is not None
|
||
and analyser._last_action_tag != current_tag
|
||
):
|
||
f.write("=" * 80 + "\n")
|
||
analyser._last_action_tag = current_tag
|
||
f.write(action_log_line + "\n")
|
||
f.flush()
|
||
except Exception:
|
||
pass
|
||
|
||
# 详细模式:保留标准logging输出(用于debug)
|
||
try:
|
||
import logging
|
||
|
||
root_logger = logging.getLogger()
|
||
if not root_logger.handlers:
|
||
try:
|
||
from douyin.logging import douyin_logging
|
||
|
||
douyin_logging.configure_logging()
|
||
except Exception:
|
||
pass
|
||
|
||
if not hasattr(analyser, "_std_logger") or analyser._std_logger is None:
|
||
try:
|
||
from douyin.logging.unified_logger import get_unified_logger
|
||
|
||
analyser._std_logger = get_unified_logger("douyin.fudai")
|
||
except ImportError:
|
||
try:
|
||
from douyin.logging import douyin_logging
|
||
|
||
analyser._std_logger = douyin_logging.get_logger("douyin")
|
||
except Exception:
|
||
analyser._std_logger = logging.getLogger("douyin.fudai")
|
||
|
||
root_logger = logging.getLogger()
|
||
if root_logger.handlers:
|
||
std_msg_parts = [f"[{tag}]"]
|
||
if caller_info:
|
||
std_msg_parts.append(f"[调用:{caller_info}]")
|
||
if msg:
|
||
try:
|
||
from douyin.logging.unified_logger import SensitiveDataMasker
|
||
|
||
masked_msg = SensitiveDataMasker.mask_all(str(msg))
|
||
std_msg_parts.append(masked_msg)
|
||
except ImportError:
|
||
std_msg_parts.append(str(msg))
|
||
|
||
masked_fields: Dict[str, Any] = {}
|
||
try:
|
||
from douyin.logging.unified_logger import SensitiveDataMasker
|
||
|
||
masked_fields = SensitiveDataMasker.mask_dict(fields)
|
||
except ImportError:
|
||
masked_fields = fields
|
||
|
||
for k, v in masked_fields.items():
|
||
if k in (
|
||
"tag",
|
||
"msg",
|
||
"level",
|
||
"exc_info",
|
||
"_show_caller",
|
||
"_caller",
|
||
):
|
||
continue
|
||
if v is not None:
|
||
std_msg_parts.append(f"{k}={v}")
|
||
|
||
log_message = " ".join(std_msg_parts)
|
||
|
||
exc_info = fields.get("exc_info")
|
||
if exc_info is None:
|
||
if sys.exc_info()[0] is not None:
|
||
exc_info = sys.exc_info()
|
||
|
||
level = getattr(logging, log_level, logging.INFO)
|
||
extra_data = {
|
||
"caller": caller_info,
|
||
"suppress_console_output": True,
|
||
"suppress_file_output": True,
|
||
}
|
||
if exc_info:
|
||
root_logger.log(
|
||
level, log_message, exc_info=exc_info, extra=extra_data
|
||
)
|
||
else:
|
||
root_logger.log(level, log_message, extra=extra_data)
|
||
except Exception:
|
||
pass
|