Cloud Logging の Node.js 向け設定

Node.js アプリケーションでは、一般的な BunyanWinston のロギング ライブラリのプラグインが維持されます。

Winston は汎用のライブラリで、さまざまなログ フォーマッタとトランスポートを実装します。

Bunyan は構造化 JSON ログに特化しています。ログの書式設定は、Bunyan コマンドラインにパイプをつなぐことで実行できます。

Node.js 用 Logging クライアント ライブラリを直接使用することも、好みのロギング ライブラリと独自の統合を作成することもできます。

Bunyan と Winston のライブラリを Compute Engine VM インスタンスで使用するために、Logging エージェントをインストールする必要はありません。

準備

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

    プロジェクト セレクタに移動

  3. Google Cloud プロジェクトで課金が有効になっていることを確認します

  4. Cloud Logging API を有効にします。

    API を有効にする

  5. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

    プロジェクト セレクタに移動

  6. Google Cloud プロジェクトで課金が有効になっていることを確認します

  7. Cloud Logging API を有効にします。

    API を有効にする

  8. Node.js 開発用の環境を準備します。

    Node.js 設定ガイドに移動

Bunyan を使用する場合

Cloud Logging には、Bunyan 向けの Node.js 用 Logging ライブラリのプラグインが用意されています。この Bunyan 向けの Logging プラグインによって、Logging を使用する際により簡単で高レベルのレイヤが提供されます。

プラグインのインストール

  1. Logging Bunyan プラグインを簡単にインストールするには、次のように npm を使用します。

    npm install --save bunyan @google-cloud/logging-bunyan
  2. プラグインをインポートして Bunyan の構成にそれを追加します。

    const bunyan = require('bunyan');
    
    // Imports the Google Cloud client library for Bunyan
    const {LoggingBunyan} = require('@google-cloud/logging-bunyan');
    
    // Creates a Bunyan Cloud Logging client
    const loggingBunyan = new LoggingBunyan();
    
    // Create a Bunyan logger that streams to Cloud Logging
    // Logs will be written to: "projects/YOUR_PROJECT_ID/logs/bunyan_log"
    const logger = bunyan.createLogger({
      // The JSON payload of the log as it appears in Cloud Logging
      // will contain "name": "my-service"
      name: 'my-service',
      streams: [
        // Log to the console at 'info' and above
        {stream: process.stdout, level: 'info'},
        // And log to Cloud Logging, logging at 'info' and above
        loggingBunyan.stream('info'),
      ],
    });
    
    // Writes some log entries
    logger.error('warp nacelles offline');
    logger.info('shields at 99%');

プラグインの構成

Bunyan プラグインの動作をカスタマイズするには、Cloud Logging API の Node.js 用 Cloud クライアント ライブラリによってサポートされる構成オプションと同じオプションを使用します。これらのオプションは、プラグインのコンストラクタに渡される options オブジェクトで渡すことができます。

Bunyan と Express の使用

Node.js Express アプリケーションで Logging を使用して Bunyan をセットアップし、使用できます。

// Imports the Google Cloud client library for Bunyan.
const lb = require('@google-cloud/logging-bunyan');

// Import express module and create an http server.
const express = require('express');

async function startServer() {
  const {logger, mw} = await lb.express.middleware({
    logName: 'samples_express',
  });
  const app = express();

  // Install the logging middleware. This ensures that a Bunyan-style `log`
  // function is available on the `request` object. This should be the very
  // first middleware you attach to your app.
  app.use(mw);

  // Setup an http route and a route handler.
  app.get('/', (req, res) => {
    // `req.log` can be used as a bunyan style log method. All logs generated
    // using `req.log` use the current request context. That is, all logs
    // corresponding to a specific request will be bundled in the Stackdriver
    // UI.
    req.log.info('this is an info log message');
    res.send('hello world');
  });

  const port = process.env.PORT || 8080;

  // `logger` can be used as a global logger, one not correlated to any specific
  // request.
  logger.info({port}, 'bonjour');

  // Start listening on the http server.
  const server = app.listen(port, () => {
    console.log(`http server listening on port ${port}`);
  });

  app.get('/shutdown', (req, res) => {
    res.sendStatus(200);
    server.close();
  });
}

