MessageLogging 政策

本页面适用于 ApigeeApigee Hybrid

查看 Apigee Edge 文档。

内容

MessageLogging 政策允许您将自定义消息记录到 Cloud Logging 或 syslog。您可以将日志中的信息用于各种任务,例如跟踪 API 运行时环境中的问题。

此政策是一项可扩展政策,使用此政策可能会影响费用或使用情况,具体取决于您的 Apigee 许可。如需了解政策类型和使用情况影响,请参阅政策类型

您可以通过以下两种方式使用 MessageLogging 政策:

  • <CloudLogging> 元素将消息记录到 Cloud Logging。如需使用此方法,您需要为 Google Cloud 项目启用 Cloud Logging API。如需详细了解如何为 Google Cloud 项目启用 API,请参阅启用和停用服务
  • <Syslog> 元素将消息记录到 syslog,这是用于将系统日志或事件消息发送到特定服务器的标准协议。要使用此方法,您必须拥有 syslog 服务器。否则,您可以使用公共日志管理服务,例如 Splunk、Sumo Logic 和 Loggly。请参阅配置第三方日志管理服务

注意:您不能在同一政策中同时使用 <CloudLogging> 元素和 <Syslog> 元素。

<MessageLogging> 元素

定义 <MessageLogging> 政策。

默认值 请参阅下面的默认政策标签页
是否必需? 必需
类型 TYPE
父元素 不适用
子元素 <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>

This element has the following attributes that are common to all policies:

Attribute Default Required? Description
name N/A Required

The internal name of the policy. The value of the name attribute can contain letters, numbers, spaces, hyphens, underscores, and periods. This value cannot exceed 255 characters.

Optionally, use the <DisplayName> element to label the policy in the management UI proxy editor with a different, natural-language name.

continueOnError false Optional Set to false to return an error when a policy fails. This is expected behavior for most policies. Set to true to have flow execution continue even after a policy fails. See also:
enabled true Optional Set to true to enforce the policy. Set to false to turn off the policy. The policy will not be enforced even if it remains attached to a flow.
async   false Deprecated This attribute is deprecated.

下表提供了 <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" 的代理,生成的日志条目将为 {"fruit": "apple"}

Syslog

<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 的 Syslog

<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 属性,该属性的值可以是 text/plainapplication/json,分别用于文本和 JSON 消息。查看示例

Label 要附加到日志消息的标签(如有)。 它们将采用键值对的形式,如下所示:
<Label>
    <Key>key1</Key>
    <Value>value1</Value>
</Label>
ResourceType 否(默认为全球) 表示正在生成日志的受监控的资源。

Cloud Logging 身份验证

如需使用 <CloudLogging> 元素,您必须部署您的 API 代理以使用 Google 身份验证。Apigee 将使用与发送到 Cloud Logging 的出站请求中指定的服务账号身份对应的凭据。如需了解详情,请参阅使用 Google 身份验证

您在部署时附加到 API 代理的服务账号必须拥有包含 logging.logEntries.create 权限的角色。除非您需要更精细的控制,否则我们建议您为服务账号使用包含更多权限的预定义角色 roles/logging.logWriter。如需详细了解 <CloudLogging> 的 Identity and Access Management (IAM) 角色,请参阅访问权限控制指南

Apigee Hybrid 中的代理部署

如果您使用的是 Apigee Hybrid,则为 Apigee Hybrid 创建的运行时服务账号必须模拟代理服务账号,才能代表该账号进行经过身份验证的调用。因此,Apigee Hybrid 运行时服务账号必须拥有代理服务账号的 iam.serviceAccountTokenCreator 角色。

<Syslog>

使用 <Syslog> 元素配置要记录到 syslog 的消息。使用 <Syslog> 时,API 代理会将日志消息从 Apigee 转发到远程 syslog 服务器。要使用此方法,您必须拥有 syslog 服务器。如果您没有该服务器,也可以使用 Splunk、Sumo Logic 和 Loggly 等公共日志管理服务。请参阅配置第三方日志管理服务

字段名称 是否必需? 字段说明
Message

要记录的消息。该消息具有 contentType 属性,该属性的值可以是 text/plainapplication/json,分别用于文本和 JSON 消息。查看示例

Host 应将 syslog 发送到的服务器的主机名或 IP 地址。如果您不添加此元素,则默认为 localhost。
Port syslog 运行的端口。如果您未添加此元素,则默认为 514。
Protocol TCP 或 UDP(默认)。虽然 UDP 的性能更高,但 TCP 协议可保证将消息日志传送至 syslog 服务器。对于通过 TLS/SSL 发送 syslog 消息,系统仅支持 TCP。
FormatMessage 否,但使用 Loggly 需要 <FormatMessage>true</FormatMessage>

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 - 当前 syslog 版本。
  • 带世界协调时间 (UTC) 偏移量的日期 (UTC = +0000)。
  • 消息处理器 UUID。
  • "Apigee - - - "

如果设置为 false(默认),则消息不会附加这些固定字符。

PayloadOnly

truefalse(默认)

此元素会设置 Apigee 生成的消息的格式,使其仅包含 syslog 消息的正文,不带 FormatMessage 指定的附加字符。

如果您不添加此元素或将其留空,则默认值为 false

请参阅 FormatMessage

DateFormat

用于设置每个日志消息的时间戳格式的格式模板字符串。 默认情况下,Apigee 使用 yyyy-MM-dd'T'HH:mm:ss.SSSZJava 的 SimpleDateFormat 类文档中介绍了此模板的行为。根据该定义,格式字符串中的 yyyy 将被替换为 4 位数年份,MM 将被替换为 2 位数月份,依此类推。

SSLInfo

允许您通过 SSL/TLS 记录消息。与子元素 <Enabled>true</Enabled> 搭配使用。

如果您不添加此元素或将其留空,则默认值为 false(无 TLS/SSL)。

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

您可以配置 <SSLInfo> 标记,方式与在 TargetEndpoint 上相同,包括启用双向 TLS/SSL,如 API 代理配置参考文档中所述。系统仅支持 TCP 协议。


<logLevel>

<logLevel> 元素的有效值包括:INFO(默认)、ALERTWARNERROR

设置要包含在消息日志中的特定信息级别。

如果您使用 <logLevel> 元素(将其设置为 true),您的设置会影响在附加到消息的 Apigee 生成的信息中计算得出的优先级值(尖括号内的数字)。

使用说明

在将 MessageLogging 政策附加到 API 代理流时,请考虑将其放置在名为 PostClientFlow 的特殊流的 ProxyEndpoint 响应中。PostClientFlow 会在将响应请求发送到发出请求的客户端后执行,可确保所有指标都可供日志记录。如需详细了解如何使用 PostClientFlow,请参阅 API 代理配置参考文档

PostClientFlow 有以下两种特别之处:

  1. 它仅会作为响应流的一部分执行。
  2. 它是在代理进入错误状态后执行的唯一流。

由于无论代理是成功还是失败,系统都会执行它,因此您可以将 MessageLogging 政策放在 PostClientFlow 中,并保证它们始终执行。

以下调试图像显示在 DefaultFaultRule 执行后作为 PostClientFlow 一部分执行的 MessageLogging 政策:

在此示例中,由于 API 密钥无效,Verify API Key 政策导致故障。

下面显示了包括 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 政策允许您将 syslog 消息发送到第三方日志管理服务,例如 Splunk、Sumo Logic 和 Loggly。如果要将 syslog 发送到其中一个服务,请参阅该服务的文档以配置服务的主机、端口和协议,然后相应地设置此政策的 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

相关主题