Refactor reservation preemption handling and logging
- Removed the reservation preempt minimum value from the Runner and GUI components. - Updated logging mechanism to streamline log message handling and improve readability. - Introduced a new method for appending log lines in the Runner class. - Cleaned up related GUI elements and configuration options in web interface. - Deleted obsolete simulation scripts related to reservation preemption checks.
This commit is contained in:
1 parent
eb96d6869e
commit
93d47a16d6
20 files changed
+786
-1051
No files matched your search
@@ -210,450 +210,163 @@ class LoggingWrapper:
|
||||
"back_times": "需回退次数",
|
||||
}
|
||||
|
||||
# 构建日志行(增强格式:时间 级别 标签 [调用者] 消息 字段...)
|
||||
# 构建简洁的日志行:时间 [级别] [标签] 消息 关键字段
|
||||
log_parts: list[str] = []
|
||||
if timestamp:
|
||||
log_parts.append(f"[{timestamp}]")
|
||||
log_parts.append(f"[{log_level}]")
|
||||
log_parts.append(f"[{tag}]")
|
||||
# 如果有 log_type,则在可读日志中加入类型标记,方便过滤与配色
|
||||
if log_type:
|
||||
log_parts.append(f"[{log_type}]")
|
||||
|
||||
# 添加调用者信息(如果获取成功)
|
||||
if caller_info:
|
||||
log_parts.append(f"[{caller_info}]")
|
||||
if tag and tag != "日志":
|
||||
log_parts.append(f"[{tag}]")
|
||||
|
||||
if msg:
|
||||
m = str(msg).replace("\r", " ").replace("\n", " ").strip()
|
||||
if len(m) > 200:
|
||||
m = m[:200] + "..."
|
||||
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
|
||||
key_cn = key_map.get(str(k), f"字段_{k}")
|
||||
# 格式化值
|
||||
if isinstance(v, float):
|
||||
if abs(v) < 1:
|
||||
v_str = f"{v:.3f}"
|
||||
elif abs(v) < 100:
|
||||
v_str = f"{v:.2f}"
|
||||
# 只显示关键字段:耗时、价值、错误等
|
||||
if k in ("elapsed_seconds", "value_yuan", "error", "room_pos", "future_ts"):
|
||||
key_cn = key_map.get(str(k), k)
|
||||
if isinstance(v, float):
|
||||
if "seconds" in k or "elapsed" in k:
|
||||
v_str = f"{v:.1f}s"
|
||||
elif "yuan" in k:
|
||||
v_str = f"{v:.0f}元"
|
||||
else:
|
||||
v_str = f"{v:.1f}"
|
||||
else:
|
||||
v_str = f"{int(v)}"
|
||||
elif isinstance(v, (int, bool)):
|
||||
v_str = str(v)
|
||||
else:
|
||||
s = str(v).replace("\r", " ").replace("\n", " ").strip()
|
||||
if len(s) > 100:
|
||||
s = s[:100] + "..."
|
||||
v_str = s
|
||||
log_parts.append(f"{key_cn}={v_str}")
|
||||
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
|
||||
|
||||
# 1. 错误发生时(优先级最高)
|
||||
if log_level in ("ERROR", "WARNING", "CRITICAL"):
|
||||
# 只在错误或非常重要的阶段变化时添加分隔符,避免日志过于冗余
|
||||
if log_level in ("ERROR", "CRITICAL"):
|
||||
need_separator = True
|
||||
separator_reason = "错误/警告"
|
||||
|
||||
# 2. 运行开始时
|
||||
elif tag and any(
|
||||
keyword in str(tag) for keyword in ["运行", "启动", "开始", "初始化"]
|
||||
):
|
||||
separator_reason = f"错误: {tag or '系统'}"
|
||||
elif tag_changed and tag in ("运行", "启动", "完成"):
|
||||
need_separator = True
|
||||
separator_reason = "运行开始"
|
||||
separator_reason = tag
|
||||
|
||||
# 3. 阶段变化时(tag变化且包含阶段相关关键词)
|
||||
elif tag and getattr(analyser, "_last_log_tag", None) != tag:
|
||||
if any(
|
||||
keyword in str(tag)
|
||||
for keyword in ["阶段", "循环", "参与", "检测", "寻找", "进入", "退出"]
|
||||
):
|
||||
need_separator = True
|
||||
separator_reason = "阶段变化"
|
||||
|
||||
# 4. 重要操作(通过tag判断)
|
||||
elif tag and getattr(analyser, "_last_log_tag", None) != tag:
|
||||
if any(
|
||||
keyword in str(tag)
|
||||
for keyword in ["参与", "中奖", "完成", "失败", "超时"]
|
||||
):
|
||||
need_separator = True
|
||||
separator_reason = "重要操作"
|
||||
|
||||
# 输出分隔符(如果需要)
|
||||
# 输出分隔符(如果需要)- 使用更简洁的分隔符
|
||||
if need_separator:
|
||||
try:
|
||||
# 使用等号作为分隔符,更清晰易读
|
||||
separator = "=" * 80
|
||||
# 在分隔符中间显示原因,更美观
|
||||
reason_text = f" {separator_reason} "
|
||||
separator_line = (
|
||||
f"{separator}\n{reason_text.center(80, '=')}\n{separator}"
|
||||
)
|
||||
print(separator_line, flush=True)
|
||||
separator = f"=== {separator_reason} ==="
|
||||
print(separator, flush=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 更新上一个日志标签
|
||||
analyser._last_log_tag = tag
|
||||
|
||||
# 获取日志格式模式配置(simple 或 detailed)
|
||||
log_format_mode = "simple" # 默认简洁模式
|
||||
try:
|
||||
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 LoggingWrapper._enhanced_log_kv_detailed(analyser, tag, msg, log_level, log_type, log_parts, timestamp, caller_info, fields, need_separator, separator_reason)
|
||||
else:
|
||||
# 简洁模式:使用优化后的格式
|
||||
return LoggingWrapper._enhanced_log_kv_simple(analyser, tag, msg, log_level, log_parts, timestamp, fields, need_separator, separator_reason)
|
||||
|
||||
@staticmethod
|
||||
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) -> 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)
|
||||
|
||||
# 始终输出到 stdout(供 GUI 捕获)- 这是最重要的!
|
||||
try:
|
||||
print(log_line, flush=True) # flush=True 确保立即输出,不缓冲
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 写入行为日志(actions.log)- 使用运行日志格式,但只保留关键信息
|
||||
# 记录所有操作到行为日志
|
||||
# 简化行为日志记录,避免重复输出
|
||||
try:
|
||||
# 判断是否需要记录(记录所有操作,但可以过滤一些噪音日志)
|
||||
should_log = True
|
||||
# 只在重要事件时写入行为日志
|
||||
should_log_action = False
|
||||
if tag and any(keyword in str(tag) for keyword in ["参与", "中奖", "完成", "失败", "运行"]):
|
||||
should_log_action = True
|
||||
|
||||
# 过滤一些不需要记录的日志(避免噪音)
|
||||
if tag:
|
||||
# 跳过一些调试或详细日志
|
||||
skip_tags = ["[调试图像]", "[步骤耗时]"]
|
||||
for skip_tag in skip_tags:
|
||||
if tag.startswith(skip_tag):
|
||||
should_log = False
|
||||
break
|
||||
|
||||
if should_log:
|
||||
if should_log_action:
|
||||
# 获取时间戳
|
||||
if not timestamp:
|
||||
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
|
||||
|
||||
# 提取关键信息:做了什么、耗时、分数
|
||||
# 如果msg为空,从tag中提取操作描述
|
||||
if msg:
|
||||
action_desc = str(msg)
|
||||
# 移除函数名:匹配 "函数名:" 或 "函数名 " 格式
|
||||
# 先移除带冒号的函数名
|
||||
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 = str(msg)
|
||||
# 简化描述:移除字段前缀,只保留关键信息
|
||||
if "字段_" in action_desc:
|
||||
# 提取阶段信息(如果有)
|
||||
if "字段_阶段=" in action_desc:
|
||||
stage_match = re.search(r"字段_阶段=(\w+)", action_desc)
|
||||
if stage_match:
|
||||
action_desc = f"阶段={stage_match.group(1)}"
|
||||
else:
|
||||
# 简化其他字段描述,只保留消息部分
|
||||
action_desc = action_desc.split("字段_")[0].strip()
|
||||
else:
|
||||
# 从tag中提取操作类型(移除标签的方括号)
|
||||
if tag:
|
||||
tag_clean = tag.strip("[]").strip()
|
||||
if tag_clean:
|
||||
action_desc = tag_clean
|
||||
else:
|
||||
action_desc = "操作"
|
||||
else:
|
||||
action_desc = "操作"
|
||||
|
||||
# 归一化字段名,支持以 '字段_' 前缀的字段名向后兼容
|
||||
fields_clean: Dict[str, Any] = {}
|
||||
for k, v in fields.items():
|
||||
kk = str(k)
|
||||
if kk.startswith("字段_"):
|
||||
kk = kk[len("字段_") :]
|
||||
fields_clean[kk] = v
|
||||
|
||||
# 提取耗时(从字段中查找,优先使用毫秒字段)
|
||||
elapsed_str = ""
|
||||
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 "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 "总耗时毫秒" in fields_clean:
|
||||
elapsed_seconds = float(fields_clean.get("总耗时毫秒", 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
|
||||
elif (
|
||||
"max_val" in fields_clean
|
||||
and fields_clean.get("max_val") is not None
|
||||
):
|
||||
try:
|
||||
score_val = float(fields_clean.get("max_val", 0))
|
||||
score_str = f"分数:{score_val:.3f}"
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
elif "分数" in fields_clean:
|
||||
score_field = fields_clean.get("分数")
|
||||
# 允许显示0.0分数,只要不是None
|
||||
if score_field is not None:
|
||||
try:
|
||||
score_val = float(score_field)
|
||||
score_str = f"分数:{score_val:.3f}"
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
# 构建精简的行为日志行,使用运行日志格式:时间 - [GUI] - [标签] 做了什么 耗时:XXs 分数:XX
|
||||
action_parts = [timestamp, "-", "[GUI]", "-"]
|
||||
# 构建简洁的行为日志
|
||||
action_parts = [f"[{timestamp}]"]
|
||||
if tag:
|
||||
action_parts.append(tag)
|
||||
else:
|
||||
action_parts.append("[日志]")
|
||||
|
||||
# 在行为日志中也写入类型标签,便于按类型过滤(例如 ERR/DEBUG/SCREENSHOT/PERF/OP)
|
||||
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_parts.append(f"[{tag}]")
|
||||
if msg:
|
||||
action_parts.append(msg[:100]) # 限制长度
|
||||
action_log_line = " ".join(action_parts)
|
||||
|
||||
# 写入 actions.log 文件
|
||||
# 使用统一的路径配置
|
||||
try:
|
||||
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(由 RotatingFileHandler 管理)
|
||||
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()
|
||||
with open(
|
||||
actions_log_path,
|
||||
"a",
|
||||
encoding="utf-8-sig",
|
||||
errors="replace",
|
||||
) as f:
|
||||
f.write(action_log_line + "\n")
|
||||
f.flush()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 同时输出到标准 logging(如果已配置,可选)
|
||||
try:
|
||||
# 确保日志系统已配置
|
||||
import logging
|
||||
|
||||
root_logger = logging.getLogger()
|
||||
if not root_logger.handlers:
|
||||
# 如果根 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 unified_logger import get_unified_logger
|
||||
|
||||
analyser._std_logger = get_unified_logger("douyin.fudai")
|
||||
except ImportError:
|
||||
try:
|
||||
from douyin.logging import douyin_logger
|
||||
|
||||
analyser._std_logger = douyin_logger.get_logger("douyin")
|
||||
except Exception:
|
||||
# 如果都失败了,使用根 logger
|
||||
analyser._std_logger = logging.getLogger("douyin.fudai")
|
||||
|
||||
# 使用根 logger 确保日志能写入文件(子 logger 会传播到根 logger)
|
||||
root_logger = logging.getLogger()
|
||||
if root_logger.handlers:
|
||||
# 如果根 logger 有 handlers,使用根 logger 写入(确保能写入文件)
|
||||
# 构建标准 logging 消息(包含调用者信息)
|
||||
std_msg_parts = [f"[{tag}]"]
|
||||
if caller_info:
|
||||
std_msg_parts.append(f"[调用:{caller_info}]")
|
||||
if msg:
|
||||
# 对消息进行敏感信息脱敏
|
||||
try:
|
||||
from 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 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()
|
||||
|
||||
# 记录到根 logger(确保能写入文件)
|
||||
# 优化:只写入文件,不输出到控制台(避免与 print 重复)
|
||||
level = getattr(logging, log_level, logging.INFO)
|
||||
# 临时禁用控制台输出,只写入文件
|
||||
console_handlers = [
|
||||
h
|
||||
for h in root_logger.handlers
|
||||
if isinstance(h, logging.StreamHandler) and h.stream == sys.stdout
|
||||
]
|
||||
# 保存原始级别并在 finally 中恢复,确保在异常路径也能正确还原
|
||||
original_levels = {}
|
||||
for handler in console_handlers:
|
||||
try:
|
||||
original_levels[id(handler)] = getattr(
|
||||
handler, "level", logging.NOTSET
|
||||
)
|
||||
handler.setLevel(logging.CRITICAL + 1) # 临时禁用
|
||||
except Exception:
|
||||
# 如果无法修改某个 handler,跳过但继续记录
|
||||
continue
|
||||
|
||||
try:
|
||||
if exc_info:
|
||||
root_logger.log(
|
||||
level,
|
||||
log_message,
|
||||
exc_info=exc_info,
|
||||
extra={"caller": caller_info},
|
||||
)
|
||||
else:
|
||||
root_logger.log(
|
||||
level, log_message, extra={"caller": caller_info}
|
||||
)
|
||||
finally:
|
||||
# 恢复控制台输出级别到原始值,避免长期禁用
|
||||
for handler in console_handlers:
|
||||
try:
|
||||
orig = original_levels.get(id(handler), logging.NOTSET)
|
||||
handler.setLevel(orig)
|
||||
except Exception:
|
||||
try:
|
||||
handler.setLevel(logging.NOTSET)
|
||||
except Exception:
|
||||
pass
|
||||
elif hasattr(analyser, "_std_logger") and analyser._std_logger:
|
||||
# 如果根 logger 没有 handlers,尝试使用 _std_logger(但通常不会到这里)
|
||||
# 优化:跳过标准 logging 输出,避免与控制台 print 重复
|
||||
# 因为 print 已经输出了,这里只用于文件日志(如果需要)
|
||||
pass # 不再输出到标准 logging,避免重复
|
||||
except Exception as e:
|
||||
# 如果标准 logging 写入失败,记录详细错误信息并尝试使用根 logger 写入(作为备用)
|
||||
try:
|
||||
if _error_logger:
|
||||
_error_logger.log_exception(
|
||||
e, context={"tag": tag, "caller": caller_info}
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 如果标准 logging 写入失败,继续使用根 logger 写入(作为备用)
|
||||
try:
|
||||
import logging
|
||||
|
||||
root_logger = logging.getLogger()
|
||||
level = getattr(logging, log_level, logging.INFO)
|
||||
# 构建简单的日志消息
|
||||
simple_msg = f"[{tag}] {msg}" if msg else f"[{tag}]"
|
||||
# 直接使用根 logger,它会自动处理子 logger 的传播
|
||||
root_logger.log(level, simple_msg)
|
||||
except Exception:
|
||||
# 如果所有日志写入都失败,至少确保 stdout 输出(已在上面完成)
|
||||
pass
|
||||
# 移除标准 logging 输出,避免与 stdout 重复
|
||||
# 现在只通过 print 输出到控制台,行为日志只记录重要事件
|
||||
|
||||
# 如果有异常堆栈,也输出到 stdout
|
||||
exc_info = fields.get("exc_info")
|
||||
@@ -815,3 +528,296 @@ class LoggingWrapper:
|
||||
except Exception:
|
||||
pass
|
||||
return {}
|
||||
|
||||
@staticmethod
|
||||
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) -> 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)
|
||||
|
||||
# 始终输出到 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:
|
||||
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 unified_logger import get_unified_logger
|
||||
analyser._std_logger = get_unified_logger("douyin.fudai")
|
||||
except ImportError:
|
||||
try:
|
||||
from douyin.logging import douyin_logger
|
||||
analyser._std_logger = douyin_logger.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 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 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
|
||||
Reference in new issue
Block a user