在 Cloud Functions 中编写结构化日志记录

此示例演示了如何使用 Google Cloud 日志记录客户端在 Cloud Functions 中写入结构化日志。结构化日志可让您更详细、更有条理地记录应用相关信息,从而更轻松地排查和分析问题。

代码示例

Node.js

如需向 Cloud Run functions 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

const {Logging} = require('@google-cloud/logging');
const functions = require('@google-cloud/functions-framework');
const pkg = require('./package.json');

functions.http('structuredLogging', async (req, res) => {
  // Initialize the logging client
  const logging = new Logging();
  // Required to capture your project id
  await logging.setProjectId();
  // Create a LogSync transport, defaulting to process.stdout
  const log = logging.logSync(pkg.name);
  const text = 'Hello, world!';
  // Create a structured log entry with severity,
  // additional component fields, and HTTP request.
  // Appending the httpRequest enables log correlation.
  const metadata = {
    severity: 'NOTICE',
    component: 'arbitrary-property',
    httpRequest: req,
  };
  // Prepares a log entry
  const entry = log.entry(metadata, text);
  log.write(entry);
  res.status(200).send('Success: A log message was written');
});

Python

如需向 Cloud Run functions 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

import logging

import functions_framework
from google.cloud.logging import Client


@functions_framework.http
def structured_logging(request):
    # Initialize the Google Cloud logging client
    cloud_logging_client = Client()
    # Set up a Log Handler that exports logs in JSON format to stdout
    # when running in a serverless environment.
    # To manually set up a Structured Log Handler, see
    # https://googleapis.dev/python/logging/latest/handlers-structured-log.html
    cloud_logging_client.setup_logging()

    # Construct log message and additional metadata
    # https://cloud.google.com/run/docs/logging#using-json
    msg = "Hello, world!"
    metadata = {"component": "arbitrary-property"}

    # Write structured log with additional component fields
    # HTTP request data is attached automatically for request-log correlation
    logging.info(msg, extra={"json_fields": metadata})

    return "Success: A log message was written"

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器