jpskill.com
🛠️ 開発・MCP コミュニティ

rn-observability

Logging, error messages, and debugging patterns for React Native. Use when adding logging, designing error messages, debugging production issues, or improving code observability.

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o rn-observability.zip https://jpskill.com/download/17859.zip && unzip -o rn-observability.zip && rm rn-observability.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/17859.zip -OutFile "$d\rn-observability.zip"; Expand-Archive "$d\rn-observability.zip" -DestinationPath $d -Force; ri "$d\rn-observability.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して rn-observability.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → rn-observability フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

React Native Observability

問題提起

サイレントな失敗はデバッグの悪夢です。ログを出力せずに途中で処理を終えるコード、コンテキストが不足しているエラーメッセージ、そして観測性の欠如は、本番環境での問題を診断不可能にします。まるで午前3時にログだけを使ってデバッグするかのようにコードを書きましょう。


パターン: サイレントな早期リターンを避ける

問題: ログを出力しない早期リターンは、目に見えない失敗経路を作り出します。

例 (retake のバグから):

// 間違い - サイレントな死
const saveAnswer = (questionId: string, value: number) => {
  if (!retakeAreas.has(skillArea)) {
    return;  // ❌ なぜリターンしたのか?誰も知らない。
  }
  // ... 保存ロジック
};

// 正しい - 観測可能
const saveAnswer = (questionId: string, value: number) => {
  if (!retakeAreas.has(skillArea)) {
    logger.warn('[saveAnswer] Dropping answer - skill area not in retake set', {
      questionId,
      skillArea,
      retakeAreas: Array.from(retakeAreas),
    });
    return;
  }
  // ... 保存ロジック
};

ルール: すべての早期リターンは、なぜリターンするのかを診断可能な十分なコンテキストとともにログに出力すべきです。


パターン: エラーメッセージの設計

問題: 問題の診断に役立たないエラーメッセージ。

// 悪い - コンテキストがない
throw new Error('No answers found');

// 悪い - 少しはマシだが、午前3時にはやはり役に立たない
throw new Error('No answers found. Please complete at least one question.');

// 良い - 診断コンテキストが含まれている
throw new Error(
  `No answers found. Completed: ${Object.keys(completedAnswers).length}, ` +
  `New: ${Object.keys(userAnswers).length}, ` +
  `Assessment ID: ${assessmentId}. This may indicate a timing issue.`
);

エラーメッセージのテンプレート:

throw new Error(
  `[${functionName}] ${whatFailed}. ` +
  `Context: ${relevantState}. ` +
  `Possible cause: ${hypothesis}.`
);

含めるべきもの:

要素 理由
関数/場所 エラーが発生した場所
何が失敗したか 満たされなかった特定の条件
関連する状態 診断に役立つ値
考えられる原因 修正のための最良の推測

パターン: 構造化されたロギング

問題: 解析と検索が難しい console.log ステートメント。

// 悪い - 非構造化
console.log('saving answer', questionId, value);
console.log('current state', answers);

// 良い - コンテキストオブジェクトで構造化
logger.info('[saveAnswer] Saving answer', {
  questionId,
  value,
  skillArea,
  existingAnswerCount: Object.keys(answers).length,
});

ログレベル:

レベル 使用目的
error 例外、緊急の対応が必要な失敗
warn 失敗はしていないが、問題を示唆する可能性のある予期しない状態
info 重要なビジネスイベント (ユーザーアクション、フローのマイルストーン)
debug 詳細な診断情報 (状態のダンプ、タイミング)

一貫性のあるロギングのためのラッパー:

// utils/logger.ts
const LOG_LEVELS = ['debug', 'info', 'warn', 'error'] as const;
type LogLevel = typeof LOG_LEVELS[number];

const currentLevel: LogLevel = __DEV__ ? 'debug' : 'warn';

function shouldLog(level: LogLevel): boolean {
  return LOG_LEVELS.indexOf(level) >= LOG_LEVELS.indexOf(currentLevel);
}

