关于 debugging
面向开发者的调试技能,涵盖错误与堆栈分析、日志解析、问题复现和根因定位,并指导实施最小修复及验证。附带 Python 脚本,可从日志中提取错误并识别模式。
主要功能
- 01分析错误消息与多语言堆栈
- 02解析日志并识别错误模式
- 03关联分布式服务中的错误
- 04制定复现步骤并定位故障
- 05实施最小修复并验证结果
- 06提供 Python 日志解析脚本
适用场景
- 01调查测试失败或异常行为
- 02从应用日志中查找错误根因
- 03关联多个服务的故障并分析事件
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ 89jobrien/ steve --skill debugging安装后在 Claude Code 中输入/debugging确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/debugging-workflows.mdincident-postmortem.template.mdscripts/parse-logs.py详细介绍
调试
此技能提供全面的调试功能,用于识别和修复错误、测试失败、意外行为及生产环境问题。它结合了通用调试工作流与专门的错误分析、日志解析和模式识别功能。
何时使用此技能
- 遇到代码错误或异常时
- 测试失败且需要了解原因时
- 调查意外行为或 Bug 时
- 分析堆栈跟踪和错误消息时
- 调试生产环境问题时
- 修复用户或 QA 报告的问题时
- 分析错误日志和堆栈跟踪时
- 调查性能问题或异常情况时
- 关联多个服务中的错误时
- 识别重复出现的错误模式时
- 设置错误监控和告警时
- 对事件进行事后分析时
此技能的功能
- 错误分析:捕获并分析错误消息和堆栈跟踪
- 日志解析:使用正则表达式模式和结构化解析从日志中提取错误
- 堆栈跟踪分析:分析多种编程语言中的堆栈跟踪
- 错误关联:识别分布式系统中各错误之间的关联
- 模式识别:检测常见错误模式和反模式
- 复现问题:找出复现问题的步骤
- 隔离问题:定位代码中的确切故障点
- 根因分析:从症状反向追查,找出根本原因
- 最小化修复:实施能够解决问题的最小改动
- 验证:确认解决方案有效且不会引入新问题
- 监控设置:创建用于错误检测的查询和告警
辅助脚本
此技能在 scripts/ 中包含 Python 辅助脚本:
-
parse_logs.py:解析日志文件并提取错误、异常和堆栈跟踪。输出包含错误分析和模式检测结果的 JSON。python scripts/parse_logs.py /var/log/app.log
使用方法
调试错误
Debug this error: TypeError: Cannot read property 'x' of undefined
Investigate why the test is failing in test_user_service.js
分析错误日志
Analyze the error logs in /var/log/app.log and identify the root cause
Investigate why the API is returning 500 errors
模式检测
Find patterns in these error logs from the past 24 hours
Correlate errors between the API service and database
调试流程
1. 收集错误信息
错误消息:
- 阅读完整的错误消息
- 记录错误类型(TypeError、ReferenceError 等)
- 确认错误位置(文件和行号)
堆栈跟踪:
- 分析调用栈
- 确认函数调用的顺序
- 找到错误的起始位置
上下文:
- 检查近期代码变更
- 查看相关代码文件
- 了解执行流程
2. 提取错误(日志分析)
使用辅助脚本:
此技能包含一个用于解析日志的 Python 辅助脚本:
# Parse log file and extract errors
python scripts/parse_logs.py /var/log/app.log
手动解析日志的模式:
# Extract errors from logs
grep -i "error\|exception\|fatal\|critical" /var/log/app.log
# Extract stack traces
grep -A 20 "Exception\|Error\|Traceback" /var/log/app.log
# Extract specific error types
grep "TypeError\|ReferenceError\|SyntaxError" /var/log/app.log
结构化日志解析:
// Parse JSON logs
const errors = logs
.filter(log => log.level === 'error' || log.level === 'critical')
.map(log => ({
timestamp: log.timestamp,
message: log.message,
stack: log.stack,
context: log.context
}));
3. 堆栈跟踪分析
常见模式:
JavaScript/Node.js:
Error: Cannot read property 'x' of undefined
at FunctionName (file.js:123:45)
at AnotherFunction (file.js:456:78)
Python:
Traceback (most recent call last):
File "app.py", line 123, in function_name
result = process(data)
File "utils.py", line 45, in process
return data['key']
KeyError: 'key'
Java:
java.lang.NullPointerException
at com.example.Class.method(Class.java:123)
at com.example.AnotherClass.call(AnotherClass.java:456)
4. 错误关联
时间线分析:
- 按时间戳对错误分组
- 识别错误高峰和模式
- 与部署或变更关联
- 检查是否存在级联故障
服务关联:
- 跨服务边界映射错误
- 识别上游/下游关系
- 跟踪错误传播路径
- 找出常见故障点
5. 模式识别
常见错误模式:
N+1 查询问题:
Multiple database queries in loop
Pattern: SELECT * FROM users; SELECT * FROM posts WHERE user_id = ?
内存泄漏:
Gradually increasing memory usage
Pattern: Memory growth over time without release
竞态条件:
Intermittent failures under load
Pattern: Errors only occur with concurrent requests
超时问题:
Requests timing out
Pattern: Errors after specific duration (e.g., 30s)
6. 复现问题
复现步骤:
- 找出触发错误的确切条件
- 创建能够复现问题的最小测试用例
- 验证问题是否稳定且可复现
- 清晰记录步骤
示例:
## Reproduction Steps
1. Navigate to `/users/123`
2. Click "Edit Profile"
3. Submit form without filling required fields
4. Error occurs: "Cannot read property 'validate' of undefined"
7. 隔离故障位置
代码分析:
- 阅读错误位置附近的代码
- 跟踪执行路径
- 找出假设不成立的位置
- 检查变量状态和值
调试技巧:
- 在关键位置添加日志以跟踪执行
- 使用调试器断点
- 检查变量状态
- 检查函数返回值
- 验证数据结构
8. 提出并验证假设
提出假设:
- 什么可能导致此错误?
- 哪些假设可能有误?
- 哪些边缘情况未考虑?
- 可能缺少哪些依赖项?
验证假设:
- 添加日志以验证假设
- 测试边缘情况
- 检查输入验证
- 确认依赖项可用
- 使用不同的数据进行测试
9. 根因分析
调查步骤:
- 从症状入手:发生了什么错误?
- 逆向追溯:错误发生前有什么变化?
- 检查模式:这是反复发生的问题,还是个例?
- 关联事件:同一时间还发生了什么?
- 找出原因:根本问题是什么?
分析框架:
## Error Analysis
**Error**: [Description]
**Frequency**: [How often]
**Timeline**: [When it started]
**Affected Services**: [Which services]
**User Impact**: [How many users affected]
**Root Cause Hypothesis**:
- [Primary hypothesis with evidence]
- [Alternative hypotheses]
**Evidence**:
- [Log entries supporting hypothesis]
- [Error patterns observed]
- [Correlation with other events]
**Recommended Actions**:
- [Immediate fix]
- [Long-term prevention]
10. 实施最小修复
修复原则:
- 修复根因,而不只是症状
- 尽可能减少改动
- 保留现有功能
- 不要引入新的复杂性
- 添加适当的错误处理
修复验证:
- 使用复现案例测试修复
- 确认没有引入回归问题
- 检查边缘情况
- 确保错误处理恰当
- 确认修复完整
11. 记录解决方案
文档应包括:
- 根因说明
- 支持诊断结论的证据
- 具体代码修复
- 测试方法
- 预防建议
示例
示例 1:空引用错误
输入:错误:TypeError: Cannot read property 'name' of undefined
输出:
## Debugging Analysis
### Error Information
- **Type**: TypeError
- **Location**: `src/services/user.js:45`
- **Message**: Cannot read property 'name' of undefined
### Root Cause
The `getUser()` function returns `undefined` when a user is not found, but the code assumes it always returns a user object.
### Code Location
```javascript
// src/services/user.js:45
const user = getUser(userId);
console.log(user.name); // ❌ Error: user is undefined
修复
// Add null check
const user = getUser(userId);
if (!user) {
throw new Error(`User ${userId} not found`);
}
console.log(user.name); // ✅ Safe
预防措施
- 始终验证可能返回 null/undefined 的函数的返回值
- 使用可选链:
user?.name - 添加 TypeScript 类型,以便在编译时发现此类问题
### Example 2: Database Connection Errors (Log Analysis)
**Input**: Error logs showing database connection failures
**Output**:
```markdown
## Error Analysis: Database Connection Failures
### Pattern Detected
**Error**: `ECONNREFUSED` errors from PostgreSQL
**Frequency**: 15 errors/minute, started 2 hours ago
**Timeline**: Errors began after deployment at 14:30
### Root Cause Analysis
**Hypothesis**: Connection pool exhaustion
**Evidence**:
- Errors correlate with high traffic period (14:30-16:30)
- Connection pool size: 10, concurrent requests: 50+
- No connection cleanup in error handlers
- Errors spike during peak usage
**Code Location**: `src/db/connection.js:45`
**Fix**:
```javascript
// Add connection cleanup
try {
const result = await query(sql);
return result;
} catch (error) {
// Ensure connection is released
await releaseConnection();
throw error;
}
监控查询:
SELECT count(*) FROM pg_stat_activity WHERE state = 'active';
## Reference Files
For detailed debugging workflows, error patterns, and techniques, load reference files as needed:
- **`references/debugging_workflows.md`** - Common debugging workflows by issue type, language-specific debugging, debugging techniques, debugging checklists, and common error patterns (database errors, memory leaks, race conditions, timeouts, authentication errors, network errors, application errors, performance errors)
- **`references/INCIDENT_POSTMORTEM.template.md`** - Incident postmortem template with timeline, root cause analysis, and action items
When debugging specific types of issues or analyzing error patterns, load `references/debugging_workflows.md` and refer to the relevant section.
## Best Practices
### Debugging Approach
1. **Start with Symptoms**: Understand what's wrong before jumping to solutions
2. **Work Backward**: Trace from error to cause
3. **Test Hypotheses**: Don't assume, verify
4. **Minimal Changes**: Fix only what's necessary
5. **Verify Fixes**: Always test that the fix works
### Log Analysis Techniques
1. **Use Structured Logging**: JSON logs are easier to parse and analyze
2. **Include Context**: Add request IDs, user IDs, timestamps to all logs
3. **Log Levels**: Use appropriate levels (error, warn, info, debug)
4. **Correlation IDs**: Use request IDs to trace errors across services
5. **Error Grouping**: Group similar errors to identify patterns
### Error Pattern Recognition
**Time-Based Patterns:**
- Errors at specific times (deployment windows, peak hours)
- Errors after specific duration (timeouts, memory leaks)
- Errors during specific events (database migrations, cache clears)
**Frequency Patterns:**
- Sudden spikes (deployment issues, traffic spikes)
- Gradual increases (memory leaks, resource exhaustion)
- Intermittent (race conditions, timing issues)
**Correlation Patterns:**
- Errors in multiple services simultaneously (infrastructure issues)
- Errors after specific user actions (application bugs)
- Errors correlated with external services (dependency issues)
### Common Debugging Patterns
**Null/Undefined Checks:**
```javascript
// Always check for null/undefined
if (!value) {
// Handle missing value
}
错误处理:
try {
// Risky operation
} catch (error) {
// Log error with context
console.error('Operation failed:', error);
// Handle gracefully
}
日志记录:
// Strategic logging
console.log('Before operation:', { userId, data });
const result = await operation();
console.log('After operation:', { result });
类型检查:
// Verify types
if (typeof value !== 'string') {
throw new TypeError('Expected string');
}
监控设置
错误率监控:
// Track error rate over time
const errorRate = errors.length / totalRequests;
if (errorRate > 0.01) { // 1% error rate threshold
alert('High error rate detected');
}
错误告警:
- 错误率激增(增加 > 5%)时发出告警
- 出现新的错误类型时发出告警
- 出现严重错误模式时发出告警
- 服务间错误出现关联时发出告警
预防策略
- 输入验证:在边界处验证所有输入
- 类型安全:使用 TypeScript 或类型检查
- 错误边界:在适当的层级捕获错误
- 测试:为边缘情况编写测试
- 代码审查:检查代码中常见的陷阱
相关用例
- 修复生产环境 Bug
- 调试测试失败
- 调查用户报告的问题
- 分析错误日志
- 根因分析
- 性能调试
- 调查生产环境事故
- 系统可靠性分析
- 设置错误监控
- 事后分析
- 调试分布式系统
评论
支持 Markdown