mcpField
D
debugging

debugging

github.com/89jobrien開発436 回インストール9 週間前に更新
リポジトリ

debugging について

開発者向けのデバッグスキルです。エラーやスタックトレースの分析、ログ解析、再現手順の特定、根本原因の調査を支援し、最小限の修正と検証を案内します。ログからエラーを抽出してパターンを検出するPythonスクリプトも含みます。

主な機能

  1. 01エラーと複数言語のスタックトレース分析
  2. 02ログ解析とエラーパターンの検出
  3. 03分散サービス間のエラー相関
  4. 04問題の再現と障害箇所の特定
  5. 05最小限の修正と結果の検証
  6. 06ログ解析用Pythonスクリプト

活用シーン

  1. 01テスト失敗や予期しない動作の調査
  2. 02アプリケーションログから根本原因を特定
  3. 03複数サービスにまたがる障害の相関分析

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/89jobrien/steve --skill debugging

インストール後、Claude Code で/debuggingを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

references/
debugging-workflows.md
incident-postmortem.template.md
scripts/
parse-logs.py

詳細

デバッグ

このスキルは、エラー、テストの失敗、予期しない動作、本番環境の問題を特定して修正するための包括的なデバッグ機能を提供します。一般的なデバッグのワークフローに加え、エラー分析、ログ解析、パターン認識に特化した機能を備えています。

このスキルを使用するタイミング

  • コードでエラーや例外が発生したとき
  • テストが失敗し、その理由を把握する必要があるとき
  • 予期しない動作やバグを調査するとき
  • スタックトレースやエラーメッセージを分析するとき
  • 本番環境の問題をデバッグするとき
  • ユーザーや QA から報告された問題を修正するとき
  • エラーログやスタックトレースを分析するとき
  • パフォーマンスの問題や異常を調査するとき
  • 複数のサービスにまたがるエラーを関連付けるとき
  • 繰り返し発生するエラーパターンを特定するとき
  • エラーの監視とアラートを設定するとき
  • インシデントの事後分析を実施するとき

このスキルでできること

  1. エラー分析:エラーメッセージとスタックトレースを収集して分析します
  2. ログ解析:正規表現パターンと構造化解析を使用して、ログからエラーを抽出します
  3. スタックトレース分析:複数のプログラミング言語のスタックトレースを分析します
  4. エラーの関連付け:分散システム全体にわたるエラーの関係を特定します
  5. パターン認識:一般的なエラーパターンとアンチパターンを検出します
  6. 再現:問題を再現する手順を特定します
  7. 切り分け:コード内の正確な障害箇所を特定します
  8. 根本原因分析:症状をさかのぼって調査し、根本的な原因を特定します
  9. 最小限の修正:問題を解決するための最小限の変更を実装します
  10. 検証:解決策が機能し、新たな問題を引き起こさないことを確認します
  11. 監視の設定:エラー検出用のクエリとアラートを作成します

ヘルパースクリプト

このスキルには、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. 問題の再現

再現手順:

  1. エラーを引き起こす正確な条件を特定します
  2. 問題を再現する最小限のテストケースを作成します
  3. 問題が一貫して再現することを確認します
  4. 手順を明確に記録します

例:

## 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. 根本原因分析

調査手順:

  1. 症状から始める:どのようなエラーが発生しているか?
  2. さかのぼって調べる:エラーの前に何が変わったか?
  3. パターンを確認する:繰り返し発生しているか、それとも単発か?
  4. イベントを関連付ける:同じタイミングでほかに何が起きたか?
  5. 原因を特定する:根本的な問題は何か?

分析フレームワーク:

## 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%超の増加)にアラートを通知する
  • 新しい種類のエラーが発生した場合にアラートを通知する
  • 重大なエラーパターンが発生した場合にアラートを通知する
  • サービス間でエラーに相関が見られた場合にアラートを通知する
予防策
  1. 入力検証:境界ですべての入力を検証する
  2. 型安全性:TypeScript または型チェックを使用する
  3. エラーバウンダリー:適切なレベルでエラーを捕捉する
  4. テスト:エッジケースのテストを書く
  5. コードレビュー:よくある落とし穴がないかコードを確認する

関連するユースケース

  • 本番環境のバグ修正
  • テスト失敗のデバッグ
  • ユーザーから報告された問題の調査
  • エラーログの分析
  • 根本原因分析
  • パフォーマンスのデバッグ
  • 本番環境のインシデント調査
  • システムの信頼性分析
  • エラー監視の設定
  • 事後分析
  • 分散システムのデバッグ

コメント