preserve simple and detail logs
This commit is contained in:
1 parent
f07fbb305b
commit
5e2ca0587b
4 files changed
+190
-62
No files matched your search
@@ -142,6 +142,16 @@ def get_log_file_path() -> str:
|
|||||||
return os.path.join(PROJECT_ROOT, "logs", "unified.log")
|
return os.path.join(PROJECT_ROOT, "logs", "unified.log")
|
||||||
|
|
||||||
|
|
||||||
|
def get_simple_log_path() -> str:
|
||||||
|
"""返回简洁日志文件的路径"""
|
||||||
|
return os.path.join(PROJECT_ROOT, "logs", "simple.log")
|
||||||
|
|
||||||
|
|
||||||
|
def get_detail_log_path() -> str:
|
||||||
|
"""返回详细日志文件的路径"""
|
||||||
|
return os.path.join(PROJECT_ROOT, "logs", "detail.log")
|
||||||
|
|
||||||
|
|
||||||
def get_actions_log_path() -> str:
|
def get_actions_log_path() -> str:
|
||||||
"""返回行为日志文件 (actions.log) 的路径"""
|
"""返回行为日志文件 (actions.log) 的路径"""
|
||||||
return os.path.join(PROJECT_ROOT, "logs", "actions.log")
|
return os.path.join(PROJECT_ROOT, "logs", "actions.log")
|
||||||
|
|||||||
@@ -22,6 +22,73 @@ from ._common import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
_DETAILED_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": "需回退次数",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _format_detailed_stdout_line(
|
||||||
|
log_parts: list[str],
|
||||||
|
caller_info: str,
|
||||||
|
fields: Dict[str, Any],
|
||||||
|
) -> str:
|
||||||
|
"""生成 detailed 展示/落盘共用的单行文本。"""
|
||||||
|
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 = _DETAILED_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}]")
|
||||||
|
|
||||||
|
return " ".join(detailed_log_parts)
|
||||||
|
|
||||||
|
|
||||||
def _enhanced_log_kv_detailed(
|
def _enhanced_log_kv_detailed(
|
||||||
analyser: Any,
|
analyser: Any,
|
||||||
tag: str,
|
tag: str,
|
||||||
@@ -37,37 +104,6 @@ def _enhanced_log_kv_detailed(
|
|||||||
color: Optional[str] = None,
|
color: Optional[str] = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""详细模式的日志记录(保留之前的复杂格式用于debug)"""
|
"""详细模式的日志记录(保留之前的复杂格式用于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:
|
if need_separator:
|
||||||
try:
|
try:
|
||||||
@@ -80,37 +116,7 @@ def _enhanced_log_kv_detailed(
|
|||||||
# 更新上一个日志标签
|
# 更新上一个日志标签
|
||||||
analyser._last_log_tag = tag
|
analyser._last_log_tag = tag
|
||||||
|
|
||||||
# 构建详细的日志行(包含更多信息)
|
log_line = _format_detailed_stdout_line(log_parts, caller_info, fields)
|
||||||
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:
|
if color:
|
||||||
|
|||||||
@@ -26,7 +26,56 @@ from ._common import (
|
|||||||
|
|
||||||
|
|
||||||
from .simple import _enhanced_log_kv_simple
|
from .simple import _enhanced_log_kv_simple
|
||||||
|
from .simple import _format_simple_stdout_line
|
||||||
from .detailed import _enhanced_log_kv_detailed
|
from .detailed import _enhanced_log_kv_detailed
|
||||||
|
from .detailed import _format_detailed_stdout_line
|
||||||
|
|
||||||
|
|
||||||
|
_ANSI_RE = re.compile(r"\x1b\[[0-9;]*m")
|
||||||
|
|
||||||
|
|
||||||
|
def _strip_ansi(text: str) -> str:
|
||||||
|
return _ANSI_RE.sub("", str(text or ""))
|
||||||
|
|
||||||
|
|
||||||
|
def _dated_log_path(base_path: str, timestamp: str) -> str:
|
||||||
|
root, ext = os.path.splitext(base_path)
|
||||||
|
try:
|
||||||
|
day = str(timestamp or "")[:10]
|
||||||
|
if re.fullmatch(r"\d{4}-\d{2}-\d{2}", day):
|
||||||
|
return f"{root}_{day}{ext or '.log'}"
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return base_path
|
||||||
|
|
||||||
|
|
||||||
|
def _append_line(path: str, line: str) -> None:
|
||||||
|
try:
|
||||||
|
log_dir = os.path.dirname(path)
|
||||||
|
if log_dir:
|
||||||
|
os.makedirs(log_dir, exist_ok=True)
|
||||||
|
with open(path, "a", encoding="utf-8-sig", errors="replace") as f:
|
||||||
|
f.write(_strip_ansi(line).replace("\r", " ").replace("\n", " ") + "\n")
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def _append_dual_format_logs(timestamp: str, simple_line: str, detail_line: str) -> None:
|
||||||
|
"""磁盘始终保留 simple/detail 两份,GUI 显示模式不影响留存。"""
|
||||||
|
try:
|
||||||
|
from douyin.core import path_config
|
||||||
|
|
||||||
|
simple_path = _dated_log_path(path_config.get_simple_log_path(), timestamp)
|
||||||
|
detail_path = _dated_log_path(path_config.get_detail_log_path(), timestamp)
|
||||||
|
except Exception:
|
||||||
|
log_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "..", "logs"))
|
||||||
|
day = str(timestamp or "")[:10]
|
||||||
|
suffix = f"_{day}" if re.fullmatch(r"\d{4}-\d{2}-\d{2}", day) else ""
|
||||||
|
simple_path = os.path.join(log_dir, f"simple{suffix}.log")
|
||||||
|
detail_path = os.path.join(log_dir, f"detail{suffix}.log")
|
||||||
|
|
||||||
|
_append_line(simple_path, simple_line)
|
||||||
|
_append_line(detail_path, detail_line)
|
||||||
|
|
||||||
|
|
||||||
def enhanced_log_kv(analyser: Any, *args: Any, **fields: Any) -> None:
|
def enhanced_log_kv(analyser: Any, *args: Any, **fields: Any) -> None:
|
||||||
@@ -350,6 +399,26 @@ def enhanced_log_kv(analyser: Any, *args: Any, **fields: Any) -> None:
|
|||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
file_fields = dict(fields)
|
||||||
|
file_fields.pop("_log_type", None)
|
||||||
|
try:
|
||||||
|
simple_file_line = _format_simple_stdout_line(
|
||||||
|
tag,
|
||||||
|
msg,
|
||||||
|
log_level,
|
||||||
|
timestamp,
|
||||||
|
fields,
|
||||||
|
log_line,
|
||||||
|
)
|
||||||
|
detail_file_line = _format_detailed_stdout_line(
|
||||||
|
log_parts,
|
||||||
|
caller_info,
|
||||||
|
file_fields,
|
||||||
|
)
|
||||||
|
_append_dual_format_logs(timestamp, simple_file_line, detail_file_line)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
# 根据模式决定日志格式
|
# 根据模式决定日志格式
|
||||||
if log_format_mode == "detailed":
|
if log_format_mode == "detailed":
|
||||||
# 详细模式:保留之前的复杂格式
|
# 详细模式:保留之前的复杂格式
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
|
|
||||||
from douyin.logging.douyin_logging_wrapper_pkg.enhanced import enhanced_log_kv
|
from douyin.logging.douyin_logging_wrapper_pkg.enhanced import enhanced_log_kv
|
||||||
@@ -168,3 +169,45 @@ def test_simple_suppresses_ocr_summary_and_validation_noise(capsys):
|
|||||||
)
|
)
|
||||||
|
|
||||||
assert capsys.readouterr().out == ""
|
assert capsys.readouterr().out == ""
|
||||||
|
|
||||||
|
|
||||||
|
def test_enhanced_log_preserves_simple_and_detail_files(monkeypatch, tmp_path):
|
||||||
|
import douyin.core.path_config as path_config
|
||||||
|
|
||||||
|
config_path = tmp_path / "config.json"
|
||||||
|
config_path.write_text(
|
||||||
|
json.dumps({"logging": {"log_format_mode": "simple"}}),
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
monkeypatch.setattr(path_config, "get_config_path", lambda: str(config_path))
|
||||||
|
monkeypatch.setattr(
|
||||||
|
path_config, "get_logs_dir", lambda: str(tmp_path)
|
||||||
|
)
|
||||||
|
monkeypatch.setattr(
|
||||||
|
path_config, "get_actions_log_path", lambda: str(tmp_path / "actions.log")
|
||||||
|
)
|
||||||
|
monkeypatch.setattr(
|
||||||
|
path_config, "get_simple_log_path", lambda: str(tmp_path / "simple.log")
|
||||||
|
)
|
||||||
|
monkeypatch.setattr(
|
||||||
|
path_config, "get_detail_log_path", lambda: str(tmp_path / "detail.log")
|
||||||
|
)
|
||||||
|
|
||||||
|
analyser = _analyser()
|
||||||
|
enhanced_log_kv(analyser, "福袋详情", "OCR摘要", log_type="OCR_SUMMARY", total_ms=1234.5)
|
||||||
|
config_path.write_text(
|
||||||
|
json.dumps({"logging": {"log_format_mode": "detailed"}}),
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
enhanced_log_kv(analyser, "福袋详情", "OCR摘要2", log_type="OCR_SUMMARY", total_ms=2345.6)
|
||||||
|
|
||||||
|
simple_log = next(tmp_path.glob("simple_*.log"))
|
||||||
|
detail_log = next(tmp_path.glob("detail_*.log"))
|
||||||
|
assert simple_log.exists()
|
||||||
|
assert detail_log.exists()
|
||||||
|
simple_text = simple_log.read_text(encoding="utf-8-sig")
|
||||||
|
detail_text = detail_log.read_text(encoding="utf-8-sig")
|
||||||
|
assert "OCR摘要" in simple_text
|
||||||
|
assert "OCR摘要2" in simple_text
|
||||||
|
assert "total_ms=1234.50" in detail_text
|
||||||
|
assert "total_ms=2345.60" in detail_text
|
||||||
Reference in new issue
Block a user