export const logger = {
  debug: (message: string, context?: object) => {
    if (shouldLog('debug')) {
      console.log(`[DEBUG] ${message}`, context ?? '');
    }
  },
  info: (message: string, context?: object) => {
    if (shouldLog('info')) {
      console.log(`[INFO] ${message}`, context ?? '');
    }
  },
  warn: (message: string, context?: object) => {
    if (shouldLog('warn')) {
      console.warn(`[WARN] ${message}`, context ?? '');
    }
  },
  error: (message: string, context?: object) => {
    if (shouldLog('error')) {
      console.error(`[ERROR] ${message}`, context ?? '');
    }
  },
};

パターン: 機密データの取り扱い

問題: コンソールまたはクラッシュレポートへの機密データのロギング。

// utils/secureLogger.ts
const SENSITIVE_KEYS = ['password', 'token', 'ssn', 'creditCard', 'apiKey'];

function redactSensitive(obj: object): object {
  const redacted = { ...obj };
  for (const key of Object.keys(redacted)) {
    if (SENSITIVE_KEYS.some(s => key.toLowerCase().includes(s))) {
      redacted[key] = '[REDACTED]';
    } else if (typeof redacted[key] === 'object' && redacted[key] !== null) {
      redacted[key] = redactSensitive(redacted[key]);
    }
  }
  return redacted;
}

export const secureLogger = {
  info: (message: string, context?: object) => {
    const safeContext = context ? redactSensitive(context) : undefined;
    logger.info(message, safeContext);
  },
  // ... 他のレベル
};

パターン: フローのトレース

問題: 実行がどこまで進んだのか不明確な複数ステップの操作。

async function retakeFlow(assessmentId: string, skillArea: string) {
  const flowId = `retake-${Date.now()}`;

  logger.info(`[retakeFlow:${flowId}] Starting`, { assessmentId, skillArea });

  try {
    logger.debug(`[retakeFlow:${flowId}] Step 1: Loading completed answers`);
    await loadCompletedAssessmentAnswers(assessmentId);

    logger.debug(`[retakeFlow:${flowId}] Step 2: Enabling retake`);
    await enableSkillAreaRetake(skillArea);

    logger.debug(`[retakeFlow:${flowId}] Step 3: Clearing answers`);
    await clearSkillAreaAnswers(skillArea);

    logger.info(`[retakeFlow:${flowId}] Completed successfully`);
  } catch (error) {
    logger.error(`[retakeFlow:${flowId}] Failed`, {
      error: error.message,
      stack: error.stack,
      assessmentId,
      skillArea,
    });
    throw error;
  }
}

利点:

  • flowId でログを検索して、フロー全体を確認できる
  • どのステップが失敗したかを正確に把握できる
  • タイムスタンプでタイミングを確認できる

パターン: デバッグのための状態スナップショット

問題: 複雑なフローの特定の時点での状態を理解する必要がある。


