在 Cloud Run 中記錄及查看記錄檔

本頁面說明使用 Cloud Run 時可用的記錄,以及記錄的查看與寫入方式。

Cloud Run 提供多種類型的記錄,這些記錄會自動傳送到 Cloud Logging

  • 要求記錄 (僅限服務):傳送到 Cloud Run 服務的要求記錄,這類的記錄是自動建立的。
  • 容器記錄 (服務、工作和工作站集區):執行個體發出的記錄,通常是來自您自己的程式碼,這類的記錄會寫入支援的位置,如寫入容器記錄所述。
  • 系統記錄 (服務、工作和工作站集區):平台產生的記錄,內含工作負載的相關資訊。這些記錄會寫入 varlog/system

查看記錄

您可以透過幾種方式查看服務、工作或工作站集區的記錄:

這兩種查看記錄的控制台方法所看到的記錄相同,都儲存在 Cloud Logging 中,但 Cloud Logging 記錄檔探索工具提供更多詳細資料和更多的篩選功能。

在 Cloud Run 中查看記錄

您可以在 Cloud Run 頁面查看下列資源的記錄:

查看服務記錄

如要在 Cloud Run 頁面查看服務記錄:

  1. 前往 Cloud Run

  2. 在顯示的清單中按一下服務。

  3. 按一下 [LOGS] (記錄) 分頁標籤,取得此服務所有修訂版本的要求和容器記錄。您可以依記錄的嚴重性等級進行篩選。

查看工作的記錄

如要在 Cloud Run 頁面查看工作記錄:

  1. 前往 Cloud Run

  2. 按一下「Jobs」(工作)。

  3. 在工作清單中找出所需工作,然後按一下。

  4. 按一下「LOGS」(記錄) 分頁標籤,取得這項工作所有執行的容器記錄。您可以依記錄的嚴重性等級進行篩選。

  5. 或者,如要查看已預先篩選特定工作執行作業的記錄,請按一下工作執行作業,然後按一下「記錄」分頁標籤。

查看工作站集區的記錄

如要在 Cloud Run 頁面查看工作站集區記錄:

  1. 前往 Cloud Run

  2. 按一下「工作站集區」

  3. 在顯示的清單中按一下工作站集區。

  4. 按一下「LOGS」(記錄) 分頁標籤,取得此工作站集區所有修訂版本的請求和容器記錄。您可以依記錄的嚴重性等級進行篩選。

使用 Google Cloud CLI 查看服務記錄

您可以使用 Google Cloud CLI 在指令列中查看追蹤記錄或讀取 Cloud Run 服務的現有記錄。根據預設,記錄會以單行格式顯示,方便您在控制台中查看。

如要追蹤記錄,您需要在 Google Cloud CLI 中安裝 log-streaming 元件。如果未安裝元件,系統會在需要時提示您安裝。

在指令列中查看尾部記錄

如果是 Cloud Run 服務,您可以直接在指令列中,即時追蹤 Cloud Run 服務的記錄:

gcloud beta run services logs tail SERVICE --project PROJECT-ID

取代:

  • SERVICE 改為 Cloud Run 服務名稱。
  • PROJECT-ID 替換為 Google Cloud 專案 ID。執行 gcloud config get-value project 指令即可查看專案 ID。

在指令列中讀取記錄

如要查看 Cloud Run 服務的現有記錄,可以採取下列任一做法:

  • 以適合控制台的格式:
    gcloud run services logs read SERVICE --limit=10 --project PROJECT-ID
  • 直接透過 Cloud Logging:
    gcloud logging read "resource.type=cloud_run_revision AND resource.labels.service_name=SERVICE" --project PROJECT-ID --limit 10

取代:

  • SERVICE 改為 Cloud Run 服務名稱。
  • PROJECT-ID 替換為 Google Cloud 專案 ID。執行 gcloud config get-value project 指令即可查看專案 ID。

在 Cloud Logging 中查看記錄

如要在 Cloud Logging 記錄檔探索工具中查看 Cloud Run 記錄:

  1. 前往Google Cloud 控制台的「記錄檔探索工具」頁面:

    前往「Logs Explorer」(記錄檔探索工具) 頁面

  2. 在頁面頂端選取現有 Google Cloud 專案,或建立新專案。

  3. 使用下拉式選單選取資源:

    • 服務的 Cloud Run 修訂版本
    • 工作的 Cloud Run 工作
    • 工作站集區的 Cloud Run worker 集區

詳情請參閱「使用記錄檔探索工具」。

在 Cloud Code 中查看服務記錄

如要在 Cloud Code 中查看記錄,請參閱 IntelliJVisual Studio Code 指南。

以程式輔助方式讀取記錄

如要以程式輔助方式讀取記錄,可以使用下列其中一種方法:

