399 lines
13 KiB
Python
399 lines
13 KiB
Python
"""douyin_logging_wrapper_pkg.simple - _enhanced_log_kv_simple 简化版日志记录。"""
|
||
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,
|
||
)
|
||
|
||
_SIMPLE_NOISE_LOG_TYPES = {"DEBUG", "PERF", "SCREENSHOT", "FLOW", "OCR_SUMMARY"}
|
||
_SIMPLE_NOISE_TAGS = {
|
||
"OCR",
|
||
"OCR摘要",
|
||
"性能",
|
||
"验证",
|
||
"流程标志",
|
||
"调试图像",
|
||
"步骤耗时",
|
||
"福袋倒计时",
|
||
"[性能]",
|
||
"[验证]",
|
||
"[流程标志]",
|
||
"[调试图像]",
|
||
"[步骤耗时]",
|
||
"[福袋倒计时]",
|
||
}
|
||
_SIMPLE_NOISE_PATTERNS = (
|
||
"[FLOW_FLAG]",
|
||
"OCR摘要",
|
||
"OCR调试(",
|
||
"OCR识别任务列表区域",
|
||
"OCR结果完全为空",
|
||
"分割识别失败",
|
||
"result[0] keys=",
|
||
"dt_polys",
|
||
"rec_texts",
|
||
"调试图像",
|
||
"综合标注图已保存",
|
||
"像素阶段总览保存",
|
||
"关键耗时",
|
||
"read_fudai_detail_once:",
|
||
)
|
||
_SIMPLE_MAX_LINE_LEN = 150
|
||
|
||
|
||
def _should_write_simple_action(tag: str, msg: str, fields: Dict[str, Any]) -> bool:
|
||
tag_text = str(tag or "")
|
||
msg_text = str(msg or "")
|
||
decision = str(fields.get("decision", "") or "")
|
||
action = str(fields.get("action", "") or "")
|
||
|
||
if "福袋查找" in tag_text and ("检测完成" in tag_text or "检测完成" in msg_text):
|
||
return False
|
||
if decision == "button_ocr_state_only":
|
||
return False
|
||
if decision.endswith("_click_sent") or action:
|
||
return True
|
||
return bool(
|
||
tag_text
|
||
and any(keyword in tag_text for keyword in ["参与", "中奖", "完成", "失败", "运行"])
|
||
)
|
||
|
||
|
||
def _clean_simple_tag(tag: str) -> str:
|
||
return str(tag or "").strip().strip("[]").strip()
|
||
|
||
|
||
def _should_skip_simple_stdout(
|
||
tag: str,
|
||
msg: str,
|
||
log_level: str,
|
||
fields: Dict[str, Any],
|
||
log_line: str,
|
||
) -> bool:
|
||
"""Simple 模式只显示业务状态;调试/性能细节留给 detailed/debug。"""
|
||
if fields.get("exc_info") is not None:
|
||
return False
|
||
|
||
level = str(log_level or "").upper()
|
||
if level in {"ERROR", "CRITICAL"}:
|
||
return False
|
||
|
||
tag_clean = _clean_simple_tag(tag)
|
||
|
||
log_type = str(fields.get("_log_type", "") or "").upper()
|
||
text = f"{tag} {msg} {log_line}"
|
||
|
||
is_noise = (
|
||
tag_clean in _SIMPLE_NOISE_TAGS
|
||
or log_type in _SIMPLE_NOISE_LOG_TYPES
|
||
or any(pattern in text for pattern in _SIMPLE_NOISE_PATTERNS)
|
||
)
|
||
if level == "WARNING":
|
||
return is_noise
|
||
|
||
if is_noise:
|
||
return True
|
||
|
||
return False
|
||
|
||
|
||
def _compact_simple_line(log_line: str) -> str:
|
||
if len(log_line) <= _SIMPLE_MAX_LINE_LEN:
|
||
return log_line
|
||
return log_line[: _SIMPLE_MAX_LINE_LEN - 3].rstrip() + "..."
|
||
|
||
|
||
def _format_simple_stdout_line(
|
||
tag: str,
|
||
msg: str,
|
||
log_level: str,
|
||
timestamp: str,
|
||
fields: Dict[str, Any],
|
||
fallback_line: str,
|
||
) -> str:
|
||
"""日常模式只保留短时间、标签、业务消息和少量结果字段。"""
|
||
parts: list[str] = []
|
||
if timestamp:
|
||
parts.append(f"[{timestamp[-12:-4]}]")
|
||
|
||
level = str(log_level or "INFO").upper()
|
||
if level not in {"INFO", ""}:
|
||
parts.append(f"[{level}]")
|
||
|
||
tag_clean = _clean_simple_tag(tag)
|
||
if tag_clean:
|
||
parts.append(f"[{tag_clean}]")
|
||
|
||
msg_clean = str(msg or "").replace("\r", " ").replace("\n", " ").strip()
|
||
if msg_clean:
|
||
parts.append(msg_clean[:80])
|
||
|
||
key_map = {
|
||
"elapsed_seconds": "耗时",
|
||
"elapsed_ms": "耗时",
|
||
"value_yuan": "价值",
|
||
"room_pos": "位置",
|
||
"future_ts": "开奖",
|
||
"actual_remaining_seconds": "剩余",
|
||
"实际_剩余秒数": "剩余",
|
||
"实际_价值": "价值",
|
||
"实际_内容": "内容",
|
||
"button_text": "按钮",
|
||
"按钮文本": "按钮",
|
||
"error": "错误",
|
||
}
|
||
field_parts: list[str] = []
|
||
for key in (
|
||
"value_yuan",
|
||
"实际_价值",
|
||
"actual_remaining_seconds",
|
||
"实际_剩余秒数",
|
||
"button_text",
|
||
"按钮文本",
|
||
"room_pos",
|
||
"elapsed_seconds",
|
||
"elapsed_ms",
|
||
"error",
|
||
):
|
||
if key not in fields or fields.get(key) is None:
|
||
continue
|
||
value = fields.get(key)
|
||
if isinstance(value, float):
|
||
if "seconds" in key or "剩余" in key:
|
||
value_str = f"{value:.0f}s"
|
||
elif "ms" in key:
|
||
value_str = f"{value:.0f}ms"
|
||
elif "价值" in key or "yuan" in key:
|
||
value_str = f"{value:.0f}元"
|
||
else:
|
||
value_str = f"{value:.1f}"
|
||
else:
|
||
value_str = str(value).strip()
|
||
if not value_str:
|
||
continue
|
||
field_parts.append(f"{key_map.get(key, key)}={value_str[:36]}")
|
||
|
||
if field_parts:
|
||
parts.append(" ".join(field_parts[:4]))
|
||
|
||
line = " ".join(parts).strip() or fallback_line
|
||
return _compact_simple_line(line)
|
||
|
||
|
||
def _enhanced_log_kv_simple(
|
||
analyser: Any,
|
||
tag: str,
|
||
msg: str,
|
||
log_level: str,
|
||
log_parts: list[str],
|
||
timestamp: str,
|
||
fields: Dict[str, Any],
|
||
need_separator: bool,
|
||
separator_reason: str,
|
||
color: Optional[str] = None,
|
||
) -> None:
|
||
"""简洁模式的日志记录"""
|
||
fallback_line = _compact_simple_line(" ".join(log_parts))
|
||
if _should_skip_simple_stdout(tag, msg, log_level, fields, fallback_line):
|
||
return
|
||
log_line = _format_simple_stdout_line(
|
||
tag,
|
||
msg,
|
||
log_level,
|
||
timestamp,
|
||
fields,
|
||
fallback_line,
|
||
)
|
||
|
||
# 输出分隔符(如果需要)- 使用更简洁的分隔符
|
||
if need_separator:
|
||
try:
|
||
separator = f"=== {separator_reason} ==="
|
||
print(separator, flush=True)
|
||
except Exception:
|
||
pass
|
||
|
||
# 更新上一个日志标签
|
||
analyser._last_log_tag = tag
|
||
|
||
# 应用颜色(如果指定了颜色)
|
||
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) # flush=True 确保立即输出,不缓冲
|
||
except Exception:
|
||
pass
|
||
|
||
# 简化行为日志记录,避免重复输出
|
||
try:
|
||
# 只在重要事件时写入行为日志
|
||
should_log_action = _should_write_simple_action(tag, msg, fields)
|
||
|
||
if should_log_action:
|
||
# 获取时间戳
|
||
if not timestamp:
|
||
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
|
||
|
||
# 构建简洁的行为日志
|
||
action_parts = [f"[{timestamp}]"]
|
||
if tag:
|
||
action_parts.append(f"[{tag}]")
|
||
if msg:
|
||
action_parts.append(msg[:100]) # 限制长度
|
||
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)
|
||
|
||
with open(
|
||
actions_log_path,
|
||
"a",
|
||
encoding="utf-8-sig",
|
||
errors="replace",
|
||
) as f:
|
||
f.write(action_log_line + "\n")
|
||
f.flush()
|
||
# 同步调用行为日志模块以获得结构化记录
|
||
try:
|
||
if LOGGING_MODULES_AVAILABLE and _action_logger:
|
||
# 提取耗时(统一为秒传入 ActionLogger)
|
||
elapsed_seconds = None
|
||
try:
|
||
if "elapsed_ms" in fields:
|
||
elapsed_seconds = (
|
||
float(fields.get("elapsed_ms", 0)) / 1000.0
|
||
)
|
||
elif "total_elapsed_ms" in fields:
|
||
elapsed_seconds = (
|
||
float(fields.get("total_elapsed_ms", 0)) / 1000.0
|
||
)
|
||
elif "total_ms" in fields:
|
||
elapsed_seconds = (
|
||
float(fields.get("total_ms", 0)) / 1000.0
|
||
)
|
||
elif "elapsed_seconds" in fields:
|
||
elapsed_seconds = float(
|
||
fields.get("elapsed_seconds", 0)
|
||
)
|
||
elif "seconds" in fields:
|
||
elapsed_seconds = float(fields.get("seconds", 0))
|
||
except Exception:
|
||
elapsed_seconds = None
|
||
|
||
# 构建额外字段(保留分数、价值、位置信息)
|
||
extra = {}
|
||
for k in ("score", "value_yuan", "room_pos", "fudai_x", "rid"):
|
||
if k in fields:
|
||
extra[k] = fields.get(k)
|
||
|
||
try:
|
||
op_name = tag if tag else "操作"
|
||
details = msg if msg else None
|
||
if elapsed_seconds is not None:
|
||
_action_logger.log_operation(
|
||
op_name,
|
||
details or "",
|
||
elapsed=elapsed_seconds,
|
||
**extra,
|
||
)
|
||
else:
|
||
_action_logger.log_operation(
|
||
op_name, details or "", **extra
|
||
)
|
||
except Exception:
|
||
pass
|
||
except Exception:
|
||
pass
|
||
except Exception:
|
||
pass
|
||
|
||
# 移除标准 logging 输出,避免与 stdout 重复
|
||
# 现在只通过 print 输出到控制台,行为日志只记录重要事件
|
||
|
||
# 如果有异常堆栈,也输出到 stdout
|
||
exc_info = fields.get("exc_info")
|
||
if exc_info is None:
|
||
if sys.exc_info()[0] is not None:
|
||
exc_info = sys.exc_info()
|
||
|
||
if exc_info:
|
||
try:
|
||
# exc_info 应该是 (type, value, traceback) 元组
|
||
if isinstance(exc_info, tuple) and len(exc_info) == 3:
|
||
exc_type, exc_value, exc_traceback = exc_info
|
||
# 确保 exc_value 是 BaseException 实例
|
||
if isinstance(exc_value, BaseException):
|
||
tb_str = traceback.format_exception(
|
||
exc_type, exc_value, exc_traceback
|
||
)
|
||
else:
|
||
# 如果不是异常实例,创建一个包装异常
|
||
try:
|
||
# 尝试使用原始值
|
||
tb_str = traceback.format_exception(
|
||
exc_type,
|
||
(
|
||
BaseException(str(exc_value))
|
||
if exc_value
|
||
else BaseException("Unknown error")
|
||
),
|
||
exc_traceback,
|
||
)
|
||
except Exception:
|
||
# 如果还是失败,只输出异常信息
|
||
print(
|
||
f" 异常类型: {exc_type}, 异常值: {exc_value}",
|
||
flush=True,
|
||
)
|
||
tb_str = []
|
||
for line in tb_str:
|
||
print(f" {line.rstrip()}", flush=True)
|
||
else:
|
||
# 如果不是标准格式,尝试直接格式化
|
||
try:
|
||
tb_str = traceback.format_exception(*exc_info)
|
||
for line in tb_str:
|
||
print(f" {line.rstrip()}", flush=True)
|
||
except Exception:
|
||
# 如果格式化失败,只输出异常信息
|
||
print(f" 异常信息: {exc_info}", flush=True)
|
||
except Exception:
|
||
pass
|