查看及編寫 Cloud Run functions 記錄
寫入執行階段記錄
Cloud Run 函式預設會提供簡單的執行階段記錄。寫入 stdout
或 stderr
的記錄會自動顯示在Google Cloud 控制台中。如要進行更進階的記錄作業,請使用 Cloud Logging 用戶端程式庫。
根據預設,記錄酬載是簡單的文字字串,如下列程式碼片段所示。字串會儲存在記錄項目的 textPayload
欄位中。
Node.js
大多數記錄項目都沒有相關聯的記錄層級。包括:- 使用
console.log()
、console.info()
、console.warn()
或console.error()
發出的記錄 - 直接寫入
stdout
或stderr
的記錄
內部系統訊息的記錄層級為 DEBUG
。
Python
- 標準輸出或標準錯誤的記錄檔沒有相關聯的記錄檔層級。
- 內部系統訊息擁有
DEBUG
記錄層級。
Go
- 記錄至
stdout
或stderr
的記錄沒有相關聯的記錄層級。 - 內部系統訊息擁有
DEBUG
記錄層級。
Java
- 記錄至
stdout
或stderr
的記錄沒有相關聯的記錄層級。 - 內部系統訊息擁有
DEBUG
記錄層級。
C#
using Google.Cloud.Functions.Framework; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using System; using System.Threading.Tasks; namespace LogHelloWorld; public class Function : IHttpFunction { private readonly ILogger _logger; public Function(ILogger<Function> logger) => _logger = logger; public async Task HandleAsync(HttpContext context) { Console.WriteLine("I am a log to stdout!"); Console.Error.WriteLine("I am a log to stderr!"); _logger.LogInformation("I am an info log!"); _logger.LogWarning("I am a warning log!"); await context.Response.WriteAsync("Messages successfully logged!", context.RequestAborted); } }
- 寫入
stdout
(例如透過Console.WriteLine
) 和stderr
(例如透過Console.Error.WriteLine
) 的文字沒有記錄層級。 - ASP.NET Core 記錄層級與 Cloud Logging 層級的對應關係如下:
LogLevel.Trace
和LogLevel.Debug map
至 Cloud LoggingDEBUG
。LogLevel.Information
對應至 Cloud LoggingINFO
。LogLevel.Warning
對應至 Cloud LoggingWARNING
。LogLevel.Error
對應至 Cloud LoggingERROR
。LogLevel.Critical
對應至 Cloud LoggingCRITICAL
。
Ruby
記錄項目沒有相關聯的記錄層級。
PHP
use Psr\Http\Message\ServerRequestInterface; function helloLogging(ServerRequestInterface $request): string { // Code running in Google Cloud Functions itself writes log entries to // Cloud Logging. (Default log severity level is INFO.) $log = fopen('php://stderr', 'wb'); fwrite($log, "Log entry from fwrite().\n"); // You can also specify a severity level explicitly using structured logs. // See this page for a list of log severity values: // https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#LogSeverity fwrite($log, json_encode([ 'message' => 'Structured log with error severity', 'severity' => 'error' ]) . PHP_EOL); // This will log to standard error, which will appear in Cloud Logging error_log('error_log logs in Cloud Functions!'); // This will log an error message and immediately terminate the function execution // trigger_error('fatal errors are logged!'); // For HTTP functions, this is added to the HTTP response // For CloudEvent functions, this does nothing var_dump('var_dump goes to HTTP response for HTTP functions'); // You can also dump variables using var_export() and forward // the resulting string to Cloud Logging via an fwrite() call. $entry = var_export('var_export output can be captured.', true); fwrite($log, $entry); // Functions must return a String or PSR-7 Response object return ''; }
寫入結構化記錄檔
上述預設文字記錄沒有相關聯的記錄層級。
如要在記錄項目中加入記錄層級或其他特定欄位,可以將記錄寫入 stdout
或 stderr
,格式為一行序列化 JSON。Cloud Run 函式會擷取並剖析這行內容,然後將其放入 jsonPayload
欄位,而非 textPayload
。以下程式碼片段示範如何寫入這類結構化記錄。
Node.js
Python
Python 3.8 以上版本支援結構化記錄。
Go
每個記錄項目的結構都由 Entry
型別提供:
記錄 Entry 結構體時,系統會呼叫 String
方法,將結構體封送至 Cloud Logging 預期的 JSON 格式:
Java
使用 Logback 和 SLF4J 啟用 JSON 記錄,方法是在 logback.xml
設定中啟用 Logstash JSON 編碼器。
處理訊息中的特殊 JSON 欄位
當您以 JSON 字典的形式提供結構化資料時,系統會從 jsonPayload
去除某些特殊欄位,然後寫入產生的 LogEntry
中的對應欄位,如特殊欄位的說明文件所述。
舉例來說,如果您的 JSON 含有 severity
屬性,系統會從 jsonPayload
移除這個屬性,並改以記錄項目的 severity
形式顯示。如果存在,message
屬性會做為記錄項目的主要顯示文字。
使用用戶端程式庫寫入記錄
Cloud Logging 用戶端程式庫提供另一種記錄寫入方式。您可以使用這些程式庫,透過程式設計語言的標準記錄機制,與各種支援的記錄架構整合。用戶端程式庫也會自動擷取部分資訊,並提供適當填入欄位的介面,簡化特殊 JSON 欄位的填入作業。
您可以使用用戶端程式庫,透過 Cloud Logging API 同步或非同步寫入記錄。部分用戶端程式庫也支援直接將結構化記錄寫入 stdout
或 stderr
。請注意,如果以非同步方式寫入記錄,函式意外終止可能會導致記錄項目遺失。此外,請注意,使用 Logging API 進行同步記錄會增加函式執行時間,因為必須等待 API 呼叫完成。
查看執行階段記錄
本節說明查看執行階段記錄的選項。
使用指令列工具
您可以在 Cloud Logging UI 中查看 Cloud Run functions 的記錄檔,也可以使用 Google Cloud CLI。
如要透過 gcloud CLI 查看記錄,請使用 gcloud functions logs read
指令:
gcloud functions logs read
如要查看特定函式的記錄,請提供函式名稱做為引數:
gcloud functions logs read FUNCTION_NAME
如要查看特定執行的記錄,請使用下列方法:
gcloud functions logs read FUNCTION_NAME --execution-id EXECUTION_ID
如需完整的記錄檢視選項,請參閱 gcloud functions logs read
的說明文件。
使用記錄資訊主頁
您也可以在Google Cloud 控制台中查看 Cloud Run 函式的執行階段記錄。
使用 Logging API
您也可以透過 Cloud Logging API 寫入及擷取執行階段記錄。Cloud Logging 用戶端程式庫提供 Logging API 的慣用介面:
Node.js
詳情請參閱 Node.js 用戶端程式庫參考資料。Python
詳情請參閱 Python 用戶端程式庫參考資料。Go
詳情請參閱 Go 用戶端程式庫參考資料。Java
詳情請參閱 Java 用戶端程式庫參考資料。C#
private void ListLogEntries(string logId) { var client = LoggingServiceV2Client.Create(); LogName logName = new LogName(s_projectId, logId); ProjectName projectName = new ProjectName(s_projectId); var results = client.ListLogEntries(Enumerable.Repeat(projectName, 1), $"logName={logName.ToString()}", "timestamp desc", callSettings: _retryAWhile); foreach (var row in results) { Console.WriteLine($"{row.TextPayload.Trim()}"); } }
Ruby
PHP
use Google\Cloud\Logging\LoggingClient; /** * Print the timestamp and entry for the project and logger. * * @param string $projectId The Google project ID. * @param string $loggerName The name of the logger. */ function list_entries($projectId, $loggerName) { $logging = new LoggingClient(['projectId' => $projectId]); $loggerFullName = sprintf('projects/%s/logs/%s', $projectId, $loggerName); $oneDayAgo = date(\DateTime::RFC3339, strtotime('-24 hours')); $filter = sprintf( 'logName = "%s" AND timestamp >= "%s"', $loggerFullName, $oneDayAgo ); $options = [ 'filter' => $filter, ]; $entries = $logging->entries($options); // Print the entries foreach ($entries as $entry) { /* @var $entry \Google\Cloud\Logging\Entry */ $entryInfo = $entry->info(); if (isset($entryInfo['textPayload'])) { $entryText = $entryInfo['textPayload']; } else { $entryPayload = []; foreach ($entryInfo['jsonPayload'] as $key => $value) { $entryPayload[] = "$key: $value"; } $entryText = '{' . implode(', ', $entryPayload) . '}'; } printf('%s : %s' . PHP_EOL, $entryInfo['timestamp'], $entryText); } }
如需 Java 的其他記錄選項,請參閱「Java Logging」。
回應執行階段記錄
您可以將記錄轉送至 Cloud Run 函式,藉此回應 Cloud Logging 事件。詳情請參閱「會使用 Cloud Logging 的第二方觸發條件」頁面。
查看建構映像檔記錄
您也可以查看部署程序中「建構映像檔」步驟的記錄。點選連結即可瞭解詳情。