"""参数调用位置跟踪器。 提供两种使用方式: - 在任意位置直接调用 `track_param(name, value)` 记录该参数的调用位置与值; - 使用装饰器 `@track_call()` 自动记录函数被调用时传入的参数及调用位置信息。 日志以逐行 JSON(NDJSON)格式追加到 `state/param_usage.json`,方便并发写入与后续分析。 """ from __future__ import annotations import inspect import json import os import threading import time from typing import Any, Callable, Dict, List, Optional try: from path_config import get_state_dir, ensure_dir except Exception: # 兜底:如果无法导入 path_config,则使用 workspace 相对的 state 目录 def get_state_dir() -> str: return os.path.join( os.path.dirname(os.path.abspath(__file__)), os.pardir, os.pardir, "state" ) def ensure_dir(path: str) -> None: dir_path = os.path.dirname(path) if os.path.isfile(path) else path os.makedirs(dir_path, exist_ok=True) _lock = threading.Lock() def _get_log_path() -> str: state_dir = get_state_dir() if not os.path.isabs(state_dir): state_dir = os.path.abspath(state_dir) ensure_dir(state_dir) return os.path.join(state_dir, "param_usage.json") def _now_ts() -> float: return time.time() def _caller_info(skip: int = 1) -> Dict[str, Any]: # skip=1 返回直接调用者,skip=2 返回上级调用者,依此类推 stack = inspect.stack() idx = min(skip, len(stack) - 1) frame = stack[idx] return {"file": frame.filename, "lineno": frame.lineno, "function": frame.function} def _safe_repr(value: Any) -> str: try: return repr(value) except Exception: return "" def _write_ndjson(entry: Dict[str, Any]) -> None: path = _get_log_path() line = json.dumps(entry, ensure_ascii=False) with _lock: with open(path, "a", encoding="utf-8") as f: f.write(line + "\n") def track_param(name: str, value: Any, extra: Optional[Dict[str, Any]] = None) -> None: """记录单个参数的访问位置与值。 Args: name: 参数名称(字符串) value: 参数值(将尝试使用 repr 序列化) extra: 可选额外字段,会合并入记录 """ caller = _caller_info(skip=1) entry = { "ts": _now_ts(), "type": "param_access", "param": name, "value": _safe_repr(value), "caller_file": caller.get("file"), "caller_line": caller.get("lineno"), "caller_func": caller.get("function"), } if extra: entry.update(extra) _write_ndjson(entry) def track_call(include_args: bool = True) -> Callable[[Callable], Callable]: """装饰器:记录被装饰函数每次被调用时的参数及调用位置信息。 Args: include_args: 是否记录具体参数(默认 True)。 用法: @track_call() def foo(a, b=1): ... """ def decorator(func: Callable) -> Callable: sig = inspect.signature(func) def wrapper(*args, **kwargs): # 获取调用方位置信息(wrapper 的上一帧) call_site = _caller_info(skip=1) entry_base: Dict[str, Any] = { "ts": _now_ts(), "type": "call", "func_name": getattr(func, "__name__", str(func)), "def_file": getattr(func, "__code__", None) and func.__code__.co_filename, "def_line": getattr(func, "__code__", None) and func.__code__.co_firstlineno, "call_file": call_site.get("file"), "call_line": call_site.get("lineno"), "call_func": call_site.get("function"), } if include_args: try: bound = sig.bind_partial(*args, **kwargs) params = {k: _safe_repr(v) for k, v in bound.arguments.items()} except Exception: # 绑定失败时降级记录位置与 repr params = {"args": _safe_repr(args), "kwargs": _safe_repr(kwargs)} entry_base["params"] = params _write_ndjson(entry_base) return func(*args, **kwargs) try: wrapper.__name__ = func.__name__ wrapper.__doc__ = func.__doc__ except Exception: pass return wrapper return decorator def read_entries(limit: Optional[int] = None) -> List[Dict[str, Any]]: """读取记录文件,返回解析后的条目列表(最近的在后)。 Args: limit: 可选限制返回最近 N 条。 """ path = _get_log_path() if not os.path.exists(path): return [] out: List[Dict[str, Any]] = [] with open(path, "r", encoding="utf-8") as f: for line in f: line = line.strip() if not line: continue try: out.append(json.loads(line)) except Exception: # 忽略不可解析行 continue if limit is not None and limit > 0: return out[-limit:] return out __all__ = ["track_param", "track_call", "read_entries"]