把 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>
217 lines
7.7 KiB
Python
217 lines
7.7 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,
|
||
)
|
||
|
||
|
||
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
|