Files
douyi_guaji_main/douyin/utils/param_usage_tracer.py
T
CodexandClaude Opus 4.5 8fe7ff0585 refactor: 根目录核心模块迁移到 douyin/core/ 和 douyin/logging/
将 4 个根目录核心模块迁移到合理位置:
- path_config.py    -> douyin/core/path_config.py
- version.py        -> douyin/core/version.py
- Underlying_Operations.py -> douyin/core/underlying_operations.py
- unified_logger.py -> douyin/logging/unified_logger.py

配套更新所有 import:
- path_config: 41 处 import 改为 douyin.core.path_config
- version: 4 处改为 douyin.core.version
- unified_logger: 5 处改为 douyin.logging.unified_logger
- Underlying_Operations: 14 处改为 douyin.core.underlying_operations

修复 path_config.PROJECT_ROOT 计算(向上 2 级而非当前目录)。

验证:python -m compileall 全项目通过。

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 00:23:14 +08:00

136 lines
3.8 KiB
Python

"""全局参数/调用跟踪器(可选启用)。
启用方式:在运行前设置环境变量 `PARAM_TRACK_ALL=1`,然后在入口处调用 `start_tracing()`。
该跟踪器使用 `sys.settrace` 捕获函数调用事件,仅记录位于项目根目录下的文件中的函数调用,避免跟踪第三方库。
记录格式与 `param_usage_tracker` 兼容,写入 `state/param_usage.json`(逐行 JSON)。
"""
from __future__ import annotations
import os
import sys
import threading
import time
import inspect
from typing import Any, Dict
try:
from douyin.core.path_config import get_project_root
except Exception:
def get_project_root() -> str:
return os.path.abspath(
os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)
)
try:
# reuse internal writer for consistent format
from douyin.utils import param_usage_tracker as _tracker
except Exception:
_tracker = None
_lock = threading.Lock()
_state = {"enabled": False}
_project_root = os.path.abspath(get_project_root())
def _in_project(filename: str) -> bool:
try:
fn = os.path.abspath(filename)
return fn.startswith(_project_root)
except Exception:
return False
def _safe_short_repr(v: Any, limit: int = 300) -> str:
try:
s = repr(v)
if len(s) > limit:
return s[:limit] + "..."
return s
except Exception:
return "<unrepresentable>"
def _tracefunc(frame, event, arg):
if event != "call":
return _tracefunc
try:
code = frame.f_code
filename = code.co_filename
if not _in_project(filename):
return _tracefunc
func_name = code.co_name
lineno = frame.f_lineno
# 获取参数及其值
try:
arginfo = inspect.getargvalues(frame)
params = {}
for n in arginfo.args:
if n in arginfo.locals:
params[n] = _safe_short_repr(arginfo.locals.get(n))
if arginfo.varargs and arginfo.varargs in arginfo.locals:
params["*" + arginfo.varargs] = _safe_short_repr(
arginfo.locals.get(arginfo.varargs)
)
if arginfo.keywords and arginfo.keywords in arginfo.locals:
params["**" + arginfo.keywords] = _safe_short_repr(
arginfo.locals.get(arginfo.keywords)
)
except Exception:
params = {"_args": "<inspect-failed>"}
entry: Dict[str, Any] = {
"ts": time.time(),
"type": "call",
"func_name": func_name,
"def_file": filename,
"def_line": getattr(code, "co_firstlineno", None),
"call_file": (
frame.f_back.f_code.co_filename if frame.f_back is not None else None
),
"call_line": frame.f_back.f_lineno if frame.f_back is not None else None,
"params": params,
}
# 写入记录
if _tracker is not None and hasattr(_tracker, "_write_ndjson"):
try:
with _lock:
_tracker._write_ndjson(entry)
except Exception:
# 忽略写入错误
pass
except Exception:
# tracing must never raise
pass
return _tracefunc
def start_tracing() -> None:
"""开启全局跟踪(幂等)"""
if _state.get("enabled"):
return
try:
sys.settrace(_tracefunc)
_state["enabled"] = True
except Exception:
_state["enabled"] = False
def stop_tracing() -> None:
try:
sys.settrace(None)
finally:
_state["enabled"] = False
def is_enabled() -> bool:
return bool(_state.get("enabled"))
__all__ = ["start_tracing", "stop_tracing", "is_enabled"]