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

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

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

  • 要求記錄 (僅限服務):傳送至 Cloud Run 服務的要求記錄。這類的記錄是自動建立的。
  • 容器記錄 (服務和工作):容器執行個體發出的記錄,通常是來自您自己的程式碼,這類的記錄會寫入支援的位置,如寫入容器記錄所述。

查看記錄

您可以透過多種方式查看服務或工作的記錄:

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

在 Cloud Run 中查看記錄

您可以在對應的服務和工作頁面中查看服務和工作記錄。

查看服務的記錄檔

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

  1. 前往 Cloud Run

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

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

查看工作的記錄檔

如要在 Cloud Run 頁面查看工作記錄,請按照下列步驟操作:

  1. 前往 Cloud Run

  2. 按一下「JOBS」分頁標籤。

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

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

  5. 或者,如果您想查看針對特定工作執行作業預先篩選的記錄,請按一下工作執行作業,然後點選「記錄檔」分頁。

使用 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」頁面:

    前往「Logs Explorer」頁面

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

  3. 使用下拉式選單,選取服務的「Cloud Run 修訂版本」資源,或工作任務的「Cloud Run 工作」

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

在 Cloud Code 中查看服務記錄

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

以程式輔助方式讀取記錄

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

寫入容器記錄檔

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

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

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

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

如果應用程式需要更高的資料量或可靠性,建議您直接使用 Cloud Logging API,無論是應用程式中的程式庫,還是獨立的附屬容器皆可。

在記錄中使用簡單文字與結構化 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

logback.xml 設定中啟用 Logstash JSON 編碼器,即可透過 LogbackSLF4J 啟用 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 的排除記錄功能。

記錄代理程式注意事項

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

記錄資源名稱

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

記錄資源

按一下 Logs Explorer 中的記錄項目,開啟 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 資源類型。