MessageLogging 政策

本頁內容適用於 ApigeeApigee Hybrid

查看 Apigee Edge 說明文件。

政策圖示

結果

您可以使用 MessageLogging 政策,將自訂訊息記錄到 Cloud Logging 或系統記錄檔。您可以使用記錄中的資訊執行各種工作,例如追蹤 API 執行階段環境中的問題。

這項政策是可擴充政策,使用這項政策可能會產生費用或影響用量,具體情況取決於您的 Apigee 授權。如要瞭解政策類型和使用方式的影響,請參閱「政策類型」。

使用 MessageLogging 政策的方法有兩種:

  • <CloudLogging> 元素會將訊息記錄至 Cloud Logging。如要使用這個方法,請為 Google Cloud 專案啟用 Cloud Logging API。如要進一步瞭解如何為 Google Cloud 專案啟用 API,請參閱「啟用及停用服務」。
  • <Syslog> 元素會將訊息記錄到系統記錄檔,這是將系統記錄或事件訊息傳送至特定伺服器的標準通訊協定。如要使用這種方法,您必須有可用的系統記錄伺服器。如果沒有,可以使用 Splunk、Sumo Logic 和 Loggly 等公開記錄管理服務。請參閱「設定第三方記錄管理服務」。

注意:無法在同一項政策中同時使用 <CloudLogging> 元素和 <Syslog> 元素。

<MessageLogging> 元素

定義 <MessageLogging> 政策。

預設值 請參閱下方的「預設政策」分頁
是否必要 必填
類型 類型
父項元素 不適用
子項元素 <CloudLogging>
<Syslog>
<logLevel>

<MessageLogging> 元素使用下列語法:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<MessageLogging continueOnError="false" enabled="true" name="Message-Logging-1">
    <DisplayName>Message Logging-1</DisplayName>
    <Syslog>
<!-- Note: You cannot use both the <Syslog> element and the <CloudLogging> element in the same policy. -->
        <Message>Some message for syslog</Message>
        <Host>localhost</Host>
        <Port>514</Port>
    </Syslog>
    <CloudLogging>
<!-- Note: You cannot use both the <CloudLogging> and the <Syslog> element in the same policy. -->
        <LogName>projects/{organization.name}/logs/{log.id}</LogName>
        <Message contentType="application/json">{"{message.queryparam.key}": "{message.queryparam.value}"}</Message>
        <Labels>
            <Label>
                <Key>key1</Key>
                <Value>value1</Value>
            </Label>
            <Label>
                <Key>key2</Key>
                <Value>value2</Value>
            </Label>
        </Labels>
        <ResourceType>api</ResourceType>
    </CloudLogging>
    <logLevel>ALERT</logLevel>
</MessageLogging>

這個元素包含下列所有政策都適用的屬性:

屬性 預設 是否必要? 說明
name 不適用 必要

政策的內部名稱。name 屬性的值可以包含英文字母、數字、空格、連字號、底線和句號。這個值不得超過 255 個半形字元。

您可以選擇使用 <DisplayName> 元素,在管理 UI 代理程式編輯器中為政策加上不同、自然語言的名稱。

continueOnError false 選用 將其設為 false,即可在政策失敗時傳回錯誤。這是大多數政策的預期行為。將其設為 true,即使政策失敗,流程執行作業仍會繼續進行。另請參閱:
enabled 選用 設為 true 即可強制執行政策。設為 false 即可關閉政策。即使政策仍附加至流程,系統也不會強制執行這項政策。
async   false 已淘汰 此屬性已淘汰。

下表提供 <MessageLogging> 子元素的高階說明:

欄位名稱 欄位說明
CloudLogging

設定要記錄到 Cloud Logging 的訊息。

Syslog

設定要記錄到 syslog 的訊息。

範例

CloudLogging

<MessageLogging name="LogToCloudLogging">
    <CloudLogging>
        <LogName>projects/{organization.name}/logs/{log.id}</LogName>
        <Message contentType="application/json">{"{message.queryparam.key}": "{message.queryparam.value}"}</Message>
        <Labels>
            <Label>
                <Key>key1</Key>
                <Value>value1</Value>
            </Label>
            <Label>
                <Key>key2</Key>
                <Value>value2</Value>
            </Label>
        </Labels>
        <ResourceType>api</ResourceType>
    </CloudLogging>
</MessageLogging>

這個範例說明如何使用 訊息範本。由於 Message 元素包含流程變數

{"{message.queryparam.key}": "{message.queryparam.value}"}