執行個體資源調度記錄格式和內容

當 Cloud Run 服務啟動新執行個體時,Cloud Logging 會在 varlog/system 記錄檔名稱下加入記錄項目,說明建立每個執行個體的原因。記錄項目採用下列格式:

Starting new instance. Reason: REASON - DESCRIPTION

下表列出各個執行個體說明:

原因 說明
MANUAL_OR_CUSTOMER_MIN_INSTANCE 執行個體是因客戶設定執行個體數量下限手動調度資源而啟動。
AUTOSCALING 由於設定的調度因素 (例如 CPU 使用率、要求輸送量等),或目前流量的現有容量不足,因此啟動執行個體。
DEPLOYMENT_ROLLOUT 由於部署作業、流量分割調整或部署健康狀態檢查,導致修訂版本間的流量轉移,因此啟動執行個體。

寫入容器記錄

當您寫入服務、作業或工作站集區的記錄時,只要將記錄寫入以下任一位置,Cloud Logging 就會自動收集記錄:

多數開發人員應使用標準輸出和標準錯誤來寫入記錄。

寫入這些支援位置的容器記錄會自動與 Cloud Run 服務、修訂版本和位置、Cloud Run 工作人員集區、修訂版本和位置,或 Cloud Run 作業建立關聯。Error Reporting 會抓取並記錄包含在這些記錄中的例外狀況。

整合式記錄功能可在可靠性和資源用量之間取得平衡,適用於大多數應用程式。使用整合式記錄功能寫入記錄項目時,不會耗用 Cloud Logging API 每分鐘 entries.write 要求數的配額。

如果應用程式需要更高的用量或可靠性,建議直接使用 Cloud Logging API,做為應用程式中的程式庫或獨立的 Sidecar 容器

在記錄中使用簡單文字與結構化 JSON

當您寫入記錄時,您可以傳送簡易文字字串或傳送一行序列化 JSON (又稱為「結構化」資料)。Cloud Logging 會擷取並剖析這項資料,然後置於 jsonPayload 中,簡易文字訊息則置於 textPayload

寫入結構化記錄檔

下列程式碼片段說明如何寫入結構化記錄項目。並說明如何將記錄訊息與對應的要求記錄建立關聯。

Node.js


// Uncomment and populate this variable in your code:
// const project = 'The project ID of your function or Cloud Run service';

// Build structured log messages as an object.
const globalLogFields = {};

// Add log correlation to nest all log messages beneath request log in Log Viewer.
// (This only works for HTTP-based invocations where `req` is defined.)
if (typeof req !== 'undefined') {
  const traceHeader = req.header('X-Cloud-Trace-Context');
  if (traceHeader && project) {
    const [trace] = traceHeader.split('/');
    globalLogFields['logging.googleapis.com/trace'] =
      `projects/${project}/traces/${trace}`;
  }
}

// Complete a structured log entry.
const entry = Object.assign(
  {
    severity: 'NOTICE',
    message: 'This is the default display field.',
    // Log viewer accesses 'component' as 'jsonPayload.component'.
    component: 'arbitrary-property',
  },
  globalLogFields
);

// Serialize to a JSON string and output.
console.log(JSON.stringify(entry));

Python

# Uncomment and populate this variable in your code:
# PROJECT = 'The project ID of your Cloud Run service';

# Build structured log messages as an object.
global_log_fields = {}

# Add log correlation to nest all log messages.
# This is only relevant in HTTP-based contexts, and is ignored elsewhere.
# (In particular, non-HTTP-based Cloud Functions.)
request_is_defined = "request" in globals() or "request" in locals()
if request_is_defined and request:
    trace_header = request.headers.get("X-Cloud-Trace-Context")

    if trace_header and PROJECT:
        trace = trace_header.split("/")
        global_log_fields[
            "logging.googleapis.com/trace"
        ] = f"projects/{PROJECT}/traces/{trace[0]}"

# Complete a structured log entry.
entry = dict(
    severity="NOTICE",
    message="This is the default display field.",
    # Log viewer accesses 'component' as jsonPayload.component'.
    component="arbitrary-property",
    **global_log_fields,
)

print(json.dumps(entry))

Go

每個記錄項目的結構都由 Entry 型別提供:


// Entry defines a log entry.
type Entry struct {
	Message  string `json:"message"`
	Severity string `json:"severity,omitempty"`
	Trace    string `json:"logging.googleapis.com/trace,omitempty"`

	// Logs Explorer allows filtering and display of this as `jsonPayload.component`.
	Component string `json:"component,omitempty"`
}

// String renders an entry structure to the JSON format expected by Cloud Logging.
func (e Entry) String() string {
	if e.Severity == "" {
		e.Severity = "INFO"
	}
	out, err := json.Marshal(e)
	if err != nil {
		log.Printf("json.Marshal: %v", err)
	}
	return string(out)
}

