設定 Node.js 適用的 Cloud Logging

對於 Node.js 應用程式,我們維護了熱門 WinstonBunyan 記錄程式庫的外掛程式。Winston 是通用程式庫,可實作各種記錄格式化工具和傳輸方式。Bunyan 專門處理結構化 JSON 記錄,支援透過管道傳輸至 Bunyan 指令列來設定記錄格式。

您也可以直接使用 Node.js 適用的 Logging 用戶端程式庫,或使用偏好的記錄程式庫建立自己的整合。舉例來說,您可以使用 Pino 記錄架構範例。

您不須安裝 Logging 代理程式,就可以在 Compute Engine 虛擬機器 (VM) 執行個體上使用 Winston 或 Bunyan。

事前準備

  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. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. Enable the Cloud Logging API.

    Enable the API

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  6. Make sure that billing is enabled for your Google Cloud project.

  7. Enable the Cloud Logging API.

    Enable the API

  8. 設定適當的 Node.js 開發環境。

    前往 Node.js 設定指南

  9. 設定記錄功能

    本節說明如何安裝及設定 WinstonBunyan 記錄檔程式庫的外掛程式。針對 Bunyan,我們提供如何搭配 Node.js Express 應用程式使用 Bunyan 的相關資訊。

    您可以使用其他程式庫或架構。舉例來說,您可以使用 Pino 記錄架構。如需使用 OpenTelemetry 收集指標和追蹤資料,以及使用 Pino 記錄架構收集記錄資料的程式碼範例,請參閱 Node.js 檢測範例。如果您使用 Pino,就必須實作 Pino 嚴重程度與 Cloud Logging 所用嚴重程度之間的對應。如需程式碼範例,請參閱「對應 Pino 記錄層級」。

    安裝及設定 Winston 外掛程式

    Cloud Logging 提供 Winston Node.js Logging 程式庫的外掛程式。Winston 的 Logging 外掛程式提供較簡單的高層級層,可與 Logging 搭配使用。

    如要安裝及設定 Winston 外掛程式,請按照下列步驟操作:

    1. 如要安裝 Logging Winston 外掛程式,請使用 npm

      npm install @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%');
    3. 設定外掛程式。

      您可以使用 Node.js 適用的 Cloud Logging API Cloud 用戶端程式庫支援的相同設定選項,自訂 Winston 外掛程式的行為。這些選項可傳入傳送至外掛程式建構函式的 options 物件。

    安裝及設定 Bunyan 外掛程式

    Cloud Logging 提供 Bunyan Node.js Logging 程式庫的外掛程式。Bunyan 的 Logging 外掛程式提供較簡單的高階層,可與 Logging 搭配使用。

    如要安裝及設定 Bunyan 外掛程式,請按照下列步驟操作:

    1. 如要安裝 Logging Bunyan 外掛程式,請使用 npm

      npm install 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%');
    3. 設定外掛程式。

      您可以使用 Node.js 適用的 Cloud Logging API Cloud 用戶端程式庫支援的相同設定選項,自訂 Bunyan 外掛程式的行為。這些選項可傳入傳送至外掛程式建構函式的 options 物件。

    使用 Bunyan 和 Express

    您可以在 Node.js Express 應用程式中,設定及使用 Bunyan 和 Logging。

    // 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();

    如要進一步瞭解安裝,請參閱 Node.js 適用的 Cloud Logging 程式庫說明文件。您也可以使用問題追蹤工具報告問題。

    使用 Cloud Logging 用戶端程式庫寫入記錄

    如要瞭解如何直接使用 Node.js 適用的 Cloud Logging 用戶端程式庫,請參閱「Cloud Logging 用戶端程式庫」。

    在 Google Cloud上執行

    如要讓應用程式使用 Node.js 適用的 Cloud Logging 程式庫寫入記錄,基礎資源的服務帳戶必須具備 Logs Writer (roles/logging.logWriter) IAM 角色。 大多數 Google Cloud 環境都會自動設定預設服務帳戶,使其具備這個角色。

    App Engine

    系統會自動為 App Engine 啟用 Cloud Logging,且應用程式的預設服務帳戶預設會具備寫入記錄項目的 IAM 權限。

    如要從應用程式寫入記錄項目,建議您使用本頁面所述的 BunyanWinston

    詳情請參閱「寫入及查看記錄」。

    Google Kubernetes Engine (GKE)

    GKE 會自動授予預設服務帳戶「記錄檔寫入者 (roles/logging.logWriter)」 IAM 角色。如果您使用適用於 GKE 的工作負載身分聯盟,搭配這個預設服務帳戶,讓工作負載存取特定Google Cloud API,則不需要進行額外設定。不過,如果您使用 Workload Identity Federation for GKE,並搭配自訂 IAM 服務帳戶,請確保自訂服務帳戶具備記錄寫入者角色 (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 主控台建立新執行個體時,您可在「Create Instance」(建立執行個體) 面板的「Identity and API access」(身分及 API 存取權) 區段中執行此操作。請使用 Compute Engine 預設服務帳戶或您選擇的其他服務帳戶,並選取「Identity and API access」 (身分及 API 存取權) 區段的「Allow full access to all Cloud APIs」(允許所有 Cloud API 的完整存取權)。無論您選取哪個服務帳戶,請確認該帳戶已在Google Cloud 主控台的「IAM & Admin」區段取得記錄寫入者角色

    Cloud Run 函式

    在預設情況下,Cloud Run functions 會授予記錄寫入者角色

    不需要明確提供憑證,即可使用 Node.js 適用的 Cloud Logging 程式庫。

    Cloud Run functions 設定為自動使用 Cloud Logging。

    在本機及其他位置執行

    如要在 Google Cloud以外使用 Node.js 適用的 Cloud Logging 程式庫 (包括在您自己的工作站、資料中心的電腦或其他雲端服務供應商的 VM 執行個體上執行程式庫),您必須在本機環境中設定應用程式預設憑證 (ADC),才能向 Node.js 適用的 Cloud Logging 程式庫進行驗證。

    詳情請參閱「為內部部署環境或其他雲端服務供應商設定 ADC」。

    使用 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',
    });

    使用 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',
    });

    查看記錄

    前往 Google Cloud 控制台的「Logs Explorer」頁面:

    前往「Logs Explorer」(記錄檔探索工具)

    如果您是使用搜尋列尋找這個頁面,請選取子標題為「Logging」的結果

    在記錄檔探索器中,您必須指定一或多個資源,但資源的選取可能並不明顯。下列提示可協助您著手操作:

    • 如果您將應用程式部署至 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. 按一下 [Submit Filter] (提交篩選器)

      您可以檢查個別項目,以識別您的資源。

    詳情請參閱「使用記錄檔探索工具」。