拆分 douyin_logging_wrapper (1080 → 6 个子模块 + 59 行 shim)
把 douyin/logging/douyin_logging_wrapper.py 的 LoggingWrapper 类(8 个
@staticmethod)按职责拆成 douyin/logging/douyin_logging_wrapper_pkg/ 子包:
- _common (76) 共享:colorama / 占位类 / 模块实例
- enhanced (380) enhanced_log_kv 主入口
- simple (216) _enhanced_log_kv_simple 简化版
- detailed (356) _enhanced_log_kv_detailed 详细版(最大头)
- misc (151) 5 个小型辅助方法(log_step_time / log_error_with_context /
log_performance_step / log_debug_info / get_performance_stats)
- wrapper (55) LoggingWrapper 类(薄壳,每个方法 1 行 forwarding)
策略:8 个方法全是 @staticmethod 第一参数 analyser,搬到 module-level 后
类方法变成 1 行 forwarding。类内部互调(enhanced_log_kv → simple/detailed,
log_error_with_context → enhanced_log_kv)改为直接 import module-level 函数。
外部 import 路径不变:
``from douyin.logging.douyin_logging_wrapper import LoggingWrapper`` 仍可用
(原文件改成 59 行 re-export shim,含 18 个共享符号 / 4 个占位类)。
回归:
- 7 个新文件 + shim compileall 通过
- pytest 353 passed / 1 skipped
- LoggingWrapper.get_performance_stats / module-level 函数 / Fore/Style 占位
全部能正常调用
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
1 parent
85bd488f66
commit
4ab1b88fa0
8 files changed
+1356
-1077
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,66 @@
|
||||
"""douyin_logging_wrapper_pkg - 日志包装器子包。
|
||||
|
||||
原 douyin/logging/douyin_logging_wrapper.py 拆成 6 个子模块:
|
||||
|
||||
- _common 共享:colorama / 占位类 / 模块实例
|
||||
- enhanced enhanced_log_kv 主入口
|
||||
- simple _enhanced_log_kv_simple 简化版
|
||||
- detailed _enhanced_log_kv_detailed 详细版(最大头)
|
||||
- misc 5 个小型日志辅助方法
|
||||
- wrapper LoggingWrapper 类(薄壳)
|
||||
|
||||
外部 import 路径不变:
|
||||
``from douyin.logging.douyin_logging_wrapper import LoggingWrapper`` 仍可用
|
||||
(原文件改成 re-export shim)。
|
||||
"""
|
||||
|
||||
from ._common import (
|
||||
COLORAMA_AVAILABLE,
|
||||
Fore,
|
||||
LOGGING_MODULES_AVAILABLE,
|
||||
Style,
|
||||
ActionLogger,
|
||||
DebugLogger,
|
||||
ErrorLogger,
|
||||
PerformanceTracker,
|
||||
_action_logger,
|
||||
_debug_logger,
|
||||
_error_logger,
|
||||
_performance_tracker,
|
||||
)
|
||||
from .enhanced import enhanced_log_kv
|
||||
from .simple import _enhanced_log_kv_simple
|
||||
from .detailed import _enhanced_log_kv_detailed
|
||||
from .misc import (
|
||||
get_performance_stats,
|
||||
log_debug_info,
|
||||
log_error_with_context,
|
||||
log_performance_step,
|
||||
log_step_time,
|
||||
)
|
||||
from .wrapper import LoggingWrapper
|
||||
|
||||
__all__ = [
|
||||
"LoggingWrapper",
|
||||
"enhanced_log_kv",
|
||||
"_enhanced_log_kv_simple",
|
||||
"_enhanced_log_kv_detailed",
|
||||
"log_step_time",
|
||||
"log_error_with_context",
|
||||
"log_performance_step",
|
||||
"log_debug_info",
|
||||
"get_performance_stats",
|
||||
# 共享对象(兼容原文件 module-level 暴露)
|
||||
"COLORAMA_AVAILABLE",
|
||||
"LOGGING_MODULES_AVAILABLE",
|
||||
"Fore",
|
||||
"Style",
|
||||
"ErrorLogger",
|
||||
"DebugLogger",
|
||||
"ActionLogger",
|
||||
"PerformanceTracker",
|
||||
"_error_logger",
|
||||
"_debug_logger",
|
||||
"_action_logger",
|
||||
"_performance_tracker",
|
||||
]
|
||||
@@ -0,0 +1,76 @@
|
||||
from __future__ import annotations
|
||||
|
||||
"""douyin_logging_wrapper_pkg._common - 共享:colorama / 占位类 / 模块实例。
|
||||
|
||||
被本子包的所有方法子模块共用。
|
||||
"""
|
||||
|
||||
import sys
|
||||
|
||||
# 导入 colorama 用于颜色支持
|
||||
try:
|
||||
from colorama import Fore, Style, init
|
||||
|
||||
init(autoreset=True)
|
||||
COLORAMA_AVAILABLE = True
|
||||
except ImportError:
|
||||
# 如果没有 colorama,使用 ANSI 转义序列
|
||||
class Fore:
|
||||
RED = "\033[31m"
|
||||
GREEN = "\033[32m"
|
||||
YELLOW = "\033[33m"
|
||||
BLUE = "\033[34m"
|
||||
MAGENTA = "\033[35m"
|
||||
CYAN = "\033[36m"
|
||||
WHITE = "\033[37m"
|
||||
LIGHTRED_EX = "\033[91m"
|
||||
LIGHTGREEN_EX = "\033[92m"
|
||||
LIGHTYELLOW_EX = "\033[93m"
|
||||
LIGHTBLUE_EX = "\033[94m"
|
||||
LIGHTMAGENTA_EX = "\033[95m"
|
||||
LIGHTCYAN_EX = "\033[96m"
|
||||
LIGHTWHITE_EX = "\033[97m"
|
||||
|
||||
class Style:
|
||||
RESET_ALL = "\033[0m"
|
||||
BRIGHT = "\033[1m"
|
||||
|
||||
COLORAMA_AVAILABLE = False
|
||||
|
||||
|
||||
# 导入所有日志模块
|
||||
try:
|
||||
from douyin.logging.internal_loggers import ErrorLogger, DebugLogger # type: ignore[assignment]
|
||||
from douyin.logging.action_logger import ActionLogger # type: ignore[assignment]
|
||||
from douyin.logging.performance_tracker import PerformanceTracker # type: ignore[assignment]
|
||||
|
||||
LOGGING_MODULES_AVAILABLE = True
|
||||
except ImportError:
|
||||
# 如果导入失败,提供占位符类
|
||||
class ErrorLogger:
|
||||
def log_exception(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
class DebugLogger:
|
||||
def log_variable(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
class ActionLogger:
|
||||
def log_step(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
class PerformanceTracker:
|
||||
def end_timer(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def get_statistics(self, *args, **kwargs):
|
||||
return {}
|
||||
|
||||
LOGGING_MODULES_AVAILABLE = False
|
||||
|
||||
|
||||
# 初始化日志模块实例
|
||||
_error_logger = ErrorLogger()
|
||||
_debug_logger = DebugLogger()
|
||||
_action_logger = ActionLogger()
|
||||
_performance_tracker = PerformanceTracker()
|
||||
@@ -0,0 +1,356 @@
|
||||
"""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_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
|
||||
@@ -0,0 +1,380 @@
|
||||
"""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 .detailed import _enhanced_log_kv_detailed
|
||||
|
||||
|
||||
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))
|
||||
|
||||
# 构建完整日志行
|
||||
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
|
||||
|
||||
# 根据模式决定日志格式
|
||||
if log_format_mode == "detailed":
|
||||
# 详细模式:保留之前的复杂格式
|
||||
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,
|
||||
)
|
||||
@@ -0,0 +1,151 @@
|
||||
"""douyin_logging_wrapper_pkg.misc - 5 个小型日志辅助方法。
|
||||
|
||||
- log_step_time 记录步骤耗时
|
||||
- log_error_with_context 记录带上下文的错误
|
||||
- log_performance_step 记录性能步骤
|
||||
- log_debug_info 记录调试信息
|
||||
- get_performance_stats 获取性能统计快照
|
||||
"""
|
||||
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 .enhanced import enhanced_log_kv as _enhanced_log_kv
|
||||
|
||||
|
||||
def log_step_time(
|
||||
analyser: Any,
|
||||
step_name: str,
|
||||
start_time: float,
|
||||
extra_info: Optional[Dict[str, Any]] = None,
|
||||
) -> None:
|
||||
"""记录某个子步骤的耗时(供检测模块调用,减少日志噪音)。
|
||||
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
step_name: 步骤名称
|
||||
start_time: 开始时间(时间戳)
|
||||
extra_info: 额外信息字典
|
||||
"""
|
||||
try:
|
||||
elapsed = time.time() - float(start_time or 0.0)
|
||||
except Exception:
|
||||
elapsed = 0.0
|
||||
fields: Dict[str, Any] = {"seconds": elapsed}
|
||||
if extra_info:
|
||||
for k, v in extra_info.items():
|
||||
fields[str(k)] = v
|
||||
try:
|
||||
analyser._log_kv("步骤耗时", step_name, **fields) # type: ignore[attr-defined]
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
|
||||
|
||||
def log_error_with_context(
|
||||
analyser: Any,
|
||||
exc: BaseException,
|
||||
context: Optional[Dict[str, Any]] = None,
|
||||
level: str = "ERROR",
|
||||
) -> None:
|
||||
"""使用错误日志模块记录异常及上下文信息"""
|
||||
if LOGGING_MODULES_AVAILABLE and _error_logger:
|
||||
try:
|
||||
_error_logger.log_exception(exc, context=context, level=level)
|
||||
except Exception:
|
||||
pass # 错误日志记录失败不应该影响主流程
|
||||
|
||||
# 同时记录到标准日志
|
||||
_enhanced_log_kv(
|
||||
analyser,
|
||||
"错误",
|
||||
f"{type(exc).__name__}: {exc}",
|
||||
level=level,
|
||||
exception_type=type(exc).__name__,
|
||||
exception_message=str(exc),
|
||||
context=context or {},
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
|
||||
|
||||
def log_performance_step(
|
||||
analyser: Any,
|
||||
step_name: str,
|
||||
elapsed_seconds: float,
|
||||
details: Optional[Dict[str, Any]] = None,
|
||||
) -> None:
|
||||
"""记录性能步骤信息"""
|
||||
if LOGGING_MODULES_AVAILABLE and _performance_tracker:
|
||||
try:
|
||||
# 记录到性能追踪器
|
||||
_performance_tracker.end_timer(f"{step_name}-{int(time.time()*1000)}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 记录到行为日志
|
||||
if LOGGING_MODULES_AVAILABLE and _action_logger:
|
||||
try:
|
||||
_action_logger.log_step(step_name, elapsed=elapsed_seconds)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 记录到标准日志
|
||||
fields = {"elapsed_seconds": elapsed_seconds}
|
||||
if details:
|
||||
fields.update(details)
|
||||
|
||||
_enhanced_log_kv(
|
||||
analyser, "性能", f"步骤完成: {step_name}", **fields
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
|
||||
|
||||
def log_debug_info(analyser: Any, message: str, **context: Any) -> None:
|
||||
"""记录调试信息"""
|
||||
if LOGGING_MODULES_AVAILABLE and _debug_logger:
|
||||
try:
|
||||
# 这里可以扩展为更详细的调试信息记录
|
||||
_debug_logger.log_variable("debug_message", message)
|
||||
for key, value in context.items():
|
||||
_debug_logger.log_variable(key, value)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 记录到标准日志
|
||||
_enhanced_log_kv(
|
||||
analyser, "调试", message, level="DEBUG", **context
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
|
||||
|
||||
def get_performance_stats() -> Dict[str, Any]:
|
||||
"""获取性能统计信息"""
|
||||
if LOGGING_MODULES_AVAILABLE and _performance_tracker:
|
||||
try:
|
||||
return _performance_tracker.get_statistics()
|
||||
except Exception:
|
||||
pass
|
||||
return {}
|
||||
@@ -0,0 +1,216 @@
|
||||
"""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,
|
||||
)
|
||||
|
||||
|
||||
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:
|
||||
"""简洁模式的日志记录"""
|
||||
# 输出分隔符(如果需要)- 使用更简洁的分隔符
|
||||
if need_separator:
|
||||
try:
|
||||
separator = f"=== {separator_reason} ==="
|
||||
print(separator, flush=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 更新上一个日志标签
|
||||
analyser._last_log_tag = tag
|
||||
|
||||
# 构建简洁的日志行
|
||||
log_line = " ".join(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) # flush=True 确保立即输出,不缓冲
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 简化行为日志记录,避免重复输出
|
||||
try:
|
||||
# 只在重要事件时写入行为日志
|
||||
should_log_action = False
|
||||
if tag and any(
|
||||
keyword in str(tag)
|
||||
for keyword in ["参与", "中奖", "完成", "失败", "运行"]
|
||||
):
|
||||
should_log_action = True
|
||||
|
||||
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_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
|
||||
@@ -0,0 +1,55 @@
|
||||
"""douyin_logging_wrapper_pkg.wrapper - LoggingWrapper 类(薄壳)。
|
||||
|
||||
每个方法都是 @staticmethod 的 1 行 forwarding。
|
||||
外部 LoggingWrapper.method(...) 的代码完全不需要改。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from .enhanced import enhanced_log_kv as _enhanced_log_kv
|
||||
from .simple import _enhanced_log_kv_simple as __simple
|
||||
from .detailed import _enhanced_log_kv_detailed as __detailed
|
||||
from .misc import (
|
||||
log_step_time as _log_step_time,
|
||||
log_error_with_context as _log_error_with_context,
|
||||
log_performance_step as _log_performance_step,
|
||||
log_debug_info as _log_debug_info,
|
||||
get_performance_stats as _get_performance_stats,
|
||||
)
|
||||
|
||||
|
||||
class LoggingWrapper:
|
||||
"""日志包装器:统一管理日志功能(薄壳,转发到 module-level 函数)。"""
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def enhanced_log_kv(*args, **kwargs) -> None:
|
||||
return _enhanced_log_kv(*args, **kwargs)
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def _enhanced_log_kv_simple(*args, **kwargs) -> None:
|
||||
return __simple(*args, **kwargs)
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def _enhanced_log_kv_detailed(*args, **kwargs) -> None:
|
||||
return __detailed(*args, **kwargs)
|
||||
|
||||
@staticmethod
|
||||
def log_step_time(*args, **kwargs) -> None:
|
||||
return _log_step_time(*args, **kwargs)
|
||||
|
||||
@staticmethod
|
||||
def log_error_with_context(*args, **kwargs) -> None:
|
||||
return _log_error_with_context(*args, **kwargs)
|
||||
|
||||
@staticmethod
|
||||
def log_performance_step(*args, **kwargs) -> None:
|
||||
return _log_performance_step(*args, **kwargs)
|
||||
|
||||
@staticmethod
|
||||
def log_debug_info(*args, **kwargs) -> None:
|
||||
return _log_debug_info(*args, **kwargs)
|
||||
|
||||
@staticmethod
|
||||
def get_performance_stats() -> Dict[str, Any]:
|
||||
return _get_performance_stats()
|
||||
Reference in new issue
Block a user