startServer();

Winston を使用する場合

Cloud Logging には、Winston 向けの Node.js 用 Logging ライブラリのプラグインが用意されています。この Winston 向けの Logging プラグインによって、Logging を使用する際により簡単で高レベルのレイヤが提供されます。

プラグインのインストール

  1. Logging Winston プラグインを簡単にインストールするには、次のように npm を使用します。

    npm install --save @google-cloud/logging-winston winston
  2. プラグインをインポートして Winston の構成にそれを追加します。

    const winston = require('winston');
    
    // Imports the Google Cloud client library for Winston
    const {LoggingWinston} = require('@google-cloud/logging-winston');
    
    const loggingWinston = new LoggingWinston();
    
    // Create a Winston logger that streams to Cloud Logging
    // Logs will be written to: "projects/YOUR_PROJECT_ID/logs/winston_log"
    const logger = winston.createLogger({
      level: 'info',
      transports: [
        new winston.transports.Console(),
        // Add Cloud Logging
        loggingWinston,
      ],
    });
    
    // Writes some log entries
    logger.error('warp nacelles offline');
    logger.info('shields at 99%');

プラグインの構成

Winston プラグインの動作をカスタマイズするには、Cloud Logging API の Node.js 用 Cloud クライアント ライブラリによってサポートされる構成オプションと同じオプションを使用します。これらのオプションは、プラグインのコンストラクタに渡される options オブジェクトで渡すことができます。

インストールの詳細については、Node.js 用 Cloud Logging ライブラリのドキュメントをご覧ください。公開バグトラッカーを使用して問題を報告することもできます。

Cloud Logging クライアント ライブラリを使用してログを書き込む

Cloud Logging の Node.js 用 Cloud クライアント ライブラリを直接使用する方法については、Logging クライアント ライブラリをご覧ください。

Google Cloud での実行

