Skip to content

Instantly share code, notes, and snippets.

@yukikim
Created November 15, 2024 04:03
Show Gist options
  • Save yukikim/4dc697ea5749bb471d977888c9b8ca53 to your computer and use it in GitHub Desktop.
Save yukikim/4dc697ea5749bb471d977888c9b8ca53 to your computer and use it in GitHub Desktop.
fetchでpino

fetchで行うリクエストの前後にpinoを利用して、リクエスト内容やレスポンス、エラーのログを記録する方法を紹介します。fetchは通常クライアントサイドで使用されますが、Node.js環境でもnode-fetchなどを使えば同様に使用可能です。

以下に、pinoを使ってfetchリクエストをラップする方法を解説します。

1. 必要なライブラリをインストール

Node.js環境でfetchを使用する場合は、node-fetchをインストールします。また、pinoをインストールして、ロギング機能を追加します。

npm install pino node-fetch

2. 基本的なfetchラッパー関数の実装

pinoを使って、リクエストの送信前、成功時、エラー発生時にそれぞれログを記録するfetchWithLogging関数を実装します。

import pino from 'pino';
import fetch from 'node-fetch';

const logger = pino({
  level: 'info',
  transport: {
    target: 'pino-pretty',
    options: { colorize: true }
  }
});

// fetchラッパー関数の作成
async function fetchWithLogging(url: string, options?: RequestInit) {
  // リクエストの開始をログに記録
  logger.info({ url, options }, 'Sending request to URL');

  try {
    const response = await fetch(url, options);

    // ステータスやレスポンス内容をログに記録
    logger.info({
      url,
      status: response.status,
      statusText: response.statusText
    }, 'Received response');

    // JSONデータやテキストデータとしてレスポンスを処理
    if (response.ok) {
      const data = await response.json();
      logger.info({ data }, 'Response data');
      return data;
    } else {
      logger.warn({ status: response.status, statusText: response.statusText }, 'Request failed');
      throw new Error(`Request failed with status: ${response.status}`);
    }
  } catch (error) {
    // エラー発生時のログ記録
    logger.error({ error }, 'Error occurred during fetch');
    throw error;
  }
}

// 使用例
(async () => {
  try {
    const data = await fetchWithLogging('https://jsonplaceholder.typicode.com/todos/1');
    console.log(data);
  } catch (error) {
    console.error('Fetch failed:', error);
  }
})();

3. fetchWithLogging関数の使い方

  • fetchWithLogging関数を呼び出すと、リクエストURLとオプション、レスポンスのステータス、エラーメッセージなどをログに記録します。
  • レスポンスが成功した場合、JSONデータをログとして記録し、返します。
  • エラーが発生した場合には、エラーメッセージをログに記録し、再スローします。

4. ログの出力例

実行すると、以下のようなログが出力されます。

INFO  Sending request to URL { url: 'https://jsonplaceholder.typicode.com/todos/1', options: {} }
INFO  Received response { url: 'https://jsonplaceholder.typicode.com/todos/1', status: 200, statusText: 'OK' }
INFO  Response data { data: { userId: 1, id: 1, title: 'delectus aut autem', completed: false } }

このように、fetchWithLogging関数を使ってfetchのリクエストやレスポンス、エラーをpinoで管理できるため、リクエスト処理の可視化が容易になります。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment