如何利用VS Code Debugger逐行将Locals窗口变量保存为JSON文件?
自动记录每行代码运行时变量值的方案
1. 用VS Code自带功能+批量脚本搞定
VS Code原生支持日志点(Log Points),无需额外安装扩展:
- 手动添加日志点:在代码行左侧点击(和添加断点位置一致),右键选择「Edit Log Point」,输入
{locals}可输出所有局部变量,{globals}输出全局变量,还能自定义输出格式 - 输出到文件:修改项目下的
.vscode/launch.json,添加一行"outputCapture": "stdout",启动调试时用命令将输出定向到文件:code --debug 你的项目路径 > var-log.txt 2>&1 - 批量配置:写个Python/Shell脚本,遍历1000个项目的
.vscode/launch.json,自动预设日志点配置(VS Code支持在配置文件中预定义日志点)
2. 语言原生插桩(最靠谱的批量方案)
直接给代码添加自动记录变量的逻辑,比依赖调试器更适合批量处理:
Python示例
用内置追踪功能写通用脚本,套用到所有项目:
import sys from inspect import currentframe def log_vars(frame, event, arg): if event != 'line': return log_vars # 获取当前行、函数名及变量信息 line_num = frame.f_lineno func_name = frame.f_code.co_name locals_dict = frame.f_locals globals_dict = frame.f_globals # 写入日志文件 log_path = f"{frame.f_code.co_filename}_var_log.txt" with open(log_path, "a", encoding="utf-8") as f: f.write(f"=== 第{line_num}行,函数{func_name} ===\n") f.write(f"局部变量:{locals_dict}\n") f.write(f"全局变量:{globals_dict}\n\n") return log_vars # 启动变量追踪 sys.settrace(log_vars) # 运行目标脚本(批量处理时遍历所有Python文件导入执行) import target_script
JS/TS示例
自动给脚本插入变量记录代码:
const fs = require('fs'); // 给目标脚本添加日志插桩 function add_logs(script_path) { const content = fs.readFileSync(script_path, 'utf8'); const lines = content.split('\n'); const new_lines = lines.map((line, idx) => { const line_num = idx + 1; // 插入变量记录代码 return ` // 记录变量 fs.appendFileSync('${script_path}_log.txt', \`第${line_num}行: 局部变量:\${JSON.stringify({...this, ...locals})} 全局变量:\${JSON.stringify(global)} ---\`); ${line} `; }); const temp_script = `instrumented_${script_path}`; fs.writeFileSync(temp_script, new_lines.join('\n')); return temp_script; } // 批量处理所有脚本 const all_scripts = ['script1.js', 'script2.js']; // 替换为遍历目标文件夹的逻辑 all_scripts.forEach(script => { const temp_script = add_logs(script); // 运行插桩后的脚本 require('./' + temp_script); // 清理临时文件 fs.unlinkSync(temp_script); });
3. 基于VS Code调试API写自动化工具
如果必须依赖VS Code调试器,可基于Debug Adapter Protocol开发脚本:
- 使用
vscode-debugadapter库连接VS Code调试会话 - 配置调试器每行暂停,调用API获取局部/全局变量
- 将变量写入文件后,发送继续执行命令
- 批量处理时,遍历所有项目的launch配置,自动启动调试流程
内容的提问来源于stack exchange,提问作者horizon
相关产品推荐
相关产品推荐