當有人使用 message.queryparam.key = "fruit"message.queryparam.value = "apple" 值呼叫 Proxy 時,產生的記錄項目會是 {"fruit": "apple"}

系統記錄檔

<MessageLogging name="LogToSyslog">
  <Syslog>
    <Message>[3f509b58 tag="{organization.name}.{apiproxy.name}.{environment.name}"] Weather request for WOEID {request.queryparam.w}.</Message>
    <Host>logs-01.loggly.com</Host>
    <Port>514</Port>
    <Protocol>TCP</Protocol>
    <FormatMessage>true</FormatMessage>
    <DateFormat>yyMMdd-HH:mm:ss.SSS</DateFormat>
  </Syslog>
  <logLevel>ALERT</logLevel>
</MessageLogging>

在這個範例中,假設您需要記錄 API 從消費者應用程式收到的每則要求訊息相關資訊。值 3f509b58 代表 Loggly 服務專屬的鍵值。如果您有 Loggly 帳戶,請代入 Loggly 金鑰。產生的記錄訊息會填入四個值:與交易相關聯的機構、API 代理和環境名稱,以及要求訊息中查詢參數的值。時間戳記的格式會類似 230704-13:42:17.376,如 DateFormat 元素中指定的格式。

透過 TLS/SSL 傳送系統記錄

<MessageLogging name="LogToSyslog">
  <Syslog>
    <Message>[3f509b58 tag="{organization.name}.{apiproxy.name}.{environment.name}"] Weather request for WOEID {request.queryparam.w}.</Message>
    <Host>logs-01.loggly.com</Host>
    <Port>6514</Port>
    <Protocol>TCP</Protocol>
    <FormatMessage>true</FormatMessage>
    <SSLInfo>
        <Enabled>true</Enabled>
    </SSLInfo>
  </Syslog>
  <logLevel>WARN</logLevel>
</MessageLogging>

您可以新增 <SSLInfo> 區塊,透過 TLS/SSL 將訊息傳送給第三方訊息記錄供應商。

子元素參照

以下各節說明 <MessageLogging> 的子項元素。

<CloudLogging>

使用 <CloudLogging> 元素將訊息記錄至 Cloud Logging。

欄位名稱 是否必要 說明
LogName 記錄名稱。記錄名稱的格式應為 projects/{PROJECT_ID}/logs/{LOG_ID}。您可以改用變數取代 {PROJECT_ID}{LOG_ID}
Message

要記錄的訊息。訊息具有 contentType 屬性,其值分別為文字和 JSON 訊息的 text/plainapplication/json。請參閱範例

Label 要附加至記錄訊息的標籤 (如有)。 這些值會以鍵/值組合的形式呈現,如下所示:
<Label>
    <Key>key1</Key>
    <Value>value1</Value>
</Label>
ResourceType 否 (預設為全域) 代表產生記錄的受監控資源。

Cloud Logging 的驗證

如要使用 <CloudLogging> 元素,您必須部署 API 代理,才能使用 Google 驗證。Apigee 會使用與您在 Cloud Logging 的輸出要求中指定的服務帳戶身分相應的憑證。詳情請參閱使用 Google 驗證

您在部署時附加至 API Proxy 的服務帳戶,必須具備具有 logging.logEntries.create 權限的角色。除非您需要更精細的控制權,否則建議為服務帳戶使用更具包容性的預先定義角色 roles/logging.logWriter。如要進一步瞭解 <CloudLogging> 的 Identity and Access Management (IAM) 角色,請參閱存取權控管指南

在 Apigee Hybrid 中部署 Proxy

如果您使用 Apigee Hybrid,為 Apigee Hybrid 建立的 執行階段服務帳戶必須模擬 Proxy 服務帳戶,才能代表該帳戶發出經過驗證的呼叫。因此,Apigee Hybrid 執行階段服務帳戶必須具備 Proxy 服務帳戶的 iam.serviceAccountTokenCreator 角色。

<Syslog>

使用 <Syslog> 元素設定要記錄到 syslog 的訊息。使用 <Syslog> 時,API Proxy 會將記錄訊息從 Apigee 轉送至遠端系統記錄檔伺服器。如要使用這種方法,您必須有可用的系統記錄伺服器。如果沒有,可以使用 Splunk、Sumo Logic 和 Loggly 等公開記錄管理服務。詳情請參閱「設定第三方記錄管理服務」。

欄位名稱 是否必要 欄位說明
Message

要記錄的訊息。訊息具有 contentType 屬性,其值分別為文字和 JSON 訊息的 text/plainapplication/json。請參閱範例

