"""全局参数/调用跟踪器(可选启用)。 启用方式:在运行前设置环境变量 `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 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 "" 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": ""} 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"]