記錄 Entry 結構體時,系統會呼叫 String 方法,將結構體封送至 Cloud Logging 預期的 JSON 格式:


func init() {
	// Disable log prefixes such as the default timestamp.
	// Prefix text prevents the message from being parsed as JSON.
	// A timestamp is added when shipping logs to Cloud Logging.
	log.SetFlags(0)
}

func indexHandler(w http.ResponseWriter, r *http.Request) {
	// Uncomment and populate this variable in your code:
	// projectID = "The project ID of your Cloud Run service"

	// Derive the traceID associated with the current request.
	var trace string
	if projectID != "" {
		traceHeader := r.Header.Get("X-Cloud-Trace-Context")
		traceParts := strings.Split(traceHeader, "/")
		if len(traceParts) > 0 && len(traceParts[0]) > 0 {
			trace = fmt.Sprintf("projects/%s/traces/%s", projectID, traceParts[0])
		}
	}

	log.Println(Entry{
		Severity:  "NOTICE",
		Message:   "This is the default display field.",
		Component: "arbitrary-property",
		Trace:     trace,
	})

	fmt.Fprintln(w, "Hello Logger!")
}

Java

如要透過 LogbackSLF4J 啟用 JSON 記錄,請在 logback.xml 設定中啟用 Logstash JSON 編碼器

// Build structured log messages as an object.
Object globalLogFields = null;

// Add log correlation to nest all log messages beneath request log in Log Viewer.
// TODO(developer): delete this code if you're creating a Cloud
//                  Function and it is *NOT* triggered by HTTP.
String traceHeader = req.headers("x-cloud-trace-context");
if (traceHeader != null && project != null) {
  String trace = traceHeader.split("/")[0];
  globalLogFields =
      kv(
          "logging.googleapis.com/trace",
          String.format("projects/%s/traces/%s", project, trace));
}
// -- End log correlation code --

// Create a structured log entry using key value pairs.
// For instantiating the "logger" variable, see
// https://cloud.google.com/run/docs/logging#run_manual_logging-java
logger.error(
    "This is the default display field.",
    kv("component", "arbitrary-property"),
    kv("severity", "NOTICE"),
    globalLogFields);

自訂標準欄位名稱,從記錄酬載中排除不想要的內容。 如需欄位名稱和預期資料格式的清單,請參閱「使用記錄代理程式」。

<configuration>
  <appender name="jsonConsoleAppender" class="ch.qos.logback.core.ConsoleAppender">
    <encoder class="net.logstash.logback.encoder.LogstashEncoder">
      <!-- Ignore default logging fields -->
      <fieldNames>
        <timestamp>[ignore]</timestamp>
        <version>[ignore]</version>
        <logger>[ignore]</logger>
        <thread>[ignore]</thread>
        <level>[ignore]</level>
        <levelValue>[ignore]</levelValue>
      </fieldNames>
    </encoder>
  </appender>
  <root level="INFO">
    <appender-ref ref="jsonConsoleAppender"/>
  </root>
</configuration>

訊息中的特殊 JSON 欄位

特殊欄位的說明文件所述,當您以 JSON 目錄的形式提供結構化記錄時,系統會從 jsonPayload 去除某些特殊欄位,然後寫入產生的 LogEntry 中的對應欄位。

舉例來說,如果您的 JSON 含有 severity 屬性,系統會從 jsonPayload 移除這個屬性,並改以記錄項目的 severity 形式顯示。如果存在 message 屬性,系統會將其做為記錄項目的主要顯示文字。 如要進一步瞭解特殊屬性,請參閱下方的「記錄資源」一節。

建立容器記錄與要求記錄間的關聯 (僅限服務)

在記錄檔探索工具中,以相同 trace 關聯的記錄可用「父子關係」格式來查看:當您按一下要求記錄項目左側的三角形圖示,就會以巢狀方式,在要求記錄下方顯示與該要求相關的容器記錄。

除非您使用 Cloud Logging 用戶端程式庫,否則容器記錄不會自動與要求記錄產生關聯。如要在不使用用戶端程式庫的情況下,將容器記錄與要求記錄建立關聯,可以使用包含 logging.googleapis.com/trace 欄位的結構化 JSON 記錄行,這個欄位會顯示從 X-Cloud-Trace-Context 標頭擷取的追蹤 ID,如上述結構化記錄範例所示。

控管要求記錄的資源使用量 (僅限服務)

要求記錄會自動建立。雖然您無法直接從 Cloud Run 控管要求記錄的數量,但您可以利用 Cloud Logging 的排除記錄功能。

記錄代理程式注意事項

