本文將討論結構化記錄的概念,以及為記錄項目酬載欄位新增結構的方法。如果記錄酬載的格式為 JSON 物件,且該物件儲存在 jsonPayload 欄位中,則該記錄項目稱為結構化記錄。對於這些記錄,您可以建構查詢來搜尋特定 JSON 路徑,也可以為記錄酬載中的特定欄位建立索引。反之,如果記錄檔酬載格式為字串,並儲存在 textPayload 欄位中,記錄項目就是非結構化。您可以搜尋文字欄位,但無法為其內容建立索引。
如要建立結構化記錄項目,請執行下列任一操作:
- 呼叫
entries.writeAPI 方法,並提供格式完整的LogEntry。 - 使用
gcloud logging write指令。
- 使用可寫入結構化記錄的 Cloud Logging 用戶端程式庫。
- 使用 BindPlane 服務。
使用代理程式寫入記錄:
部分 Google Cloud 服務內建整合式記錄代理程式,可將寫入
stdout或stderr的資料以記錄形式傳送至 Cloud Logging。您可以使用這種方法處理 Google Kubernetes Engine、App Engine 彈性環境和 Cloud Run functions 等服務。 Google Cloud如果是 Compute Engine 虛擬機器 (VM),您可以安裝及設定作業套件代理程式或舊版 Logging 代理程式,然後使用已安裝的代理程式將記錄傳送至 Cloud Logging。
如要進一步瞭解這些方法,請參閱下列章節。
使用用戶端程式庫或 API 寫入記錄檔
您可以透過呼叫 Cloud Logging API 的 Cloud Logging 用戶端程式庫,或直接呼叫 Cloud Logging API,寫入記錄資料。用戶端程式庫會自動擷取部分資訊,並提供適當填寫介面,簡化特殊 JSON 欄位的填入作業。不過,如要全面控管酬載結構,請直接呼叫 Cloud Logging API,並將完整的 LogEntry 結構傳遞至 Cloud Logging API。
詳情請參閱 entries.write 參考資料。
如需程式碼範例,請參閱「撰寫結構化記錄」。
使用 gcloud CLI 寫入記錄
您可以使用 gcloud CLI 寫入記錄資料。這個介面支援非結構化記錄和結構化記錄。如要寫入結構化記錄,請提供序列化 JSON 物件給指令。
如需快速入門,請參閱「使用 Google Cloud CLI 寫入及查詢記錄項目」。
如需程式碼範例,請參閱 gcloud logging write 參考資料。
使用 BindPlane 寫入記錄
您可以使用 BindPlane 服務將記錄傳送至 Logging。這些記錄的酬載採用 JSON 格式,並根據來源系統建構。如要瞭解如何尋找及查看使用 BindPlane 擷取的記錄,請參閱 BindPlane Quickstart Guide。
使用代理程式寫入記錄檔
如要取得 Compute Engine 執行個體的記錄,可以使用 Ops Agent 或舊版 Cloud Logging 代理程式。這兩種代理程式都能從第三方應用程式收集指標,並支援結構化記錄:
建議使用作業套件代理程式,從 Compute Engine 執行個體收集遙測資料。這個代理程式會將記錄和指標結合為單一代理程式,提供以 YAML 為基礎的設定,並支援高處理量記錄功能。
如要瞭解如何設定 Ops Agent 以支援結構化記錄,或自訂結構化記錄的格式,請參閱「設定 Ops Agent」一文。
舊版 Cloud Logging 代理程式會收集記錄。這個代理程式不會收集其他形式的遙測資料。
本節的其餘部分僅適用於舊版 Logging 代理程式。
Logging 代理程式:特殊 JSON 欄位
舊版 Logging 代理程式會將 JSON 物件中的某些欄位視為特殊欄位,並擷取至 LogEntry 結構。這些特殊 JSON 欄位可用於在 LogEntry 中設定下列欄位:
severityspanIdlabels由使用者定義httpRequest
JSON 比文字行更精確且用途廣泛,因此您可以使用 JSON 物件撰寫多行訊息及新增中繼資料。
如要使用簡化格式為應用程式建立結構化記錄項目,請參閱下表,其中列出 JSON 中的欄位和值:
| JSON 記錄欄位 |
LogEntry
欄位
|
Cloud Logging 代理程式函式 | 範例值 |
|---|---|---|---|
severity
|
severity
|
記錄代理程式會嘗試比對各種常見的嚴重性字串,包括 Logging API 可辨識的 LogSeverity 字串清單。 | "severity":"ERROR"
|
message
|
textPayload
(或部分
jsonPayload)
|
Logs Explorer 中記錄項目行顯示的訊息。 | "message":"There was an error in the application." 注意:如果記錄代理程式移動其他專用欄位和,且未啟用 detect_json,則 message 會儲存為 textPayload (如果這是唯一剩下的欄位)。否則,message 會保留在 jsonPayload 中。detect_json 不適用於 Google Kubernetes Engine 等代管記錄環境。如果記錄項目包含例外狀況堆疊追蹤,則應在此 message JSON 記錄欄位中設定例外狀況堆疊追蹤,以便剖析例外狀況堆疊追蹤並儲存至 Error Reporting。 |
log
(僅限舊版
Google Kubernetes Engine) |
textPayload
|
僅適用於舊版 Google Kubernetes Engine:
如果移動特殊用途欄位後,只剩下 log 欄位,則該欄位會儲存為 textPayload。 |
|
httpRequest
|
httpRequest
|
LogEntry
HttpRequest 欄位格式的結構化記錄。 |
"httpRequest":{"requestMethod":"GET"}
|
| 時間相關欄位 | timestamp
|
詳情請參閱「時間相關欄位」。 | "time":"2025-10-12T07:20:50.52Z"
|
logging.googleapis.com/insertId
|
insertId
|
詳情請參閱insertIdLogEntry 頁面。 |
"logging.googleapis.com/insertId":"42"
|
logging.googleapis.com/labels
|
labels
|
這個欄位的值必須是結構化記錄。詳情請參閱labels LogEntry 頁面。 |
"logging.googleapis.com/labels":
{"user_label_1":"value_1","user_label_2":"value_2"}
|
logging.googleapis.com/operation
|
operation
|
Logs Explorer 也會使用這個欄位的值,將相關記錄項目分組。詳情請參閱operation頁面上的LogEntry。 |
"logging.googleapis.com/operation":
{"id":"get_data","producer":"github.com/MyProject/MyApplication",
"first":"true"}
|
logging.googleapis.com/sourceLocation
|
sourceLocation
|
與記錄項目相關聯的原始碼位置資訊 (如有)。詳情請參閱LogEntrySourceLocationLogEntry 頁面。 |
"logging.googleapis.com/sourceLocation":
{"file":"get_data.py","line":"142","function":"getData"}
|
logging.googleapis.com/spanId
|
spanId
|
記錄項目相關聯追蹤記錄中的時距 ID。詳情請參閱spanIdLogEntry 頁面。 |
"logging.googleapis.com/spanId":"000000000000004a"
|
logging.googleapis.com/trace
|
trace
|
記錄項目相關聯追蹤記錄的資源名稱 (如有)。詳情請參閱traceLogEntry頁面。 |
"logging.googleapis.com/trace":"[TRACE_ID]""logging.googleapis.com/trace":"projects/my-projectid/traces/[TRACE_ID]" 附註:如果不是寫入 stdout 或 stderr,請將這個欄位格式設為 [TRACE_ID],或使用舊版格式 projects/[PROJECT_ID]/traces/[TRACE_ID]。這兩種格式都能讓 Logs Explorer 和 Trace Explorer 關聯記錄和追蹤記錄資料。如果 autoformat_stackdriver_trace 為 true 且 [V] 符合 ResourceTrace 物件中 traceId 欄位的格式,則 LogEntry trace 欄位的值為 projects/[PROJECT_ID]/traces/[V]。 |
logging.googleapis.com/trace_sampled
|
traceSampled
|
這個欄位的值必須是 true 或 false。詳情請參閱traceSampledLogEntry 頁面。 |
"logging.googleapis.com/trace_sampled": false
|
如要以簡化格式建立記錄項目,請使用欄位建立項目的 JSON 表示法。所有欄位均為選填。
以下是簡化版 JSON 記錄項目的範例:
{ "severity":"ERROR", "message":"There was an error in the application.", "httpRequest":{ "requestMethod":"GET" }, "time":"2020-10-12T07:20:50.52Z", "logging.googleapis.com/insertId":"42", "logging.googleapis.com/labels":{ "user_label_1":"value_1", "user_label_2":"value_2" }, "logging.googleapis.com/operation":{ "id":"get_data", "producer":"github.com/MyProject/MyApplication", "first":"true" }, "logging.googleapis.com/sourceLocation":{ "file":"get_data.py", "line":"142", "function":"getData" }, "logging.googleapis.com/spanId":"000000000000004a", "logging.googleapis.com/trace":"projects/my-projectid/traces/06796866738c859f2f19b7cfb3214824", "logging.googleapis.com/trace_sampled":false }
以下是產生的記錄項目範例:
{ "insertId": "42", "jsonPayload": { "message": "There was an error in the application", "time": "2020-10-12T07:20:50.52Z" }, "httpRequest": { "requestMethod": "GET" }, "resource": { "type": "k8s_container", "labels": { "container_name": "hello-app", "pod_name": "helloworld-gke-6cfd6f4599-9wff8", "project_id": "stackdriver-sandbox-92334288", "namespace_name": "default", "location": "us-west4", "cluster_name": "helloworld-gke" } }, "timestamp": "2020-10-12T07:20:50.52Z", "severity": "ERROR", "labels": { "user_label_2": "value_2", "user_label_1": "value_1" }, "logName": "projects/stackdriver-sandbox-92334288/logs/stdout", "operation": { "id": "get_data", "producer": "github.com/MyProject/MyApplication", "first": true }, "trace": "projects/my-projectid/traces/06796866738c859f2f19b7cfb3214824", "sourceLocation": { "file": "get_data.py", "line": "142", "function": "getData" }, "receiveTimestamp": "2020-10-12T07:20:57.52Z", "spanId": "000000000000004a" }
Logging 代理程式:設定
舊版 Logging 代理程式 google-fluentd 是 Fluentd 記錄資料收集器的 Cloud Logging 專用封裝版本。Logging 代理程式預設使用 Fluentd 設定和 Fluentd 輸入外掛程式,會從磁碟中的檔案等外部來源提取事件記錄,或剖析收到的記錄檔記錄。
Fluentd 有一系列支援的剖析器,可擷取記錄並轉換為結構化 (JSON) 酬載。
使用 format [PARSER_NAME] 設定記錄來源後,就能使用 Fluentd 提供的內建剖析器。如要瞭解如何設定舊版 Logging 代理程式,請參閱「設定 Logging 代理程式」。
下列程式碼範例顯示的是 Cloud Logging 記錄項目中的 Fluentd 設定、輸入記錄檔的記錄,以及輸出的結構化酬載:
Fluentd 設定:
<source> @type tail format syslog # This uses a predefined log format regex named # `syslog`. See details at https://docs.fluentd.org/parser/syslog. path /var/log/syslog pos_file /var/lib/google-fluentd/pos/syslog.pos read_from_head true tag syslog </source>記錄檔記錄 (輸入):
<6>Feb 28 12:00:00 192.168.0.1 fluentd[11111]: [error] Syslog test結構化酬載 (輸出):
jsonPayload: { "pri": "6", "host": "192.168.0.1", "ident": "fluentd", "pid": "11111", "message": "[error] Syslog test" }
如要進一步瞭解 syslog 剖析器的運作方式,請參閱詳細的 Fluentd 說明文件。
Logging 代理程式:預設啟用標準剖析器
下表列出啟用結構化記錄時,代理程式內含的標準剖析器:
| 剖析器名稱 | 設定檔 |
|---|---|
syslog |
/etc/google-fluentd/config.d/syslog.conf |
nginx |
/etc/google-fluentd/config.d/nginx.conf |
apache2 |
/etc/google-fluentd/config.d/apache.conf |
apache_error |
/etc/google-fluentd/config.d/apache.conf |
如需在安裝舊版 Logging 代理程式時啟用結構化記錄的操作說明,請參閱「安裝」一節。
Logging 代理程式:安裝
如要啟用結構化記錄,必須在安裝 (或重新安裝) 舊版 Logging 代理程式時,更改其預設設定。啟用結構化記錄會取代先前列出的設定檔,但不會變更代理程式本身的運作方式。
啟用結構化記錄後,系統會將列出的記錄轉換為記錄項目,格式與啟用結構化記錄前不同。如果記錄檔會傳送至 Logging 以外的目的地,後續處理的應用程式均會受到變更的影響。舉例來說,如果將記錄轉送至 BigQuery,BigQuery 會拒絕當天剩餘時間的新記錄項目,因為這些項目的結構定義不正確。
如需安裝舊版 Logging 代理程式及啟用結構化記錄的操作說明,請參閱「安裝 Logging 代理程式」。
您可在 /etc/google-fluentd/config.d/ 找到舊版 Logging 代理程式的設定檔,其中應已包含預設啟用的標準剖析器。
Logging 代理程式:設定 Apache 存取記錄格式
根據預設,舊版 Logging 代理程式會將 Apache 存取記錄資料儲存在 jsonPayload 欄位中。例如:
{
"logName": ...,
"resource": ...,
"httpRequest": ...,
"jsonPayload": {
"user" : "some-user",
"method" : "GET",
"code" : 200,
"size" : 777,
"host" : "192.168.0.1",
"path" : "/some-path",
"referer": "some-referer",
"agent" : "Opera/12.0"
},
...
}
您也可以設定舊版 Logging 代理程式,將特定欄位擷取為 httpRequest 欄位。例如:
{
"logName": ...,
"resource": ...,
"httpRequest": {
"requestMethod": "GET",
"requestUrl": "/some-path",
"requestSize": "777",
"status": "200",
"userAgent": "Opera/12.0",
"serverIp": "192.168.0.1",
"referrer":"some-referrer",
},
"jsonPayload": {
"user":"some-user"
},
...
}
如先前範例所示,設定 httpRequest 欄位可協助追蹤: Google Cloud 控制台會以父項/子項階層方式,呈現指定 HTTP 要求的所有記錄。
如要設定這個擷取作業,請在 /etc/google-fluentd/config.d/apache.conf 的尾端新增以下內容:
<filter apache-access>
@type record_transformer
enable_ruby true
<record>
httpRequest ${ {"requestMethod" => record['method'], "requestUrl" => record['path'], "requestSize" => record['size'], "status" => record['code'], "userAgent" => record['agent'], "serverIp" => record['host'],
"referer" => record['referer']} }
</record>
remove_keys method, path, size, code, agent, host, referer
</filter>
要進一步瞭解如何設定記錄項目,請參閱編輯記錄一節。
Logging 代理程式:設定 nginx 存取記錄格式
根據預設,舊版 Logging 代理程式會將 nginx 存取記錄資料儲存在 jsonPayload 欄位中。例如:
{
"logName": ...,
"resource": ...,
"httpRequest": ...,
"jsonPayload": {
"remote":"127.0.0.1",
"host":"192.168.0.1",
"user":"some-user",
"method":"GET",
"path":"/some-path",
"code":"200",
"size":"777",
"referrer":"some-referrer",
"agent":"Opera/12.0",
"http_x_forwarded_for":"192.168.3.3"
},
...
}
您也可以設定舊版 Logging 代理程式,將特定欄位擷取為 httpRequest 欄位。例如:
{
"logName": ...,
"resource": ...,
"httpRequest": {
"requestMethod": "GET",
"requestUrl": "/some-path",
"requestSize": "777",
"status": "200",
"userAgent": "Opera/12.0",
"remoteIp": "127.0.0.1",
"serverIp": "192.168.0.1",
"referrer":"some-referrer",
},
"jsonPayload": {
"user":"some-user",
"http_x_forwarded_for":"192.168.3.3"
},
...
}
如先前範例所示,設定 httpRequest 欄位可協助追蹤: Google Cloud 控制台會以父項/子項階層方式,呈現指定 HTTP 要求的所有記錄。
如要設定這個擷取作業,請在 /etc/google-fluentd/config.d/nginx.conf 的尾端新增以下內容:
<filter nginx-access>
@type record_transformer
enable_ruby true
<record>
httpRequest ${ {"requestMethod" => record['method'], "requestUrl" => record['path'], "requestSize" => record['size'], "status" => record['code'], "userAgent" => record['agent'], "remoteIp" => record['remote'], "serverIp" => record['host'], "referer" => record['referer']} }
</record>
remove_keys method, path, size, code, agent, remote, host, referer
</filter>
要進一步瞭解如何設定記錄項目,請參閱編輯記錄一節。
撰寫自己的剖析器
如果標準剖析器不支援您的記錄,您可以自行編寫剖析器。剖析器包含規則運算式,可用於比對記錄檔記錄,並將標籤套用至各個部分。
下列程式碼範例顯示記錄檔記錄中的記錄行、具有標明記錄行格式的規則運算式的設定,以及儲存的記錄項目:
記錄檔記錄中的一行記錄:
REPAIR CAR $500具有標明該行記錄格式的規則運算式的設定:
$ sudo vim /etc/google-fluentd/config.d/test-structured-log.conf $ cat /etc/google-fluentd/config.d/test-structured-log.conf <source> @type tail # Format indicates the log should be translated from text to # structured (JSON) with three fields, "action", "thing" and "cost", # using the following regex: format /(?<action>\w+) (?<thing>\w+) \$(?<cost>\d+)/ # The path of the log file. path /tmp/test-structured-log.log # The path of the position file that records where in the log file # we have processed already. This is useful when the agent # restarts. pos_file /var/lib/google-fluentd/pos/test-structured-log.pos read_from_head true # The log tag for this log input. tag structured-log </source>產生的記錄項目:
{ insertId: "eps2n7g1hq99qp" jsonPayload: { "action": "REPAIR" "thing": "CAR" "cost": "500" } labels: { compute.googleapis.com/resource_name: "add-structured-log-resource" } logName: "projects/my-sample-project-12345/logs/structured-log" receiveTimestamp: "2023-03-21T01:47:11.475065313Z" resource: { labels: { instance_id: "3914079432219560274" project_id: "my-sample-project-12345" zone: "us-central1-c" } type: "gce_instance" } timestamp: "2023-03-21T01:47:05.051902169Z" }
排解問題
如需排解舊版 Logging 代理程式在安裝或互動時的常見問題,請參閱代理程式疑難排解一文。
後續步驟
如要查詢及查看記錄項目,請參閱「使用 Logs Explorer 查看記錄檔」。
如要使用 Google Cloud CLI 讀取記錄項目,請參閱讀取記錄項目一文。
如要使用 Logging API 讀取記錄項目,請參閱
entries.list方法。