设置 Node.js 版 Cloud Logging

对于 Node.js 应用,系统会为常用的 BunyanWinston 日志记录库维护插件。

Winston 是一个通用库,可实现各种日志格式和传输。

Bunyan 专用于结构化 JSON 日志。可通过连接到 Bunyan 命令行来执行日志格式设置。

您也可以直接使用 Node.js 版 Logging 客户端库,或自行创建与首选日志记录库的集成。

无需安装 Logging 代理即可在 Compute Engine 虚拟机实例上使用 Bunyan 和 Winston 库。

准备工作

  1. 登录您的 Google Cloud 账号。如果您是 Google Cloud 新手,请创建一个账号来评估我们的产品在实际场景中的表现。新客户还可获享 $300 赠金,用于运行、测试和部署工作负载。
  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%');

配置插件

您可以使用 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();

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

配置插件

您可以使用 Node.js 版 Cloud Logging API Cloud 客户端库支持的相同配置选项来自定义 Winston 插件的行为。这些选项可以在传递到插件构造函数的 options 对象中传递。

如需了解安装详情,请参阅 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 会自动向默认服务帐号授予 Logs Writer (roles/logging.logWriter) IAM 角色。如果您将 Workload Identity 与此默认服务帐号搭配使用,以便工作负载访问特定的 Google Cloud API,则无需进行其他配置。但是,如果您将 Workload Identity 与自定义 IAM 服务帐号搭配使用,请确保自定义服务帐号具有 Logs Writer (roles/logging.logWriter) 角色。

如果需要,您还可以在创建集群时使用以下命令添加 logging.write 访问权限范围:

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

Compute Engine

使用 Compute Engine 虚拟机实例时,请为每个实例添加 cloud-platform 访问权限范围。通过 Google Cloud 控制台创建新实例时,您可以在创建实例面板的身份和 API 访问权限部分执行此操作。请使用 Compute Engine 默认服务账号或您选用的其他服务账号,并在身份和 API 访问权限部分勾选允许所有 Cloud APIs 的全面访问权限。无论您选择哪个服务帐号,都请确保已在 Google Cloud 控制台的 IAM 和管理部分中向该服务帐号授予 Logs Writer 角色

Cloud Functions

Cloud Functions 默认授予 Logs Writer 角色

无需明确提供凭据即可使用 Node.js 版 Cloud Logging 库。

Cloud Functions 已配置为自动使用 Cloud Logging。

在本地和其他位置运行

如需在 Google Cloud 之外(包括您自己的工作站、您数据中心的计算机或另一家云提供商的虚拟机实例上)使用 Node.js 版 Cloud Logging 库,您必须直接向 Node.js 版 Cloud Logging 库提供您的 Google Cloud 项目 ID 和相应的服务帐号凭据。

对于现有服务帐号,请执行以下操作:

  1. 向服务帐号授予 IAM Logs Writer (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 控制台的导航面板中,选择 Logging,然后选择 Logs Explorer

前往 Logs Explorer

在日志浏览器中,您必须指定一个或多个资源,但资源的选择并不那么显而易见。以下是帮助您上手的一些提示:

  • 如果您将把应用部署到 App Engine 或者您使用的是 App Engine 专用的库,请将资源设置为 GAE 应用

  • 如果您将在 Compute Engine 上部署应用,请将资源设置为 GCE 虚拟机实例

  • 如果您要在 Google Kubernetes Engine 上部署应用,则集群的日志记录配置将确定日志条目的资源类型。如需详细了解旧版 Google Cloud Observability 和 Google Cloud Observability Kubernetes Monitoring 解决方案,以及这些选项如何影响资源类型,请参阅迁移到 Google Cloud Observability Kubernetes Monitoring

  • 如果您的应用直接使用 Cloud Logging API,则资源取决于该 API 和您的配置。例如,在您的应用中,您可以指定资源或使用默认资源。

  • 如果您在日志浏览器中没有看到任何日志,若要查看所有日志条目,请切换到高级查询模式并使用空查询。

    1. 如需切换到高级查询模式,请点击日志浏览器顶部的菜单 (▾),然后选择转换为高级过滤条件
    2. 清除过滤条件框中显示的内容。
    3. 点击提交过滤条件

    您可以检查各个条目以找出您的资源。

如需了解详情,请参阅使用 Logs Explorer