Node.js 用 Cloud Logging ライブラリを使用してログを書き込むアプリでは、基盤となるリソースのサービス アカウントにログ書き込み(roles/logging.logWriter IAMのロールが必要です。ほとんどの Google Cloud 環境では、このロールを持つようにデフォルトのサービス アカウントが自動的に構成されます。

App Engine

App Engine では Cloud Logging が自動的に有効になり、アプリのデフォルトのサービス アカウントにログエントリを書き込む IAM 権限がデフォルトで付与されます。

アプリからログエントリを書き込むには、このページの説明に沿って、Bunyan または Winston を使用することをおすすめします。

詳細については、ログの書き込みと表示をご覧ください。

Google Kubernetes Engine(GKE)

GKE は、デフォルトのサービス アカウントにログ書き込み(roles/logging.logWriter IAM ロールを自動的に付与します。このデフォルトのサービス アカウントで Workload Identity を使用して、ワークロードが特定の Google Cloud API にアクセスできるようにする場合、追加の構成は必要ありません。ただし、カスタム IAM サービス アカウントで Workload Identity を使用する場合は、カスタム サービス アカウントにログ書き込みロール(roles/logging.logWriter)があることを確認してください。

必要に応じて、クラスタの作成時に次のコマンドを使用して logging.write アクセス スコープを追加することもできます。

gcloud container clusters create example-cluster-name \
    --scopes https://www.googleapis.com/auth/logging.write

Compute Engine

Compute Engine VM インスタンスを使用する場合は、各インスタンスに cloud-platform アクセス スコープを追加します。Google Cloud Console から新しいインスタンスを作成する場合は、[インスタンスの作成] パネルの [ID と API へのアクセス] のセクションで作成します。Compute Engine のデフォルト サービス アカウントまたは別のサービス アカウントを使用し、[ID と API へのアクセス] セクションの [すべての Cloud API に完全アクセス権を許可] を選択します。どのサービス アカウントを選択する場合でも、Google Cloud コンソールの [IAM と管理] でログ書き込みロールが付与されていることを確認してください。

Cloud Functions

Cloud Functions では、デフォルトでログ書き込み役割が付与されます。

Node.js 用 Cloud Logging ライブラリは、明示的に認証情報を提示しなくても使用できます。

Cloud Functions は、自動的に Cloud Logging を使用するように構成されています。

ローカルやその他の場所で実行する

自分のワークステーション、データセンターのコンピュータ、別のクラウド プロバイダの VM インスタンスでライブラリを実行するなど、Google Cloud の外部で Node.js 用 Cloud Logging ライブラリを使用するには、Google Cloud プロジェクト ID と適切なサービス アカウント認証情報を Node.js 用 Cloud Logging ライブラリに直接提供する必要があります。

既存のサービス アカウントの場合は、次の操作を行います。

  1. サービス アカウントに IAM のログ書き込み(roles/logging.logWriter IAM。ロールを付与します。IAM ロールの詳細については、アクセス制御をご覧ください。

  2. アプリケーションのデフォルト認証情報を設定します

サービス アカウントをお持ちでない場合は、サービス アカウントを作成します。このプロセスについては、サービス アカウントの作成をご覧ください。

認証に使用できる方法に関する一般的な情報については、用語: サービス アカウントをご覧ください。

Bunyan を使用する場合:

// Imports the Google Cloud client library for Bunyan
const {LoggingBunyan} = require('@google-cloud/logging-bunyan');

// Creates a client
const loggingBunyan = new LoggingBunyan({
  projectId: 'your-project-id',
  keyFilename: '/path/to/key.json',
});

Winston を使用する場合:

// Imports the Google Cloud client library for Winston
const {LoggingWinston} = require('@google-cloud/logging-winston');

// Creates a client
const loggingWinston = new LoggingWinston({
  projectId: 'your-project-id',
  keyFilename: '/path/to/key.json',
});

ログを確認する

Google Cloud コンソールのナビゲーション パネルで、[ロギング] を選択してから、[ログ エクスプローラ] を選択します。

[ログ エクスプローラ] に移動

ログ エクスプローラでは 1 つ以上のリソースを指定する必要がありますが、リソースの選択が明確でない場合があります。その場合は、次のヒントを参考にしてください。

  • アプリケーションを App Engine にデプロイしている場合や、App Engine 固有のライブラリを使用している場合は、リソースを GAE アプリケーションに設定します。

  • アプリケーションを Compute Engine にデプロイしている場合は、リソースを GCE VM インスタンスに設定します。

  • アプリケーションを Google Kubernetes Engine にデプロイしている場合は、クラスタのロギング構成に応じてログエントリのリソースタイプが異なります。レガシー Google Cloud Observability と Google Cloud Observability Kubernetes Monitoring ソリューションに関する詳細な論議、およびどのようにこれらのオプションがリソースタイプに影響を与えるかについては、Google Cloud Observability Kubernetes Monitoring をご覧ください。

  • アプリケーションが Cloud Logging API を直接使用している場合、リソースは API と構成に依存します。たとえば、アプリケーションでリソースを指定することも、デフォルトのリソースを使用することもできます。

  • ログ エクスプローラにログが表示されない場合に、すべてのログエントリを表示するには、高度なクエリモードに切り替えて空のクエリを使用します。

    1. 高度なクエリモードに切り替えるには、ログ エクスプローラの上部にあるメニュー(▾)をクリックし、[高度なフィルタに変換] を選択します。
    2. フィルタ ボックスに表示されているコンテンツをクリアします。
    3. [フィルタを送信] をクリックします。

    個々のエントリを調べてリソースを特定します。

詳細については、ログ エクスプローラの使用をご覧ください。