

# 规范：嵌入式指标格式
<a name="CloudWatch_Embedded_Metric_Format_Specification"></a>

 CloudWatch 嵌入式指标格式是一个 JSON 规范，用于指示 CloudWatch Logs 自动提取结构化日志事件中嵌入的指标值。您可以使用 CloudWatch 基于提取的指标值绘制图表并创建告警。本节介绍嵌入式指标格式规范约定和嵌入式指标格式文档结构。

## 嵌入式指标格式规范约定
<a name="CloudWatch_Embedded_Metric_Format_Specification_Conventions"></a>

此格式规范中的关键字“MUST”、“MUST NOT”、“REQUIRED”、“SHALL”、“SHALL NOT”、“SHOULD”、“SHOULD NOT”、“RECOMMENDED”、“MAY”和“OPTIONAL”的解释如[关键字 RFC2119](http://tools.ietf.org/html/rfc2119) 中所述。

此格式规范中的属于“JSON”、“JSON text”、“JSON value”、“member”、“element”、“object”、“array”、“number”、“string”、“boolean”、“true”、“false”和“null”的解释如 [JavaScript 对象表示法 RFC8259](https://tools.ietf.org/html/rfc8259) 中所述。

**注意**  
如果您计划为使用嵌入式指标格式创建的指标创建告警，请参阅 [为使用嵌入式指标格式创建的指标设置警报](CloudWatch_Embedded_Metric_Format_Alarms.md) 获取相关建议。

## 嵌入式指标格式文档结构
<a name="CloudWatch_Embedded_Metric_Format_Specification_structure"></a>

此节介绍了嵌入式指标格式文档的结构。嵌入式指标格式文档用 [JavaScript 对象表示法 RFC8259](https://tools.ietf.org/html/rfc8259) 进行定义。

除非另有说明，否则此规范定义的对象不得包含任何其他成员。必须忽略此规范无法识别的成员。此规范中定义的成员是区分大小写的。

嵌入式指标格式受与标准 CloudWatch Logs 事件相同的限制，并且其最大大小限制为 1MB。

 通过嵌入式指标格式，您可以按指标跟踪发布在您账户的 `AWS/Logs` 命名空间中的 EMF 日志的处理。可通过这些日志跟踪 EMF 中指标生成失败的情况，以及失败的原因是解析还是验证。有关更多详细信息，请参阅[使用 CloudWatch 指标监控](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CloudWatch-Logs-Monitoring-CloudWatch-Metrics.html)。

### 根节点
<a name="CloudWatch_Embedded_Metric_Format_Specification_structure_root"></a>

LogEvent 消息必须是一个有效的 JSON 对象，并且 LogEvent 消息字符串的开头或结尾没有其他数据。有关 LogEvent 结构的更多信息，请参阅 [InputLogEvent](https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_InputLogEvent.html)。

嵌入式指标格式文档必须包含根节点上的以下顶级成员。这是一个 [元数据对象](#CloudWatch_Embedded_Metric_Format_Specification_structure_metadata) 对象。

```
{
 "_aws": {
    "CloudWatchMetrics": [ ... ]
  }
}
```

根节点必须包含由 [MetricDirective 对象](#CloudWatch_Embedded_Metric_Format_Specification_structure_metricdirective) 中的引用定义的所有 [目标成员](#CloudWatch_Embedded_Metric_Format_Specification_structure_target) 成员。

根节点可以包含上述要求中未包含的任何其他成员。这些成员的值必须是有效的 JSON 类型。

### 元数据对象
<a name="CloudWatch_Embedded_Metric_Format_Specification_structure_metadata"></a>

`_aws` 成员可用于表示有关负载的元数据，告知下游服务应如何处理 LogEvent。该值必须是一个对象，并且必须包含以下成员：
+ **CloudWatchMetrics** – 一个 [MetricDirective 对象](#CloudWatch_Embedded_Metric_Format_Specification_structure_metricdirective) 数组，用于指示 CloudWatch 从 LogEvent 的根节点提取指标。

  ```
  {
    "_aws": {
      "CloudWatchMetrics": [ ... ]
    }
  }
  ```
+ **时间戳** – 一个数字，表示用于从事件中提取的指标的时间戳。值必须表示为自 1970 年 1 月 1 日 00:00:00 UTC 以来的毫秒数。

  ```
  {
    "_aws": {
      "Timestamp": 1559748430481
    }
  }
  ```

### MetricDirective 对象
<a name="CloudWatch_Embedded_Metric_Format_Specification_structure_metricdirective"></a>

MetricDirective 对象指示下游服务 LogEvent 包含将提取并发布到 CloudWatch 的指标。MetricDirectives 必须包含以下成员：
+ **命名空间** – 一个表示指标的 CloudWatch 命名空间的字符串。
+ **维度** – 一个 [DimensionSet 数组](#CloudWatch_Embedded_Metric_Format_Specification_structure_dimensionset)。
+ **指标** – 一个 [MetricDefinition 对象](#CloudWatch_Embedded_Metric_Format_Specification_structure_metricdefinition) 对象数组。此数组不得包含 100 个以上的 MetricDefinition 对象。

### DimensionSet 数组
<a name="CloudWatch_Embedded_Metric_Format_Specification_structure_dimensionset"></a>

DimensionSet 是一个字符串数组，其中包含将应用于文档中的所有指标的维度键。此数组中的值也必须是根节点上的成员 - 称为 [目标成员](#CloudWatch_Embedded_Metric_Format_Specification_structure_target)

DimensionSet 不得包含 30 个以上的维度键。DimensionSet 可以为空。

目标成员必须具有字符串值。此值不得包含 1024 个以上的字符。目标成员定义了将作为指标标识的一部分发布的维度。使用的每个 DimensionSet 都会在 CloudWatch 中创建一个新指标。有关维度的更多信息，请参阅[维度](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_Dimension.html)和[维度](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Dimension)。

```
{
 "_aws": {
   "CloudWatchMetrics": [
     {
       "Dimensions": [ [ "functionVersion" ] ],
       ...
     }
   ]
 },
 "functionVersion": "$LATEST"
}
```

**注意**  
配置指标提取时请务必小心，因为它会影响自定义指标的使用和相应的账单。如果您无意中创建了基于高基数维度的指标（例如 `requestId`），则嵌入式指标格式将通过设计创建与每个唯一维度组合对应的自定义指标。有关更多信息，请参阅[维度](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Dimension)。

### MetricDefinition 对象
<a name="CloudWatch_Embedded_Metric_Format_Specification_structure_metricdefinition"></a>

MetricDefinition 是一个必须包含以下成员的对象：
+ **名称** – 指标 [目标成员](#CloudWatch_Embedded_Metric_Format_Specification_structure_target) 的字符串 [参考值](#CloudWatch_Embedded_Metric_Format_Specification_structure_referencevalues)。指标目标必须是数值或数值数组。

MetricDefinition 对象可以包含以下成员：
+ **单位** – 一个可选字符串值，表示相应指标的度量单位。值应是有效的 CloudWatch 指标单位。有关有效单位的信息，请参阅 [MetricDatum](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_MetricDatum.html)。如果未提供值，则假定默认值为 NONE。
+ **StorageResolution** – 可选整数值，表示相应指标的存储分辨率。将此值设置为 1，这样会将此指标指定为高分辨率指标，以便 CloudWatch 以亚分钟分辨率将指标存储到 1 秒。将此值设置为 60，这样会将此指标指定为标准分辨率，CloudWatch 以 1 分钟分辨率存储该指标。值应是支持 CloudWatch 的有效分辨率，即 1 或 60。如果未提供值，则假定默认值为 60。

  有关高精度指标的更多信息，请参阅 [高精度指标](publishingMetrics.md#high-resolution-metrics)。

**注意**  
如果您计划为使用嵌入式指标格式创建的指标创建告警，请参阅 [为使用嵌入式指标格式创建的指标设置警报](CloudWatch_Embedded_Metric_Format_Alarms.md) 获取相关建议。

```
{
  "_aws": {
    "CloudWatchMetrics": [
      {
        "Metrics": [
          {
            "Name": "Time",
            "Unit": "Milliseconds",
            "StorageResolution": 60
          }
        ],
        ...
      }
    ]
  },
  "Time": 1
}
```

### 参考值
<a name="CloudWatch_Embedded_Metric_Format_Specification_structure_referencevalues"></a>

参考值是引用根节点上的 [目标成员](#CloudWatch_Embedded_Metric_Format_Specification_structure_target) 成员的字符串值。这些引用不应与 [RFC6901](https://tools.ietf.org/html/rfc6901) 中描述的 JSON 指针混淆。无法嵌套目标值。

### 目标成员
<a name="CloudWatch_Embedded_Metric_Format_Specification_structure_target"></a>

有效目标必须是根节点上的成员，而不能是嵌套对象。例如，`"A.a"` 的参考值必须与以下成员匹配：

```
{ "A.a" }
```

它不得与嵌套成员匹配：

```
{ "A": { "a" } }
```

目标成员的有效值取决于引用它们的对象。指标目标必须是数值或数值数组。数字数组指标目标的成员不得超过 100 个。维度目标必须具有字符串值。

### 嵌入式指标格式示例和 JSON 架构
<a name="CloudWatch_Embedded_Metric_Format_Specification_structure_example"></a>

以下是嵌入式指标格式的有效示例。

```
{
  "_aws": {
    "Timestamp": 1574109732004,
    "CloudWatchMetrics": [
      {
        "Namespace": "lambda-function-metrics",
        "Dimensions": [["functionVersion"]],
        "Metrics": [
          {
            "Name": "time",
            "Unit": "Milliseconds",
            "StorageResolution": 60
          }
        ]
      }
    ]
  },
  "functionVersion": "$LATEST",
  "time": 100,
  "requestId": "989ffbf8-9ace-4817-a57c-e4dd734019ee"
}
```

您可以使用以下架构验证嵌入式指标格式文档。

```
{
    "type": "object",
    "title": "Root Node",
    "required": [
        "_aws"
    ],
    "properties": {
        "_aws": {
            "$id": "#/properties/_aws",
            "type": "object",
            "title": "Metadata",
            "required": [
                "Timestamp",
                "CloudWatchMetrics"
            ],
            "properties": {
                "Timestamp": {
                    "$id": "#/properties/_aws/properties/Timestamp",
                    "type": "integer",
                    "title": "The Timestamp Schema",
                    "examples": [
                        1565375354953
                    ]
                },
                "CloudWatchMetrics": {
                    "$id": "#/properties/_aws/properties/CloudWatchMetrics",
                    "type": "array",
                    "title": "MetricDirectives",
                    "items": {
                        "$id": "#/properties/_aws/properties/CloudWatchMetrics/items",
                        "type": "object",
                        "title": "MetricDirective",
                        "required": [
                            "Namespace",
                            "Dimensions",
                            "Metrics"
                        ],
                        "properties": {
                            "Namespace": {
                                "$id": "#/properties/_aws/properties/CloudWatchMetrics/items/properties/Namespace",
                                "type": "string",
                                "title": "CloudWatch Metrics Namespace",
                                "examples": [
                                    "MyApp"
                                ],
                                "pattern": "^(.*)$",
                                "minLength": 1,
                                "maxLength": 1024
                            },
                            "Dimensions": {
                                "$id": "#/properties/_aws/properties/CloudWatchMetrics/items/properties/Dimensions",
                                "type": "array",
                                "title": "The Dimensions Schema",
                                "minItems": 1,
                                "items": {
                                    "$id": "#/properties/_aws/properties/CloudWatchMetrics/items/properties/Dimensions/items",
                                    "type": "array",
                                    "title": "DimensionSet",
                                    "minItems": 0,
                                    "maxItems": 30,
                                    "items": {
                                        "$id": "#/properties/_aws/properties/CloudWatchMetrics/items/properties/Dimensions/items/items",
                                        "type": "string",
                                        "title": "DimensionReference",
                                        "examples": [
                                            "Operation"
                                        ],
                                        "pattern": "^(.*)$",
                                        "minLength": 1,
                                        "maxLength": 250
}
                                }
                            },
                            "Metrics": {
                                "$id": "#/properties/_aws/properties/CloudWatchMetrics/items/properties/Metrics",
                                "type": "array",
                                "title": "MetricDefinitions",
                                "items": {
                                    "$id": "#/properties/_aws/properties/CloudWatchMetrics/items/properties/Metrics/items",
                                    "type": "object",
                                    "title": "MetricDefinition",
                                    "required": [
                                        "Name"
                                    ],
                                    "properties": {
                                        "Name": {
                                            "$id": "#/properties/_aws/properties/CloudWatchMetrics/items/properties/Metrics/items/properties/Name",
                                            "type": "string",
                                            "title": "MetricName",
                                            "examples": [
                                                "ProcessingLatency"
                                            ],
                                            "pattern": "^(.*)$",
                                            "minLength": 1,
                                            "maxLength": 1024
                                        },
                                        "Unit": {
                                            "$id": "#/properties/_aws/properties/CloudWatchMetrics/items/properties/Metrics/items/properties/Unit",
                                            "type": "string",
                                            "title": "MetricUnit",
                                            "examples": [
                                                "Milliseconds"
                                            ],
                                            "pattern": "^(Seconds|Microseconds|Milliseconds|Bytes|Kilobytes|Megabytes|Gigabytes|Terabytes|Bits|Kilobits|Megabits|Gigabits|Terabits|Percent|Count|Bytes\\/Second|Kilobytes\\/Second|Megabytes\\/Second|Gigabytes\\/Second|Terabytes\\/Second|Bits\\/Second|Kilobits\\/Second|Megabits\\/Second|Gigabits\\/Second|Terabits\\/Second|Count\\/Second|None)$"
                                         },
                                         "StorageResolution": {
                                            "$id": "#/properties/_aws/properties/CloudWatchMetrics/items/properties/Metrics/items/properties/StorageResolution",
                                            "type": "integer",
                                            "title": "StorageResolution",
                                            "examples": [
                                                60
                                            ]
                                         }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
```

## 采用 EMF 格式的实体信息
<a name="entity-information-emf-format"></a>

使用嵌入式指标格式（EMF）将日志发布到 Amazon CloudWatch 时，您可以将实体信息包含在日志事件中。本部分介绍如何指定实体信息以及 CloudWatch 如何处理这些信息。

### 实体类型
<a name="entity-types-emf"></a>

如果 `PutLogEvents` 请求中未指定任何实体，则 CloudWatch 会在 EMF 日志内容中查找实体信息：
+ **服务类型的实体**

  必填字段：`Service` 和 `Environment`
+ **资源类型的实体**

  必填字段：`ResourceType` 和 `Identifier`

### 平台属性
<a name="platform-attributes-emf"></a>

CloudWatch 根据以下属性自动确定平台类型：
+ **Kubernetes (K8s)：**

  必需：`K8s.Cluster`

  可选：`K8s.Namespace`、`K8s.Workload`、`K8s.Node`、`K8s.Pod`、`EC2.InstanceId`、`EC2.AutoScalingGroup`
+ **Amazon EKS**

  必需：`EKS.Cluster`

  可选：`K8s.Namespace`、`K8s.Workload`、`K8s.Node`、`K8s.Pod`、`EC2.InstanceId`
+ **Amazon ECS：**

  必需：`ECS.Cluster`

  可选：`ECS.Service`、`ECS.Task`
+ **Amazon EC2**

  必需：`EC2.InstanceId`

  可选：`EC2.AutoScalingGroup`
+ **Lambda：**

  必需：`Lambda.Function`
+ **通用主机：**

  必需：`Host`

### EMF 日志格式示例
<a name="example-emf-log-format"></a>

```
{
    "_aws": {
        "CloudWatchMetrics": [
            {
                "Metrics": [
                    {"Name": "RequestLatency", "Unit": "Milliseconds"}
                ],
                "Namespace": "MyApplication"
            }
        ]
    },
    "Service": "PaymentService",
    "Environment": "Production",
    "K8s.Cluster": "main-cluster",
    "K8s.Namespace": "payment-ns",
    "K8s.Pod": "payment-pod-123",
    "K8s.Node": "worker-node-1",
    "K8s.Workload": "payment-deployment",
    "RequestLatency": 135.5,
    "timestamp": 1622163600000
}
```

### 所生成实体
<a name="generated-entity-emf"></a>

以上 EMF 日志将会生成下列实体：

```
{
    "KeyAttributes": {
        "Type": "Service",
        "Name": "PaymentService",
        "Environment": "Production"
    },
    "Attributes": {
        "PlatformType": "K8s",
        "K8s.Cluster": "main-cluster",
        "K8s.Namespace": "payment-ns",
        "K8s.Pod": "payment-pod-123",
        "K8s.Node": "worker-node-1",
        "K8s.Workload": "payment-deployment"
    }
}
```

### 实体处理
<a name="entity-processing-emf"></a>

CloudWatch 处理实体信息的方式如下：
+ **关键属性：**
  + 按照必填字段来确定实体类型
  + 针对服务类型，可提取服务名称与环境
  + 这些将成为该实体的主要标识符
+ **属性**：
  + 根据所含平台属性来设置平台类型
  + 包含所有与平台相关的特定信息
  + 保持遥测数据的关系情境

CloudWatch 利用该实体信息建立不同遥测数据间的关联关系，由此增强对应用程序与基础设施的可观测性，并支持情境分析。如需更多信息，请参阅[如何向发送到 CloudWatch 的自定义遥测添加相关信息](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/adding-your-own-related-telemetry.html)。

**注意**  
实体信息有助于 CloudWatch 构建应用程序遥测数据的完整视图，并清晰呈现这些数据在基础设施中的关联关系。