在 Cloud Functions 中編寫結構化記錄

這個範例示範如何使用 Google Cloud 記錄用戶端,在 Cloud Functions 中寫入結構化記錄。結構化記錄檔可提供更詳細且有條理的應用程式資訊記錄方式,方便您排解及分析問題。

程式碼範例

Node.js

如要驗證 Cloud Run 函式,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證機制」。

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 函式,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證機制」。

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 範例瀏覽器