Host 應傳送系統記錄的伺服器主機名稱或 IP 位址。如未加入這個元素,預設值為 localhost。
Port 執行系統記錄的通訊埠。如未加入這個元素,預設值為 514。
Protocol TCP 或 UDP (預設值)。雖然 UDP 的效能較高,但 TCP 通訊協定可確保訊息記錄檔傳送至系統記錄伺服器。如要透過 TLS/SSL 傳送系統記錄訊息,僅支援 TCP。
FormatMessage 不需要,但必須使用 <FormatMessage>true</FormatMessage> 才能搭配 Loggly 使用。

truefalse (預設)

這個元素可讓您控制附加至訊息的 Apigee 產生內容格式。如果設為 true,syslog 訊息會以固定數量的字元做為前置字元,方便您從訊息中篩除該資訊。以下是固定格式的範例:

<14>1 2023-03-20T09:24:39.039+0000 e49cd3a9-4cf6-48a7-abb9-7ftfe4d97d00 Apigee - - - Message starts here

Apigee 產生的資訊包括:

  • <14> - 根據訊息的記錄層級和設施層級,計算出的優先順序分數 (請參閱 Syslog 通訊協定)。
  • 1 - 目前的系統記錄版本。
  • 日期 (世界標準時間 = +0000)。
  • 訊息處理器 UUID。
  • 「Apigee - - - 」

如果設為 false (預設值),系統不會在訊息開頭加上這些固定字元。

PayloadOnly

truefalse (預設)

這個元素會將 Apigee 產生的訊息格式設為僅包含系統記錄訊息主體,不含 FormatMessage 指定的前置字元。

如未加入這個元素或將其留空,預設值為 false

請參閱 FormatMessage

DateFormat

用於設定每個記錄訊息時間戳記格式的範本字串。 根據預設,Apigee 會使用 yyyy-MM-dd'T'HH:mm:ss.SSSZ。如要瞭解這個範本的行為,請參閱 Java 的 SimpleDateFormat 類別說明文件。根據該定義,格式字串中的 yyyy 會替換為 4 位數的年份,MM 會替換為 2 位數的月份編號,依此類推。

SSLInfo

可透過 SSL/TLS 記錄訊息。搭配子元素 <Enabled>true</Enabled> 使用。

如未加入這個元素或將其留空,預設值為 false (無 TLS/SSL)。

<SSLInfo>
    <Enabled>true</Enabled>
</SSLInfo>

您可以設定 <SSLInfo> 標記,方法與在 TargetEndpoint 上相同,包括啟用雙向 TLS/SSL,詳情請參閱「API Proxy 設定參考資料」。系統僅支援 TCP 通訊協定。


<logLevel>

<logLevel> 元素的有效值為:INFO (預設值)、ALERTWARNERROR

設定要納入訊息記錄的資訊詳細程度。

如果您使用 FormatMessage 元素 (設為 true),<logLevel> 設定會影響 Apigee 產生的資訊中,附加至訊息的計算優先順序分數 (角括號內的數字)。

使用須知

MessageLogging 政策附加至 API Proxy 流程時,請考慮將其放在 ProxyEndpoint 回應中,也就是名為 PostClientFlow 的特殊流程。PostClientFlow 會在回應傳送至要求用戶端後執行,確保所有指標都可供記錄。如要瞭解如何使用 PostClientFlow,請參閱 API Proxy 設定參考資料

PostClientFlow 有兩項特殊之處:

  1. 只會在回覆流程中執行。
  2. 這是 Proxy 進入錯誤狀態後執行的唯一流程。

無論 Proxy 是否成功或失敗,系統都會執行這項政策,因此您可以將 MessageLogging 政策放在 PostClientFlow 中,確保政策一律會執行。

下圖顯示在 DefaultFaultRule 執行後,MessageLogging 政策在 PostClientFlow 中執行的偵錯畫面:

在本例中,由於金鑰無效,因此「驗證 API 金鑰」政策導致錯誤。

以下是包含 PostClientFlow 的 ProxyEndpoint 定義:

<ProxyEndpoint name="default">
  ...
  <PostClientFlow>
    <Response>
      <Step>
        <Name>Message-Logging-1</Name>
      </Step>
    </Response>
  </PostClientFlow>
  ...
</ProxyEndpoint>

Apigee 會將訊息記錄為簡單文字,您可以設定記錄檔,加入變數,例如收到要求或回應的日期和時間、要求中的使用者身分、傳送要求的來源 IP 位址等。