function snapshotState(label: string) {
  const state = useStore.getState();
  logger.debug(`[StateSnapsh

(原文がここで切り詰められています)
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

React Native Observability

Problem Statement

Silent failures are debugging nightmares. Code that returns early without logging, error messages that lack context, and missing observability make production issues impossible to diagnose. Write code as if you'll debug it at 3am with only logs.


Pattern: No Silent Early Returns

Problem: Early returns without logging create invisible failure paths.

Example (from retake bug):

// WRONG - silent death
const saveAnswer = (questionId: string, value: number) => {
  if (!retakeAreas.has(skillArea)) {
    return;  // ❌ Why did we return? No one knows.
  }
  // ... save logic
};

// CORRECT - observable
const saveAnswer = (questionId: string, value: number) => {
  if (!retakeAreas.has(skillArea)) {
    logger.warn('[saveAnswer] Dropping answer - skill area not in retake set', {
      questionId,
      skillArea,
      retakeAreas: Array.from(retakeAreas),
    });
    return;
  }
  // ... save logic
};

Rule: Every early return should log why it's returning, with enough context to diagnose.


Pattern: Error Message Design

Problem: Error messages that don't help diagnose the issue.

// BAD - no context
throw new Error('No answers found');

// BAD - slightly better but still useless at 3am
throw new Error('No answers found. Please complete at least one question.');

// GOOD - diagnostic context included
throw new Error(
  `No answers found. Completed: ${Object.keys(completedAnswers).length}, ` +
  `New: ${Object.keys(userAnswers).length}, ` +
  `Assessment ID: ${assessmentId}. This may indicate a timing issue.`
);

Error message template:

throw new Error(
  `[${functionName}] ${whatFailed}. ` +
  `Context: ${relevantState}. ` +
  `Possible cause: ${hypothesis}.`
);

What to include:

Element Why
Function/location Where the error occurred
What failed The specific condition that wasn't met
Relevant state Values that help diagnose
Possible cause Your best guess for the fix

Pattern: Structured Logging

Problem: Console.log statements that are hard to parse and search.

// BAD - unstructured
console.log('saving answer', questionId, value);
console.log('current state', answers);

// GOOD - structured with context object
logger.info('[saveAnswer] Saving answer', {
  questionId,
  value,
  skillArea,
  existingAnswerCount: Object.keys(answers).length,
});

Logging levels:

Level Use for
error Exceptions, failures that need immediate attention
warn Unexpected conditions that didn't fail but might indicate problems
info Important business events (user actions, flow milestones)
debug Detailed diagnostic info (state dumps, timing)

Wrapper for consistent logging:

// utils/logger.ts
const LOG_LEVELS = ['debug', 'info', 'warn', 'error'] as const;
type LogLevel = typeof LOG_LEVELS[number];

const currentLevel: LogLevel = __DEV__ ? 'debug' : 'warn';

function shouldLog(level: LogLevel): boolean {
  return LOG_LEVELS.indexOf(level) >= LOG_LEVELS.indexOf(currentLevel);
}

export const logger = {
  debug: (message: string, context?: object) => {
    if (shouldLog('debug')) {
      console.log(`[DEBUG] ${message}`, context ?? '');
    }
  },
  info: (message: string, context?: object) => {
    if (shouldLog('info')) {
      console.log(`[INFO] ${message}`, context ?? '');
    }
  },
  warn: (message: string, context?: object) => {
    if (shouldLog('warn')) {
      console.warn(`[WARN] ${message}`, context ?? '');
    }
  },
  error: (message: string, context?: object) => {
    if (shouldLog('error')) {
      console.error(`[ERROR] ${message}`, context ?? '');
    }
  },
};

Pattern: Sensitive Data Handling

Problem: Logging sensitive data to console or crash reporting.

// utils/secureLogger.ts
const SENSITIVE_KEYS = ['password', 'token', 'ssn', 'creditCard', 'apiKey'];

function redactSensitive(obj: object): object {
  const redacted = { ...obj };
  for (const key of Object.keys(redacted)) {
    if (SENSITIVE_KEYS.some(s => key.toLowerCase().includes(s))) {
      redacted[key] = '[REDACTED]';
    } else if (typeof redacted[key] === 'object' && redacted[key] !== null) {
      redacted[key] = redactSensitive(redacted[key]);
    }
  }
  return redacted;
}

export const secureLogger = {
  info: (message: string, context?: object) => {
    const safeContext = context ? redactSensitive(context) : undefined;
    logger.info(message, safeContext);
  },
  // ... other levels
};

Pattern: Flow Tracing

Problem: Multi-step operations where it's unclear how far execution got.

async function retakeFlow(assessmentId: string, skillArea: string) {
  const flowId = `retake-${Date.now()}`;

  logger.info(`[retakeFlow:${flowId}] Starting`, { assessmentId, skillArea });

  try {
    logger.debug(`[retakeFlow:${flowId}] Step 1: Loading completed answers`);
    await loadCompletedAssessmentAnswers(assessmentId);

    logger.debug(`[retakeFlow:${flowId}] Step 2: Enabling retake`);
    await enableSkillAreaRetake(skillArea);

    logger.debug(`[retakeFlow:${flowId}] Step 3: Clearing answers`);
    await clearSkillAreaAnswers(skillArea);

    logger.info(`[retakeFlow:${flowId}] Completed successfully`);
  } catch (error) {
    logger.error(`[retakeFlow:${flowId}] Failed`, {
      error: error.message,
      stack: error.stack,
      assessmentId,
      skillArea,
    });
    throw error;
  }
}

Benefits:

  • Can search logs by flowId to see entire flow
  • Know exactly which step failed
  • Timing visible via timestamps

Pattern: State Snapshots for Debugging

Problem: Need to understand state at specific points in complex flows.

function snapshotState(label: string) {
  const state = useStore.getState();
  logger.debug(`[StateSnapshot] ${label}`, {
    answers: Object.keys(state.answers).length,
    retakeAreas: Array.from(state.retakeAreas),
    completedAnswers: Object.keys(state.completedAssessmentAnswers).length,
    loading: state.loading,
  });
}

// Usage in flow
async function retakeFlow() {
  snapshotState('Before load');
  await loadCompletedAnswers(id);
  snapshotState('After load');
  await enableRetake(area);
  snapshotState('After enable');
}

Pattern: Assertion Helpers

Problem: Conditions that "should never happen" but need visibility when they do.

// utils/assertions.ts
export function assertDefined<T>(
  value: T | null | undefined,
  context: string
): asserts value is T {
  if (value === null || value === undefined) {
    const message = `[Assertion Failed] Expected defined value: ${context}`;
    logger.error(message, { value });
    throw new Error(message);
  }
}

export function assertCondition(
  condition: boolean,
  context: string,
  debugInfo?: object
): asserts condition {
  if (!condition) {
    const message = `[Assertion Failed] ${context}`;
    logger.error(message, debugInfo);
    throw new Error(message);
  }
}

// Usage
assertDefined(assessment, `Assessment not found: ${assessmentId}`);
assertCondition(
  retakeAreas.has(skillArea),
  `Skill area not in retake set`,
  { skillArea, retakeAreas: Array.from(retakeAreas) }
);

Pattern: Production Error Reporting

Problem: Errors in production with no visibility.

// Integration with error reporting service
import * as Sentry from '@sentry/react-native';

export function captureError(
  error: Error,
  context?: Record<string, unknown>
) {
  logger.error(error.message, { ...context, stack: error.stack });

  if (!__DEV__) {
    Sentry.captureException(error, {
      extra: context,
    });
  }
}

// Usage
try {
  await riskyOperation();
} catch (error) {
  captureError(error, {
    assessmentId,
    skillArea,
    userAnswers: Object.keys(userAnswers),
  });
  throw error;
}

Checklist: Adding Observability

When writing new code:

  • [ ] All early returns have logging with context
  • [ ] Error messages include diagnostic information
  • [ ] Multi-step operations have flow tracing
  • [ ] Sensitive data is redacted before logging
  • [ ] State snapshots available for debugging complex flows
  • [ ] Production errors are captured with context

When debugging existing code:

  • [ ] Add logging to suspect early returns
  • [ ] Add state snapshots before and after async operations
  • [ ] Check for silent catches that swallow errors
  • [ ] Verify error messages have enough context

Quick Debugging Template

Add this temporarily when debugging async/state issues:

const DEBUG = true;

function debugLog(label: string, data?: object) {
  if (DEBUG) {
    console.log(`[DEBUG ${Date.now()}] ${label}`, data ?? '');
  }
}

// In your flow
debugLog('Flow start', { inputs });
debugLog('After step 1', { state: getState() });
debugLog('After step 2', { state: getState() });
debugLog('Flow end', { result });

Remove before committing, or gate behind a flag.