如果您曾搭配特定 Google Cloud 產品 (例如 Compute Engine) 使用 Cloud Logging,可能已使用 Cloud Logging 記錄代理程式。Cloud Run 內建記錄檔收集功能,因此不需要使用記錄代理程式。

記錄資源名稱

Cloud Run 的記錄資源名稱如下:

記錄資源

按一下記錄探索工具中的記錄項目,開啟 JSON 格式的記錄項目,以便深入查看您要的詳細資料。

記錄項目說明文件所述,一個記錄項目中的所有欄位,例如時間戳記、嚴重性和 httpRequest 等,都是標準內容。

Cloud Run 會新增其他中繼資料,方便您識別記錄來源。包括您在 Cloud Run 服務上設定的標籤,以及 Cloud Run 專屬的資源標籤。

服務的記錄項目欄位

以下列出 Cloud Run 服務記錄項目的欄位:

欄位 值和備註
LogEntry.labels.instanceId 處理要求的執行個體。
LogEntry.labels.run.googleapis.com/base_image_versions 服務使用的基礎映像檔版本。只有從來源部署的服務,且啟用自動安全性更新時,才會顯示這項資訊。
LogEntry.labels.run.googleapis.com/cloud_event_id CloudEvent ID。只有接收 Eventarc 事件的服務會顯示這項資訊。
LogEntry.labels.run.googleapis.com/cloud_event_source CloudEvent 來源。只有接收 Eventarc 事件的服務會顯示這項資訊。
LogEntry.labels.mylabel,
LogEntry.labels.mysecondlabel
您在服務上設定的標籤
LogEntry.logName 識別記錄,例如要求記錄、標準錯誤、標準輸出等。
LogEntry.resource.labels.location 識別服務的 Google Cloud 位置。
LogEntry.resource.labels.project_id 部署服務的專案。
LogEntry.resource.labels.revision_name 處理要求的修訂版本。
LogEntry.resource.labels.service_name 處理要求的服務。
LogEntry.resource.type cloud_run_revision。Cloud Run 資源類型。

以下是 Cloud Run 服務的要求記錄項目範例:

{
 httpRequest: {}
 insertId:  "5c82b3d1000ece0000000000"
 labels: {
  instanceId:  "00bf4bf00000fb59c906a00000c9e29c2c4e06dce91500000000056008d2b6460f163c0057b97b2345f2725fb2423ee5f0bafd36df887fdb1122371563cf1ff453717282afe000001"
  mylabel: "mylabelvalue"
  mysecondlabel: "mysecondlabelvalue"
 }
 logName:  "projects/my-project/logs/run.googleapis.com%2Frequests"
 receiveTimestamp:  "2019-03-08T18:26:25.981686167Z"
 resource: {
  labels: {
   configuration_name:  "myservice"
   location:  "europe-west1"
   project_id:  "my-project"
   revision_name:  "myservice-00002"
   service_name:  "myservice"
  }
  type:  "cloud_run_revision"
 }
 severity:  "INFO"
 timestamp:  "2019-03-08T18:26:25.970397Z"
}

職務的記錄項目欄位

以下列出 Cloud Run 工作記錄項目中的欄位:

欄位 值和備註
LogEntry.labels.instanceId 執行個體。
LogEntry.labels.mylabel,

LogEntry.labels.mysecondlabel

您在工作中設定的標籤
LogEntry.logName 識別記錄,例如標準錯誤、標準輸出等。
LogEntry.resource.labels.location 識別工作地點。 Google Cloud
LogEntry.resource.labels.project_id 工作部署的專案。
LogEntry.resource.labels.job_name 工作名稱。
LogEntry.labels.execution_name 工作執行的名稱。
LogEntry.labels.task_index 工作索引。
LogEntry.labels.task_attempt 這項工作的嘗試次數。
LogEntry.resource.type cloud_run_job。Cloud Run 資源類型。

工作站集區的記錄項目欄位

以下列出 Cloud Run 工作站集區的記錄項目中可能出現的欄位:

欄位 值和備註
LogEntry.labels.instanceId 執行個體。
LogEntry.labels.mylabel,

LogEntry.labels.mysecondlabel

您在工作站集區中設定的標籤
LogEntry.logName 識別記錄,例如標準錯誤、標準輸出等。
LogEntry.resource.labels.location 工作站集區的 Google Cloud 位置。
LogEntry.resource.labels.project_id 工作站集區部署的專案。
LogEntry.resource.labels.workerpool_name 工作站集區的名稱。
LogEntry.resource.type cloud_run_workerpool。Cloud Run 資源類型。

後續步驟

  • 使用 Gemini Cloud Assist Investigations 診斷問題、收集可執行的洞察資料,以及解決問題。如要進一步瞭解如何使用記錄檔探索工具啟動調查,請參閱 Gemini 說明文件中的「使用 Gemini Cloud Assist Investigations 解決問題」。