Apigee 會非同步記錄訊息:系統會傳回回應,但記錄檔仍在寫入中。因此,封鎖呼叫不會導致 API 延遲。有時系統可能不會寫入記錄,也不會傳回錯誤,但這種情況很少發生。

MessageLogging 政策會將記錄的訊息寫入記憶體中的緩衝區。訊息記錄器會從緩衝區讀取訊息,然後寫入您設定的目的地。每個目的地都有自己的緩衝區。

如果寫入緩衝區的速率超過讀取速率,緩衝區就會溢位,導致記錄作業失敗。如果發生這種情況,您可能會在記錄檔中看到下列其中一則訊息:

  • 使用 <CloudLogging>
    steps.messagelogging.TooManyPendingLoggingRequest
  • 使用 <Syslog>
    Log message size exceeded. Increase the max message size setting

message-logging.properties 檔案中增加 max.log.message.size.in.kb 屬性 (預設值為 128 KB)。

訊息範本中變數的預設值

您可以分別為訊息範本中的每個變數指定預設值。舉例來說,如果無法解析變數 request.header.id,系統會將其值替換為 unknown

<Message>This is a test message. id = {request.header.id:unknown}</Message>

您可以為所有未解析的變數指定通用預設值,方法是在 Message 元素上設定 defaultVariableValue 屬性:

<Message defaultVariableValue="unknown">This is a test message. id = {request.header.id}</Message>

設定第三方記錄檔管理服務

您可以使用 MessageLogging 政策,將系統記錄訊息傳送至第三方記錄管理服務,例如 Splunk、Sumo Logic 和 Loggly。如要將系統記錄傳送至其中一項服務,請參閱該服務的說明文件,設定服務的主機、通訊埠和通訊協定,然後據此設定這項政策的 Syslog 元素。

如要瞭解第三方記錄檔管理設定,請參閱下列說明文件:

錯誤參考資料

This section describes the fault codes and error messages that are returned and fault variables that are set by Apigee when this policy triggers an error. This information is important to know if you are developing fault rules to handle faults. To learn more, see What you need to know about policy errors and Handling faults.

Runtime errors

These errors can occur when the policy executes.

Fault code HTTP status Cause
steps.messagelogging.StepDefinitionExecutionFailed 500 See fault string.
steps.messagelogging.InvalidGoogleCloudLogName 500 This error is thrown when the LogName does not evaluate to the valid format of projects/{project}/logs/{logid}.
steps.messagelogging.InvalidJsonMessage 500 This error is thrown when the contentType attributes value has been chosen as application/json but the actual message value is not a valid JSON string,
steps.messagelogging.TooManyPendingLoggingRequest 500 This error is thrown when there are more than 2500 pending requests that are yet to be written to Cloud Logging. The 2500 limit is for each Apigee runtime pod. For example, if the traffic is distributed over two instances of Apigee runtime pods, the effective limit is 5000 requests.
-

Deployment errors

These errors can occur when you deploy a proxy containing this policy.

Error name Cause Fix
InvalidProtocol The deployment of the MessageLogging policy can fail with this error if the protocol specified within the <Protocol> element is not valid. The valid protocols are TCP and UDP. For sending syslog messages over TLS/SSL, only TCP is supported.
InvalidPort The deployment of the MessageLogging policy can fail with this error if the port number is not specified within the <Port> element or if it is not valid. The port number must be an integer greater than zero.

Fault variables

These variables are set when a runtime error occurs. For more information, see What you need to know about policy errors.

Variables Where Example
fault.name="fault_name" fault_name is the name of the fault, as listed in the Runtime errors table above. The fault name is the last part of the fault code. fault.name Matches "StepDefinitionExecutionFailed"
messagelogging.policy_name.failed policy_name is the user-specified name of the policy that threw the fault. messagelogging.ML-LogMessages.failed = true

Example error response

{  
   "fault":{
      "detail":{
         "errorcode":"steps.messagelogging.StepDefinitionExecutionFailed"
      },
      "faultstring":"Execution failed"
   }
}

Example fault rule

<FaultRule name="MessageLogging">
    <Step>
        <Name>ML-LogMessages</Name>
        <Condition>(fault.name Matches "StepDefinitionExecutionFailed") </Condition>
    </Step>
    <Condition>(messagelogging.ML-LogMessages.failed = true) </Condition>
</FaultRule>


流程變數

政策失敗時,系統會填入下列變數。

  • messagelogging.failed
  • messagelogging.{stepdefinition-name}.failed

相關主題