寫入標準記錄檔

示範如何以標準程式庫相容的方式使用 Cloud Logging。

深入探索

如需包含此程式碼範例的詳細說明文件,請參閱以下文件:

程式碼範例

Go

如要瞭解如何安裝及使用 Logging 的用戶端程式庫,請參閱「Logging 用戶端程式庫」。

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


// Sample stdlogging writes log.Logger logs to the Cloud Logging.
package main

import (
	"context"
	"log"

	"cloud.google.com/go/logging"
)

func main() {
	ctx := context.Background()

	// Sets your Google Cloud Platform project ID.
	projectID := "YOUR_PROJECT_ID"

	// Creates a client.
	client, err := logging.NewClient(ctx, projectID)
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}
	defer client.Close()

	// Sets the name of the log to write to.
	logName := "my-log"

	logger := client.Logger(logName).StandardLogger(logging.Info)

	// Logs "hello world", log entry is visible at
	// Cloud Logs.
	logger.Println("hello world")
}

Python

如要瞭解如何安裝及使用 Logging 的用戶端程式庫,請參閱「Logging 用戶端程式庫」。

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

# Imports the Cloud Logging client library
import google.cloud.logging

# Instantiates a client
client = google.cloud.logging.Client()

# Retrieves a Cloud Logging handler based on the environment
# you're running in and integrates the handler with the
# Python logging module. By default this captures all logs
# at INFO level and higher
client.setup_logging()

# Imports Python standard library logging
import logging

# The data to log
text = "Hello, world!"

# Emits the data using the standard logging module
logging.warning(text)

print("Logged: {}".format(text))

後續步驟

如要搜尋及篩選其他 Google Cloud 產品的程式碼範例,請參閱 Google Cloud 範例瀏覽器