

# 基础设施监控
<a name="CloudWatch-Insights-Sections"></a>

本部分中的主题介绍了 CloudWatch 的功能，这些功能可以帮助您获得对 AWS 资源的操作了解。

**Topics**
+ [Container Insights](ContainerInsights.md)
+ [Lambda Insights](Lambda-Insights.md)
+ [CloudWatch Database Insights](Database-Insights.md)
+ [使用 Contributor Insights 分析高基数数据](ContributorInsights.md)
+ [使用 CloudWatch Application Insights 检测常见应用程序问题](cloudwatch-application-insights.md)
+ [使用 CloudWatch 控制台中的资源运行状况视图](servicelens_resource_health.md)

# Container Insights
<a name="ContainerInsights"></a>

使用 CloudWatch Container Insights 可以从容器化应用程序和微服务中收集、聚合和汇总指标与日志。Container Insights 可用于 Amazon EC2 上的 Amazon Elastic Container Service (Amazon ECS)、Amazon Elastic Kubernetes Service (Amazon EKS)、RedHat OpenShift on AWS (ROSA) 和 Kubernetes 平台。Container Insights 支持从部署在 AWS Fargate 上的集群中收集针对 Amazon ECS 和 Amazon EKS 的指标。

CloudWatch 会自动收集许多资源（例如 CPU、内存、磁盘和网络）的指标。Container Insights 还提供诊断信息（如容器重新启动失败），以帮助您查明问题并快速解决问题。您还可以设置 Container Insights 收集的指标的 CloudWatch 告警。

Container Insights 使用[嵌入式指标格式](CloudWatch_Embedded_Metric_Format.md)将数据收集为*性能日志事件*。这些性能日志事件是使用结构化 JSON 架构的条目，该架构允许批量提取和存储高基数数据。从该数据中，CloudWatch 在集群、节点、pod、任务和服务级别创建聚合指标以作为 CloudWatch 指标。Container Insights 收集的指标可在 CloudWatch 自动控制面板中使用，也可在 CloudWatch 控制台的**指标**部分查看。容器任务运行一段时间后，指标才可见。

当您部署 Container Insights 时，它会自动为性能日志事件创建日志组。您无需自行创建该日志组。

为帮助您管理 Container Insights 成本，CloudWatch 不会根据日志数据自动创建所有可能的指标。但是，您可以通过使用 CloudWatch Logs Insights 分析原始性能日志事件来查看其他指标和其他精细级别。

在 Container Insights 的原始版本中，收集的指标和摄取的日志将作为自定义指标收费。借助针对 Amazon EKS 增强了可观测性的 Container Insights，Container Insights 指标和日志按每次观测收费，而不是按存储的指标或摄取的日志收费。有关 CloudWatch 定价的信息，请参阅 [Amazon CloudWatch 定价](https://aws.amazon.com/cloudwatch/pricing/)。

**[预览版]** 对于 Amazon EKS，采用 OpenTelemetry 指标的 Container Insights 提供了一种额外的指标模式，该模式使用 OpenTelemetry Protocol（OTLP）收集指标并支持 PromQL 查询。每个指标都补充了多达 150 个标签，包括 OpenTelemetry 语义惯例属性以及 Kubernetes 容器组（pod）和节点标签。有关更多信息，请参阅 [适用于 Amazon EKS 的采用 OpenTelemetry 指标的 Container Insights](container-insights-otel-metrics.md)。

在 Amazon EKS、RedHatOpenshift on AWS 和 Kubernetes 上，Container Insights 使用 CloudWatch 代理的容器化版本在集群中查找所有运行的容器。然后，它在每个性能堆栈层收集性能数据。

Container Insights 支持使用 AWS KMS key 对其收集的日志和指标进行加密。要启用此加密，必须手动为接收 Container Insights 数据的日志组启用 AWS KMS 加密。这将导致 Container Insights 使用提供的 KMS 密钥加密这些数据。仅支持对称密钥。请勿使用非对称 KMS 密钥加密日志组。

有关更多信息，请参阅[使用 AWS KMS 加密 CloudWatch Logs 中的日志数据](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/encrypt-log-data-kms.html)。

## 支持的平台
<a name="container-insights-platforms"></a>

Container Insights 可用于 Amazon EC2 实例上的 Amazon Elastic Container Service、Amazon Elastic Kubernetes Service、RedHat OpenShift on AWS 和 Kubernetes 平台。
+ 对于 Amazon ECS，Container Insights 同时在 Linux 和 Windows Server 实例上的集群、任务和服务级别收集指标。Container Insights 在 Linux 实例上只收集实例级别的指标。网络指标适用于使用 `bridge` 网络模式和 `awsvpc` 网络模式的容器，但不适用于使用 `host` 网络模式的容器。
+ 对于 Amazon Elastic Kubernetes Service 和 Amazon EC2 实例上的 Kubernetes 平台，仅在 Linux 和 Windows 实例上支持 Container Insights。
+ **[预览版]** 采用 OpenTelemetry 指标的 Container Insights 适用于 Amazon EKS。有关更多信息，请参阅 [适用于 Amazon EKS 的采用 OpenTelemetry 指标的 Container Insights](container-insights-otel-metrics.md)。

# 针对 Amazon ECS 增强了可观测性的 Container Insights
<a name="container-insights-detailed-ecs-metrics"></a>

2024 年 12 月 2 日，AWS 发布了针对 Amazon ECS 增强了可观测性的 Container Insights。此版本支持针对使用 Amazon EC2 和 Fargate 启动类型的 Amazon ECS 集群增强型可观测性。在 Amazon ECS 上配置具有增强型可观测性的 Container Insights 后，Container Insights 会自动收集环境中从集群级别到容器级别的详细基础设施遥测数据，并在精选的控制面板中显示这些关键性能数据，从而减轻可观测性设置中的繁琐工作。有关如何设置具有增强型可观测性 Container Insights 的信息，请参阅[在 Amazon ECS 上设置 Container Insights](deploy-container-insights-ECS-cluster.md)。

具有增强型可观测性的 Container Insights 提供了所有 Container Insights 指标，以及其他任务和容器指标。有关更多信息，请参阅 [具有增强型可观测性的 Amazon ECS Container Insights](Container-Insights-enhanced-observability-metrics-ECS.md)。

具有增强型可观测性的 Container Insights 还支持 CloudWatch 跨账户可观测性。可以使用一个监控账户对单区域内跨多个 AWS 账户的应用程序进行监控和问题排查。有关更多信息，请参阅 [CloudWatch 跨账户可观察性](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Unified-Cross-Account.html)。

# 针对 Amazon EKS 增强了可观测性的 Container Insights
<a name="container-insights-detailed-metrics"></a>

2023 年 11 月 6 日，发布了 Container Insights 的新版本。此版本支持针对在 Amazon EC2 上运行的 Amazon EKS 集群增强的可观测性，并且可以从这些集群收集更详细的指标。安装后，它会自动为您的 Amazon EKS 集群收集详细的基础设施遥测数据和容器日志。然后，您可以使用精选的、可立即使用的控制面板，深入研究应用程序和基础设施的遥测数据。

针对 Amazon EKS 增强了可观测性的 Container Insights 可收集容器级别的精细运行状况、性能和状态指标，以及控制面板指标。有关收集的其他指标和维度的更多信息，请参阅 [具有增强型可观测性的 Amazon EKS 和 Kubernetes Container Insights](Container-Insights-metrics-enhanced-EKS.md)。

如果您在 2023 年 11 月 6 日之后在 Amazon EC2 上的 Amazon EKS 集群上使用 CloudWatch 代理安装了 Container Insights，便拥有针对 Amazon EKS 增强了可观测性的 Container Insights。否则，您可以按照 [在 CloudWatch 中升级到针对 Amazon EKS 增强了可观测性的 Container Insights](Container-Insights-upgrade-enhanced.md) 中的说明将 Amazon EKS 集群升级到此新版本。

Container Insights 支持 CloudWatch 跨账户可观测性。您可以使用一个监控账户对一个区域内跨多个 AWS 账户的应用程序进行监控和问题排查。有关更多信息，请参阅 [CloudWatch 跨账户可观测性](CloudWatch-Unified-Cross-Account.md)。

针对 Amazon EKS 增强了可观测性的 Container Insights 还支持 Windows Worker 节点。

Fargate 不支持针对 Amazon EKS 增强了可观测性的 Container Insights。

**注意**  
通过导航到 Container Insights 控制台，您可以了解您的集群是否可以升级到针对 Amazon EKS 增强了可观测性的 Container Insights。为此，请在 CloudWatch 控制台的导航窗格中依次选择 **Insights**、**Container Insights**。在 Container Insights 控制台中，横幅会告知您是否有任何可以升级的 Amazon EKS 集群，并会链接到升级页面。

# 适用于 Amazon EKS 的采用 OpenTelemetry 指标的 Container Insights
<a name="container-insights-otel-metrics"></a>

**预览**  
采用 OpenTelemetry 指标的 Container Insights 可让您深入了解 Amazon EKS 集群基础设施的运行状况。该功能的公开预览版已在美国东部（弗吉尼亚州北部）、美国西部（俄勒冈州）、欧洲地区（爱尔兰）、亚太地区（新加坡）和亚太地区（悉尼）推出，且没有额外费用。

Amazon CloudWatch Observability EKS 附加组件从 Amazon EKS 集群收集开源指标，并使用 OpenTelemetry Protocol（OTLP）以 30 秒的粒度将其发送到 CloudWatch。这些指标使用其原始来源的指标名称，包括 cAdvisor、Prometheus Node Exporter、NVIDIA DCGM、Kube State Metrics 和 AWS Neuron Monitor。您可以在 CloudWatch Query Studio 中使用 PromQL 或通过兼容 Prometheus 的查询 API 来查询这些指标。

每个指标都会自动补充多达 150 个标签，包括 OpenTelemetry 语义惯例属性以及 Kubernetes 容器组（pod）和节点标签。PromQL 在查询时处理聚合，因此每个指标按每个资源发布一次，而不是在多个聚合级别发布。该附加组件还将来自 AWS Neuron 和 AWS Elastic Fabric Adapter 的加速器指标与使用这些指标的特定容器组（pod）和容器相关联，从而提供仅从指标来源无法获得的可见性。

要在 Amazon EKS 集群上启用 OTel Container Insights，请通过 Amazon EKS 控制台或基础设施即代码安装 Amazon CloudWatch Observability EKS 附加组件版本 `v6.0.1-eksbuild.1` 或更新版本。

有关设置 OTel Container Insights 的更多信息，请参阅[设置 Container Insights](deploy-container-insights.md)。

有关使用 PromQL 查询这些指标的更多信息，请参阅 [PromQL 查询](CloudWatch-PromQL-Querying.md)。

## OTel Container Insights 与 Container Insights 的对比情况（增强型）
<a name="container-insights-otel-comparison"></a>

下表总结了 Container Insights（增强型）与 OTel Container Insights 之间的区别。


| 功能 | Container Insights（增强型） | OTel Container Insights | 
| --- | --- | --- | 
| 指标名称 | CloudWatch 格式的指标（例如 pod\$1cpu\$1utilization） | 开源原生（例如 container\$1cpu\$1usage\$1seconds\$1total） | 
| 每个指标的标签数量 | 每个指标 3 – 6 个预定义维度 | 最多 150 个标签，包括所有 Kubernetes 容器组（pod）和节点标签 | 
| 聚合 | 在多个级别 [集群、命名空间、工作负载、容器组（pod）] 进行预聚合 | 每个资源的原始指标；使用 PromQL 在查询时聚合 | 
| 查询语言 | CloudWatch 指标 API | PromQL（兼容 Prometheus） | 
| 指标摄取 | EMF 格式的 CloudWatch Logs | OTLP 端点 | 

## 指标的标记方式
<a name="container-insights-otel-labels"></a>

OTel Container Insights 收集的每个指标都带有来自三个来源的标签。

遥测数据源原生标签  
来自原始指标来源的标签（例如，cAdvisor 提供诸如 `pod`、`namespace` 和 `container` 之类的标签）。这些标签作为数据点属性保留起来。

OpenTelemetry 资源属性  
该附加组件按照 [Kubernetes](https://opentelemetry.io/docs/specs/semconv/resource/k8s/)、[Host](https://opentelemetry.io/docs/specs/semconv/resource/host/) 和 [Cloud](https://opentelemetry.io/docs/specs/semconv/resource/cloud/)（例如 `k8s.pod.name`、`k8s.namespace.name`、`k8s.node.name`、`host.name` 和 `cloud.region`）的 OpenTelemetry 语义惯例附加资源属性。这些属性在所有指标源中均一致。

Kubernetes 容器组（pod）和节点标签  
从 Kubernetes API 中发现的所有容器组（pod）标签和节点标签都将作为前缀为 `k8s.pod.label` 和 `k8s.node.label` 的资源属性附加。

有关如何使用 PromQL 查询这些属性的更多信息，请参阅 [PromQL 查询](CloudWatch-PromQL-Querying.md)。

## 受支持的指标
<a name="container-insights-otel-supported-metrics"></a>

下表列出了 OTel Container Insights 收集的指标来源和类别。


| 指标来源 | 指标类别 | 先决条件 | 
| --- | --- | --- | 
| cAdvisor | CPU 指标 | - | 
| cAdvisor | 内存指标 | - | 
| cAdvisor | 网络指标 | - | 
| cAdvisor | 磁盘和文件系统指标 | - | 
| Prometheus Node Exporter | CPU 指标 | - | 
| Prometheus Node Exporter | 内存指标 | - | 
| Prometheus Node Exporter | 磁盘指标 | - | 
| Prometheus Node Exporter | 文件系统指标 | - | 
| Prometheus Node Exporter | 网络指标 | - | 
| Prometheus Node Exporter | 系统指标 | - | 
| Prometheus Node Exporter | VMStat 指标 | - | 
| Prometheus Node Exporter | Netstat 和套接字指标 | - | 
| NVIDIA DCGM | GPU 利用率和性能指标 | 必须安装 [NVIDIA 设备插件](https://github.com/NVIDIA/k8s-device-plugin)和 [NVIDIA 容器工具包](https://github.com/NVIDIA/nvidia-container-toolkit)。 | 
| NVIDIA DCGM | GPU 内存指标 | 必须安装 [NVIDIA 设备插件](https://github.com/NVIDIA/k8s-device-plugin)和 [NVIDIA 容器工具包](https://github.com/NVIDIA/nvidia-container-toolkit)。 | 
| NVIDIA DCGM | GPU 功耗和散热指标 | 必须安装 [NVIDIA 设备插件](https://github.com/NVIDIA/k8s-device-plugin)和 [NVIDIA 容器工具包](https://github.com/NVIDIA/nvidia-container-toolkit)。 | 
| NVIDIA DCGM | GPU 节流指标 | 必须安装 [NVIDIA 设备插件](https://github.com/NVIDIA/k8s-device-plugin)和 [NVIDIA 容器工具包](https://github.com/NVIDIA/nvidia-container-toolkit)。 | 
| NVIDIA DCGM | GPU 错误和可靠性指标 | 必须安装 [NVIDIA 设备插件](https://github.com/NVIDIA/k8s-device-plugin)和 [NVIDIA 容器工具包](https://github.com/NVIDIA/nvidia-container-toolkit)。 | 
| NVIDIA DCGM | GPU NVLink 指标 | 必须安装 [NVIDIA 设备插件](https://github.com/NVIDIA/k8s-device-plugin)和 [NVIDIA 容器工具包](https://github.com/NVIDIA/nvidia-container-toolkit)。 | 
| NVIDIA DCGM | GPU 信息指标 | 必须安装 [NVIDIA 设备插件](https://github.com/NVIDIA/k8s-device-plugin)和 [NVIDIA 容器工具包](https://github.com/NVIDIA/nvidia-container-toolkit)。 | 
| AWS Neuron Monitor | NeuronCore 指标 | 必须安装 [Neuron 驱动程序](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/general/setup/neuron-setup/pytorch/neuronx/ubuntu/torch-neuronx-ubuntu22.html)和 [Neuron 设备插件](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/containers/kubernetes-getting-started.html)。 | 
| AWS Neuron Monitor | NeuronDevice 指标 | 必须安装 [Neuron 驱动程序](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/general/setup/neuron-setup/pytorch/neuronx/ubuntu/torch-neuronx-ubuntu22.html)和 [Neuron 设备插件](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/containers/kubernetes-getting-started.html)。 | 
| AWS Neuron Monitor | Neuron 系统指标 | 必须安装 [Neuron 驱动程序](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/general/setup/neuron-setup/pytorch/neuronx/ubuntu/torch-neuronx-ubuntu22.html)和 [Neuron 设备插件](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/containers/kubernetes-getting-started.html)。 | 
| AWS Elastic Fabric Adapter | EFA 指标 | 必须安装 [EFA 设备插件](https://github.com/aws/eks-charts/tree/master/stable/aws-efa-k8s-device-plugin)。 | 
| NVMe | NVMe SMART 指标 | - | 
| Kube State Metrics | 容器组（pod）、节点、部署、DaemonSet、StatefulSet、ReplicaSet、任务、CronJob、服务、命名空间、PersistentVolume、PersistentVolumeClaim 指标 | - | 
| Kubernetes API 服务器 | API 服务器和 etcd 指标 | - | 

## CloudWatch 代理容器镜像
<a name="container-insights-download-limit"></a>

亚马逊在 Amazon Elastic Container Registry 上提供 CloudWatch 代理容器镜像。有关更多信息，请参阅 Amazon ECR 上的 [cloudwatch-agent](https://gallery.ecr.aws/cloudwatch-agent/cloudwatch-agent)。

# 设置 Container Insights
<a name="deploy-container-insights"></a>

对于 Amazon ECS、Amazon EKS 和 Kubernetes，Container Insights 设置过程不同。
+ [在 Amazon EKS 和 Kubernetes 上设置 Container Insights](deploy-container-insights-EKS.md)
+ [在 Amazon ECS 上设置 Container Insights](deploy-container-insights-ECS.md)

**Topics**
+ [在 Amazon ECS 上设置 Container Insights](deploy-container-insights-ECS.md)
+ [在 Amazon EKS 和 Kubernetes 上设置 Container Insights](deploy-container-insights-EKS.md)
+ [在 RedHat OpenShift on AWS (ROSA) 上设置 Container Insights](deploy-container-insights-RedHatOpenShift.md)

# 在 Amazon ECS 上设置 Container Insights
<a name="deploy-container-insights-ECS"></a>

您可以使用以下一个或两个选项在 Amazon ECS 集群上启用 Container Insights：
+ 使用 AWS 管理控制台或 AWS CLI 开始收集集群级别、任务级别和服务级别指标。
+ 将 CloudWatch 代理部署为进程守护程序服务，来开始采集 Amazon EC2 实例上托管的集群的实例级别指标。

**Topics**
+ [在 Amazon ECS 上设置 Container Insights](deploy-container-insights-ECS-cluster.md)
+ [使用 AWS Distro for OpenTelemetry 在 Amazon ECS 上设置 Container Insights](deploy-container-insights-ECS-adot.md)
+ [部署 CloudWatch 代理以收集 Amazon ECS 上的 EC2 实例级别指标](deploy-container-insights-ECS-instancelevel.md)
+ [部署 AWS Distro for OpenTelemetry 以收集 Amazon ECS 集群上的 EC2 实例级指标](deploy-container-insights-ECS-OTEL.md)
+ [设置 Firelens 以向 CloudWatch Logs 发送日志](deploy-container-insights-ECS-logs.md)

# 在 Amazon ECS 上设置 Container Insights
<a name="deploy-container-insights-ECS-cluster"></a>

可以使用 Amazon ECS 控制台或 AWS CLI 在新的和现有的 Amazon ECS 集群上设置具有增强型可观测性的 Container Insights 或 Container Insights。Container Insights 在集群、任务和服务级别收集指标。具有增强型可观测性的 Container Insights 可提供其他维度和指标，以便深入了解容器级别的可见性。

如果在 Amazon EC2 实例上使用 Amazon ECS，则必须使用包含 Amazon ECS 代理版本 1.29 或更高版本的 AMI 启动该实例。有关更新代理版本的信息，请参阅[更新 Amazon ECS 容器代理](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-agent-update.html)。

**注意**  
如果用于 Amazon ECS Container Insights 指标的客户自主管理型 AWS KMS 密钥尚未配置为与 CloudWatch 配合使用，则必须更新密钥政策，以便允许在 CloudWatch Logs 中使用加密日志。您还必须将自己的 AWS KMS 密钥与 `/aws/ecs/containerinsights/ClusterName/performance` 中的日志组相关联。有关更多信息，请参阅[使用 AWS Key Management Service 对 CloudWatch Logs 中的日志数据进行加密](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/encrypt-log-data-kms.html)。

我们建议您使用具有增强型可观测性的 Container Insights，而不是 Container Insights，因为前者可以在容器环境中提供详细的可见性，从而缩短解决问题的平均时间。

## 设置具有增强型可观测性的 Container Insights
<a name="set-container-insights-ECS-cluster-enhanced"></a>

可以使用 Amazon ECS 控制台或 AWS CLI 启用具有增强型可观测性的 Container Insights。

------
#### [ AWS CLI ]

使用以下命令启用具有增强型可观测性的 Container Insights。

 将 `containerInsights` 账户设置设置为 `enhanced`

```
aws ecs put-account-setting --name containerInsights --value enhanced
```

 输出示例

```
{
    "setting": {
        "name": "containerInsights",
        "value": "enhanced",
        "principalArn": "arn:aws:iam::123456789012:johndoe",
         "type": user
    }
}
```

**注意**  
默认情况下，仅 `put-account-setting` 适用于当前已经过身份验证的用户。要为所有用户和角色启用账户范围的设置，请使用根用户，如以下示例所示。  

```
aws ecs put-account-setting --name containerInsights --value enhanced --principal-arn arn:aws:iam::accountID:root
```

设置此账户设置后，所有新集群都会自动使用具有增强型可观测性的 Container Insights。使用 `update-cluster-settings` 命令将具有增强型可观测性的 Container Insights 添加到现有集群，或者将当前使用 Container Insights 的集群升级为具有增强型可观测性的 Container Insights。

```
aws ecs update-cluster-settings --cluster cluster-name --settings name=containerInsights,value=enhanced
```

------
#### [ Amazon ECS console ]

1. 在 [https://console.aws.amazon.com/ecs/v2](https://console.aws.amazon.com/ecs/v2) 打开控制台。

1. 在顶部的导航栏中，选择要查看其账户设置的区域。

1. 在导航页面中，选择 **Account Settings**（账户设置）。

1. 选择**更新**。

1. 要使用具有增强型可观测性的 Container Insights，请选择**具有增强型可观测性的 Container Insights**。

1. 选择**保存更改**。

1. 在确认屏幕上，选择**确认**以保存选择。

进行此设置后，所有新集群都会自动使用具有增强型可观测性的 Container Insights。可以将具有增强型可观测性的 Container Insights 添加到现有集群，或者将当前使用 Container Insights 的集群升级为具有增强型可观测性的 Container Insights。有关更多信息，请参阅《Amazon Elastic Container Service 开发人员指南》中的[更新 Amazon ECS 集群](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/update-cluster-v2.html)。**

------

## 设置 Container Insights
<a name="set-container-insights-ECS-cluster"></a>

可以使用 Amazon ECS 控制台或 AWS CLI 启用 Container Insights。

------
#### [ AWS CLI ]

要使用 Container Insights，请将 `container Insights` 账户设置设置为 `enabled`。使用以下命令启用 Container Insights。

```
aws ecs put-account-setting --name containerInsights --value enabled
```

 输出示例

```
{
    "setting": {
        "name": "container Insights",
        "value": "enabled",
        "principalArn": "arn:aws:iam::123456789012:johndoe",
         "type": user
    }
}
```

将 `container Insights` 账户设置设为 `enabled` 时，默认情况下，所有新集群都会启用 Container Insights。使用 `update-cluster-settings` 命令将 Container Insights 添加到现有集群。

```
aws ecs update-cluster-settings --cluster cluster-name --settings name=containerInsights,value=enabled
```

------
#### [ Amazon ECS console ]

1. 在 [https://console.aws.amazon.com/ecs/v2](https://console.aws.amazon.com/ecs/v2) 打开控制台。

1. 在顶部的导航栏中，选择要查看其账户设置的区域。

1. 在导航页面中，选择 **Account Settings**（账户设置）。

1. 选择**更新**。

1. 要使用 Container Insights，请选择 **Container Insights**。

1. 选择**保存更改**。

1. 在确认屏幕上，选择**确认**以保存选择。

进行此设置后，所有新集群都会自动使用 Container Insights。更新现有集群来添加 Container Insights。有关更多信息，请参阅《Amazon Elastic Container Service 开发人员指南》中的[更新 Amazon ECS 集群](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/update-cluster-v2.html)。**

------

# 使用 AWS Distro for OpenTelemetry 在 Amazon ECS 上设置 Container Insights
<a name="deploy-container-insights-ECS-adot"></a>

如果需要使用 AWS Distro for OpenTelemetry 在 Amazon ECS 集群上设置 CloudWatch Container Insights，请使用此部分。有关 AWS Distro for Open Telemetry 的更多信息，请参阅 [AWS Distro for OpenTelemetry](https://aws.amazon.com/otel/)。

这些步骤假设您已具有正在运行 Amazon ECS 的集群。有关将 AWS Distro for Open Telemetry 与 Amazon ECS 结合使用以及为此设置 Amazon ECS 集群的更多信息，请参阅[在 Amazon Elastic Container Service 中设置 AWS Distro for OpenTelemetry Collector](https://aws-otel.github.io/docs/setup/ecs)。

## 步骤 1：创建任务角色
<a name="deploy-container-insights-ECS-adot-CreateTaskRole"></a>

第一步是在集群中创建 AWS OpenTelemetry Collector 将使用的任务角色。

**为 AWS Distro for OpenTelemetry 创建任务角色**

1. 通过 [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) 打开 IAM 控制台。

1. 在导航窗格中选择**策略**，然后选择**创建策略**。

1. 选择 **JSON** 选项卡，然后复制以下策略：

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": [
                   "logs:PutLogEvents",
                   "logs:CreateLogGroup",
                   "logs:CreateLogStream",
                   "logs:DescribeLogStreams",
                   "logs:DescribeLogGroups",
                   "ssm:GetParameters"
               ],
               "Resource": "*"
           }
       ]
   }
   ```

------

1. 选择**查看策略**。

1. 对于名称，输入 **AWSDistroOpenTelemetryPolicy**，然后选择 **Create policy（创建策略）**。

1. 在左侧的导航窗格中，选择 **Roles（角色）**，然后选择 **Create role（创建角色）**。

1. 在服务列表中，选择 **Elastic Container Service（Elastic Container 服务）**。

1. 在页面下方，选择 **Elastic Container Service Task（Elastic Container 服务任务）**，然后选择 **Next: Permissions（下一步：权限）**。

1. 在策略列表中，搜索 **AWSDistroOpenTelemetryPolicy**。

1. 选中 **AWSDistroOpenTelemetryPolicy** 旁的复选框。

1. 依次选择 **Next: Tags（下一步：标签）**和 **Next: Review（下一步：查看）**。

1. 对于 **Role name（角色名称）**，输入 **AWSOpenTelemetryTaskRole**，然后选择 **Create role（创建角色）**。

## 步骤 2：创建任务执行角色
<a name="deploy-container-insights-ECS-adot-CreateTaskExecutionRole"></a>

下一步是为 AWS OpenTelemetry Collector 创建任务执行角色。

**为 AWS Distro for OpenTelemetry 创建任务执行角色**

1. 通过 [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) 打开 IAM 控制台。

1. 在左侧的导航窗格中，选择 **Roles（角色）**，然后选择 **Create role（创建角色）**。

1. 在服务列表中，选择 **Elastic Container Service（Elastic Container 服务）**。

1. 在页面下方，选择 **Elastic Container Service Task（Elastic Container 服务任务）**，然后选择 **Next: Permissions（下一步：权限）**。

1. 在策略列表中，搜索 **AmazonECSTaskExecutionRolePolicy**，然后选中 **AmazonECSTaskExecutionRolePolicy** 旁的复选框。

1. 在策略列表中，搜索 **CloudWatchLogsFullAccess**，然后选中 **CloudWatchLogsFullAccess** 旁的复选框。

1. 在策略列表中，搜索 **AmazonSSMReadOnlyAccess**，然后选中 **AmazonSSMReadOnlyAccess** 旁的复选框。

1. 依次选择 **Next: Tags（下一步：标签）**和 **Next: Review（下一步：查看）**。

1. 对于 **Role name（角色名称）**，输入 **AWSOpenTelemetryTaskExecutionRole**，然后选择 **Create role（创建角色）**。

## 步骤 3：创建任务定义
<a name="deploy-container-insights-ECS-adot-CreateTaskDefinition"></a>

下一步是创建任务定义。

**为 AWS Distro for OpenTelemetry 创建任务定义**

1. 在 [https://console.aws.amazon.com/ecs/v2](https://console.aws.amazon.com/ecs/v2) 打开控制台。

1. 在导航窗格中，选择 **Task definitions**（任务定义）

1. 选择 **Create new task definition**（创建新的任务定义）、**Create new task definition**（创建新的任务定义）。

1. 对于**Task definition family**（任务定义系列）中，为任务定义指定唯一名称。

1. 配置您的容器，然后选择**下一步**。

1. 在**指标和日志记录**下，选择**使用指标收集**。

1. 选择**下一步**。

1. 选择**创建**。

有关将 AWS OpenTelemetry 收集器与 Amazon ECS 结合使用的更多信息，请参阅[在 Amazon Elastic Container Service 中设置 AWS Distro for OpenTelemetry Collector](https://aws-otel.github.io/docs/setup/ecs)。

## 步骤 4：运行任务
<a name="deploy-container-insights-ECS-adot-CreateTaskDefinition"></a>

最后一步是运行您创建的任务。

**运行 AWS Distro for OpenTelemetry 的任务**

1. 在 [https://console.aws.amazon.com/ecs/v2](https://console.aws.amazon.com/ecs/v2) 打开控制台。

1. 在左侧导航窗格中，选择 **Task Definitions（任务定义）**，然后选择您刚刚创建的任务。

1. 选择**操作**、**部署**、**运行任务**。

1. 选择 **Deploy**（部署）、**Run task**（运行任务）。

1. 在**计算选项**部分中，从**现有集群**中选择集群。

1. 选择**创建**。

1. 接下来，您可以在 CloudWatch 控制台中检查新指标。

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 在左侧导航窗格中，选择 **Metrics**。

   您会看到 **ECS/ContainerInsights** 命名空间。选择该命名空间，然后您会看到八个指标。

# 部署 CloudWatch 代理以收集 Amazon ECS 上的 EC2 实例级别指标
<a name="deploy-container-insights-ECS-instancelevel"></a>

要部署 CloudWatch 代理以从 EC2 实例上托管的 Amazon ECS 集群中收集实例级别指标，请使用具有默认配置的快速启动设置，或手动安装该代理以便对其进行自定义。

这两种方法都要求您已经部署了至少一个带有 EC2 启动类型的 Amazon ECS 集群，并且 CloudWatch 代理容器可以访问 Amazon EC2 实例元数据服务（IMDS）。有关 IMDS 的更多信息，请参阅[实例元数据和用户数据](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html)。

这些方法还假设您已安装 AWS CLI。此外，要在以下过程中运行这些命令，您必须登录到具有 **IAMFullAccess** 和 **AmazonECS\$1FullAccess** 策略的账户或角色。

**重要**  
在任务定义中定义 CloudWatch 代理容器时，请设置 `essential: false`。这样可防止在 CloudWatch 代理容器故障时，整个 Amazon ECS 服务随之停止。即使代理暂时不可用，其他关键应用程序容器也将会继续运行。

**Topics**
+ [使用 CloudFormation 进行快速设置](#deploy-container-insights-ECS-instancelevel-quickstart)
+ [手动和自定义设置](#deploy-container-insights-ECS-instancelevel-manual)

## 使用 CloudFormation 进行快速设置
<a name="deploy-container-insights-ECS-instancelevel-quickstart"></a>

要使用快速设置，请输入以下命令来使用 CloudFormation 安装代理。将 *cluster-name* 和 *cluster-region* 分别替换为您的 Amazon ECS 集群的名称和区域。

此命令将创建 IAM 角色，即 **CWAgentECSTaskRole** 和 **CWAgentECSExecutionRole**。如果您的账户中已有这些角色，请在输入命令时使用 `ParameterKey=CreateIAMRoles,ParameterValue=False` 而非 `ParameterKey=CreateIAMRoles,ParameterValue=True`。否则，此命令将失败。

```
ClusterName=cluster-name
Region=cluster-region
curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/ecs-task-definition-templates/deployment-mode/daemon-service/cwagent-ecs-instance-metric/cloudformation-quickstart/cwagent-ecs-instance-metric-cfn.json
aws cloudformation create-stack --stack-name CWAgentECS-${ClusterName}-${Region} \
    --template-body file://cwagent-ecs-instance-metric-cfn.json \
    --parameters ParameterKey=ClusterName,ParameterValue=${ClusterName} \
                 ParameterKey=CreateIAMRoles,ParameterValue=True \
    --capabilities CAPABILITY_NAMED_IAM \
    --region ${Region}
```

**（备选方案）使用您自己的 IAM 角色**

如果您要使用自己的自定义 ECS 任务角色和 ECS 任务执行角色，而不是使用 **CWAgentECSTaskRole** 和 **CWAgentECSExecutionRole** 角色，请先确保要用作 ECS 任务角色的角色已附加 **CloudWatchAgentServerPolicy**。此外，请确保要用作 ECS 任务执行角色的角色同时附加了 **CloudWatchAgentServerPolicy** 和 **AmazonECSTaskExecutionRolePolicy** 策略。然后，输入以下命令。在该命令中，将 *task-role-arn* 替换为您的自定义 ECS 任务角色的 ARN，并将 *execution-role-arn* 替换为您的自定义 ECS 任务执行角色的 ARN。

```
ClusterName=cluster-name
Region=cluster-region
TaskRoleArn=task-role-arn
ExecutionRoleArn=execution-role-arn
curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/ecs-task-definition-templates/deployment-mode/daemon-service/cwagent-ecs-instance-metric/cloudformation-quickstart/cwagent-ecs-instance-metric-cfn.json
aws cloudformation create-stack --stack-name CWAgentECS-${ClusterName}-${Region} \
    --template-body file://cwagent-ecs-instance-metric-cfn.json \
    --parameters ParameterKey=ClusterName,ParameterValue=${ClusterName} \
                 ParameterKey=TaskRoleArn,ParameterValue=${TaskRoleArn} \
                 ParameterKey=ExecutionRoleArn,ParameterValue=${ExecutionRoleArn} \
    --capabilities CAPABILITY_NAMED_IAM \
    --region ${Region}
```

**对快速设置进行故障排除**

要查看 CloudFormation 堆栈的状态，请输入以下命令。

```
ClusterName=cluster-name
Region=cluster-region
aws cloudformation describe-stacks --stack-name CWAgentECS-$ClusterName-$Region --region $Region
```

如果您看到的 `StackStatus` 不是 `CREATE_COMPLETE` 或 `CREATE_IN_PROGRESS`，请查看堆栈事件以查找错误。输入如下命令。

```
ClusterName=cluster-name
Region=cluster-region
aws cloudformation describe-stack-events --stack-name CWAgentECS-$ClusterName-$Region --region $Region
```

要查看 `cwagent` 守护进程服务的状态，请输入以下命令。在输出中，您应看到 `deployment` 部分中的 `runningCount` 等于 `desiredCount`。如果二者不相等，请查看输出中的 `failures` 部分。

```
ClusterName=cluster-name
Region=cluster-region
aws ecs describe-services --services cwagent-daemon-service --cluster $ClusterName --region $Region
```

您还可以使用 CloudWatch Logs 控制台来查看代理日志。查找 **/ecs/ecs-cwagent-daemon-service** 日志组。

**删除 CloudWatch 代理的 CloudFormation 堆栈**

如果您需要删除 CloudFormation 堆栈，请输入以下命令。

```
ClusterName=cluster-name
Region=cluster-region
aws cloudformation delete-stack --stack-name CWAgentECS-${ClusterName}-${Region} --region ${Region}
```

## 手动和自定义设置
<a name="deploy-container-insights-ECS-instancelevel-manual"></a>

执行此部分中的步骤，手动部署 CloudWatch 代理以从 EC2 实例上托管的 Amazon ECS 集群收集实例级别指标。

### 必要的 IAM 角色和策略
<a name="deploy-container-insights-ECS-instancelevel-IAMRoles"></a>

需要两个 IAM 角色。如果这两个角色不存在，则必须创建它们。有关这些角色的更多信息，请参阅[任务的 IAM 角色](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html)和 [Amazon ECS 任务执行角色](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_execution_IAM_role.html)。
+ 一个 *ECS 任务角色*，可供 CloudWatch 代理用来发布指标。如果此角色已存在，则必须确保它附加了 `CloudWatchAgentServerPolicy` 策略。
+ 一个 *ECS 任务执行角色*，可供 Amazon ECS 代理用来启动 CloudWatch 代理。如果此角色已存在，则必须确保它附加了 `AmazonECSTaskExecutionRolePolicy` 和 `CloudWatchAgentServerPolicy` 策略。

如果您还没有这些角色，则可使用以下命令来创建它们并附加必要的策略。第一条命令将创建 ECS 任务角色。

```
aws iam create-role --role-name CWAgentECSTaskRole \
    --assume-role-policy-document "{\"Version\": \"2012-10-17\",		 	 	 \"Statement\": [{\"Sid\": \"\",\"Effect\": \"Allow\",\"Principal\": {\"Service\": \"ecs-tasks.amazonaws.com\"},\"Action\": \"sts:AssumeRole\"}]}"
```

在输入上一条命令后，将命令输出中的 `Arn` 的值记为“TaskRoleArn”。稍后，您在创建任务定义时将需要使用它。然后，输入以下命令来附加必要的策略。

```
aws iam attach-role-policy --policy-arn arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy \
    --role-name CWAgentECSTaskRole
```

下一条命令将创建 ECS 任务执行角色。

```
aws iam create-role --role-name CWAgentECSExecutionRole \
    --assume-role-policy-document "{\"Version\": \"2012-10-17\",		 	 	 \"Statement\": [{\"Sid\": \"\",\"Effect\": \"Allow\",\"Principal\": {\"Service\": \"ecs-tasks.amazonaws.com\"},\"Action\": \"sts:AssumeRole\"}]}"
```

在输入上一条命令后，将命令输出中的 `Arn` 的值记为“ExecutionRoleArn”。稍后，您在创建任务定义时将需要使用它。然后，输入以下命令来附加必要的策略。

```
aws iam attach-role-policy --policy-arn arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy \
    --role-name CWAgentECSExecutionRole
          
aws iam attach-role-policy --policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy \
    --role-name CWAgentECSExecutionRole
```

### 创建任务定义并启动守护进程服务
<a name="deploy-container-insights-ECS-instancelevel-taskdefinition"></a>

创建一个任务定义并使用它将 CloudWatch 代理作为守护进程服务启动。要创建任务定义，请输入以下命令。在前面的行中，将占位符替换为部署的实际值。*logs-region* 为 CloudWatch Logs 所在的区域，*cluster-region* 为集群所在的区域。*task-role-arn* 为您使用的 ECS 任务角色的 Arn，*execution-role-arn* 为 ECS 任务执行角色的 Arn。

```
TaskRoleArn=task-role-arn
ExecutionRoleArn=execution-role-arn
AWSLogsRegion=logs-region
Region=cluster-region
curl https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/ecs-task-definition-templates/deployment-mode/daemon-service/cwagent-ecs-instance-metric/cwagent-ecs-instance-metric.json \
    | sed "s|{{task-role-arn}}|${TaskRoleArn}|;s|{{execution-role-arn}}|${ExecutionRoleArn}|;s|{{awslogs-region}}|${AWSLogsRegion}|" \
    | xargs -0 aws ecs register-task-definition --region ${Region} --cli-input-json
```

然后，运行以下命令来启动守护程序服务。将 *cluster-name* 和 *cluster-region* 分别替换为您的 Amazon ECS 集群的名称和区域。

**重要**  
在运行此命令之前，请移除所有容量提供程序策略。否则，命令将无法正常运行。

```
ClusterName=cluster-name
Region=cluster-region
aws ecs create-service \
    --cluster ${ClusterName} \
    --service-name cwagent-daemon-service \
    --task-definition ecs-cwagent-daemon-service \
    --scheduling-strategy DAEMON \
    --region ${Region}
```

如果您看到的错误消息为 `An error occurred (InvalidParameterException) when calling the CreateService operation: Creation of service was not idempotent`，则您已创建名为 `cwagent-daemon-service` 的守护程序服务。您必须先删除该服务，并使用以下命令作为示例。

```
ClusterName=cluster-name
Region=cluster-region
aws ecs delete-service \
    --cluster ${ClusterName} \
    --service cwagent-daemon-service \
    --region ${Region} \
    --force
```

### （可选）高级配置
<a name="deploy-container-insights-ECS-instancelevel-advanced"></a>

（可选）您可以使用 SSM 来指定 EC2 实例上托管的 Amazon ECS 集群中 CloudWatch 代理的其他配置选项。这些选项如下所示：
+ `metrics_collection_interval` – CloudWatch 代理收集指标的频率（以秒为单位）。默认值为 60。范围为 1 – 172000。
+ `endpoint_override` –（可选）指定要将日志发送到的其他端点。如果您从 VPC 的集群中发布并希望将日志数据传输到 VPC 终端节点，则可能需要执行该操作。

  `endpoint_override` 的值必须是表示 URL 的字符串。
+ `force_flush_interval` – 以秒为单位指定日志在发送到服务器之前保留在内存缓冲区中的最大时间量。无论此字段的设置如何，如果缓冲区中的日志大小达到 1 MB，日志会立即发送到服务器。默认值为 5 秒。
+ `region` – 默认情况下，代理将指标发布到 Amazon ECS 容器实例所在的同一区域。要覆盖此设置，您可以在此处指定其他区域。例如，`"region" : "us-east-1"`

以下是自定义配置的示例：

```
{
    "agent": {
        "region": "us-east-1"
    },
    "logs": {
        "metrics_collected": {
            "ecs": {
                "metrics_collection_interval": 30
            }
        },
        "force_flush_interval": 5
    }
}
```

**在 Amazon ECS 容器中自定义 CloudWatch 代理配置**

1. 确保将 **AmazonSSMReadOnlyAccess** 策略附加到 Amazon ECS 任务执行角色。可输入以下命令来执行此操作。此示例假定您的 Amazon ECS 任务执行角色是 CWAgentECSExecutionRole。如果您使用其他角色，请在以下命令中替换该角色名称。

   ```
   aws iam attach-role-policy --policy-arn arn:aws:iam::aws:policy/AmazonSSMReadOnlyAccess \
           --role-name CWAgentECSExecutionRole
   ```

1. 创建与上一示例类似的自定义配置文件。将此文件命名为 `/tmp/ecs-cwagent-daemon-config.json`。

1. 运行以下命令以将此配置放入 Parameter Store 中。将 *cluster-region* 替换为 Amazon ECS 集群的区域。要运行此命令，您必须登录到具有 **AmazonSSMFullAccess** 策略的用户或角色。

   ```
   Region=cluster-region
   aws ssm put-parameter \
       --name "ecs-cwagent-daemon-service" \
       --type "String" \
       --value "`cat /tmp/ecs-cwagent-daemon-config.json`" \
       --region $Region
   ```

1. 将任务定义文件下载到本地文件，例如 `/tmp/cwagent-ecs-instance-metric.json`

   ```
   curl https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/ecs-task-definition-templates/deployment-mode/daemon-service/cwagent-ecs-instance-metric/cwagent-ecs-instance-metric.json -o /tmp/cwagent-ecs-instance-metric.json
   ```

1. 修改任务定义文件。删除以下部分：

   ```
   "environment": [
                   {
                       "name": "USE_DEFAULT_CONFIG",
                       "value": "True"
                   }
               ],
   ```

   将此部分替换为以下内容：

   ```
   "secrets": [
                   {
                       "name": "CW_CONFIG_CONTENT",
                       "valueFrom": "ecs-cwagent-daemon-service"
                   }
               ],
   ```

1. 通过执行以下步骤，将代理作为守护程序服务重新启动：

   1. 运行如下命令。

      ```
      TaskRoleArn=task-role-arn
      ExecutionRoleArn=execution-role-arn
      AWSLogsRegion=logs-region
      Region=cluster-region
      cat /tmp/cwagent-ecs-instance-metric.json \
          | sed "s|{{task-role-arn}}|${TaskRoleArn}|;s|{{execution-role-arn}}|${ExecutionRoleArn}|;s|{{awslogs-region}}|${AWSLogsRegion}|" \
          | xargs -0 aws ecs register-task-definition --region ${Region} --cli-input-json
      ```

   1. 运行以下命令来启动守护程序服务。将 *cluster-name* 和 *cluster-region* 分别替换为您的 Amazon ECS 集群的名称和区域。

      ```
      ClusterName=cluster-name
      Region=cluster-region
      aws ecs create-service \
          --cluster ${ClusterName} \
          --service-name cwagent-daemon-service \
          --task-definition ecs-cwagent-daemon-service \
          --scheduling-strategy DAEMON \
          --region ${Region}
      ```

      如果您看到的错误消息为 `An error occurred (InvalidParameterException) when calling the CreateService operation: Creation of service was not idempotent`，则您已创建名为 `cwagent-daemon-service` 的守护程序服务。您必须先删除该服务，并使用以下命令作为示例。

      ```
      ClusterName=cluster-name
      Region=Region
      aws ecs delete-service \
          --cluster ${ClusterName} \
          --service cwagent-daemon-service \
          --region ${Region} \
          --force
      ```

# 部署 AWS Distro for OpenTelemetry 以收集 Amazon ECS 集群上的 EC2 实例级指标
<a name="deploy-container-insights-ECS-OTEL"></a>

使用此部分中的步骤使用 AWS Distro for OpenTelemetry 来收集 Amazon ECS 集群上的 EC2 实例级指标。有关 AWS Distro for OpenTelemetry 的更多信息，请参阅 [AWS Distro for OpenTelemetry](https://aws.amazon.com/otel/)。

这些步骤假设您已具有正在运行 Amazon ECS 的集群。此集群必须使用 EC2 启动类型进行部署。有关将 AWS Distro for Open Telemetry 与 Amazon ECS 结合使用以及为此设置 Amazon ECS 集群的更多信息，请参阅[设置 Amazon Elastic Container Service 中的 AWS Distro for OpenTelemetry Collector 以了解 ECS EC2 实例级指标](https://aws-otel.github.io/docs/setup/ecs#3-setup-the-aws-otel-collector-for-ecs-ec2-instance-metrics)。

**Topics**
+ [使用 CloudFormation 进行快速设置](#container-insights-ECS-OTEL-quicksetup)
+ [手动和自定义设置](#container-insights-ECS-OTEL-custom)

## 使用 CloudFormation 进行快速设置
<a name="container-insights-ECS-OTEL-quicksetup"></a>

下载 CloudFormation 模板文件，用于在 EC2 上为 Amazon ECS 安装 AWS Distro for OpenTelemetry 收集器。运行以下 curl 命令。

```
curl -O https://raw.githubusercontent.com/aws-observability/aws-otel-collector/main/deployment-template/ecs/aws-otel-ec2-instance-metrics-daemon-deployment-cfn.yaml
```

下载模板文件后，将其打开并将 *PATH\$1TO\$1CloudFormation\$1TEMPLATE* 替换为您保存模板文件的路径。然后导出以下参数并运行 CloudFormation 命令，如以下命令所示。
+ **Cluster\$1Name**– Amazon ECS 集群名称
+ **AWS\$1Region**– 将发送数据的区域
+ **PATH\$1TO\$1CloudFormation\$1TEMPLATE**– 保存 CloudFormation 模板文件的路径。
+ **command**– 要启用 AWS Distro for OpenTelemetry 收集器来收集 Amazon EC2 上 Amazon ECS 的实例级指标，您必须指定 `--config=/etc/ecs/otel-instance-metrics-config.yaml` 作为此参数。

```
ClusterName=Cluster_Name
Region=AWS_Region
command=--config=/etc/ecs/otel-instance-metrics-config.yaml
aws cloudformation create-stack --stack-name AOCECS-${ClusterName}-${Region} \
--template-body file://PATH_TO_CloudFormation_TEMPLATE \
--parameters ParameterKey=ClusterName,ParameterValue=${ClusterName} \
ParameterKey=CreateIAMRoles,ParameterValue=True \
ParameterKey=command,ParameterValue=${command} \
--capabilities CAPABILITY_NAMED_IAM \
--region ${Region}
```

运行此命令后，使用 Amazon ECS 控制台查看任务是否正在运行。

### 对快速设置进行故障排除
<a name="container-insights-ECS-OTEL-quicksetup-troubleshooting"></a>

要查看 CloudFormation 堆栈的状态，请输入以下命令。

```
ClusterName=cluster-name
Region=cluster-region
aws cloudformation describe-stack --stack-name AOCECS-$ClusterName-$Region --region $Region
```

如果 `StackStatus` 的值不是 `CREATE_COMPLETE` 或 `CREATE_IN_PROGRESS`，请查看堆栈事件以查找错误。输入如下命令。

```
ClusterName=cluster-name
Region=cluster-region
aws cloudformation describe-stack-events --stack-name AOCECS-$ClusterName-$Region --region $Region
```

要查看 `AOCECS` 守护进程服务的状态，请输入以下命令。在输出中，您应看到部署部分中的 `desiredCount` 等于 `runningCount`。如果二者不相等，请查看输出中的故障部分。

```
ClusterName=cluster-name
Region=cluster-region
aws ecs describe-services --services AOCECS-daemon-service --cluster $ClusterName --region $Region
```

您还可以使用 CloudWatch Logs 控制台来查看代理日志。查找 **/aws/ecs/containerinsights/\$1ClusterName\$1/performance** 日志组。

## 手动和自定义设置
<a name="container-insights-ECS-OTEL-custom"></a>

执行此部分中的步骤，手动部署 AWS Distro for OpenTelemetry 以从 Amazon EC2 实例上托管的 Amazon ECS 集群收集实例级别指标。

### 步骤 1：必要的角色和策略
<a name="container-insights-ECS-OTEL-custom-iam"></a>

需要两个 IAM 角色。如果这两个角色不存在，则必须创建它们。有关这些角色的更多信息，请参阅[创建 IAM 策略](https://aws-otel.github.io/docs/setup/ecs/create-iam-policy)和[创建 IAM 角色](https://aws-otel.github.io/docs/setup/ecs/create-iam-role)。

### 步骤 2：创建任务定义
<a name="container-insights-ECS-OTEL-custom-task"></a>

创建一个任务定义并使用它将 AWS Distro for OpenTelemetry 作为守护进程服务启动。

要使用任务定义模板创建任务定义，请按照[使用 AWS OTel Collector 为 EC2 实例创建 ECS EC2 任务定义](https://aws-otel.github.io/docs/setup/ecs/task-definition-for-ecs-ec2-instance)中的说明进行操作。

要使用 Amazon ECS 控制台创建任务定义，请按照[通过 AWS 控制台为 Amazon ECS EC2 实例指标创建任务定义来安装 AWS OTel Collector ](https://aws-otel.github.io/docs/setup/ecs/create-task-definition-instance-console) 中的说明进行操作。

### 步骤 3：启动守护进程服务
<a name="container-insights-ECS-OTEL-custom-launch"></a>

要将 AWS Distro for OpenTelemetry 作为守护进程服务启动，请按照[使用守护进程服务在 Amazon Elastic Container Service (Amazon ECS) 上运行您的任务](https://aws-otel.github.io/docs/setup/ecs/run-daemon-service)中的说明进行操作。

### （可选）高级配置
<a name="container-insights-ECS-OTEL-custom-advancdeconfig"></a>

（可选）您可以使用 SSM 来指定 Amazon EC2 实例上托管的 Amazon ECS 集群中 AWS Distro for OpenTelemetry 的其他配置选项。有关创建配置文件的更多信息，请参阅[自定义 OpenTelemetry 配置](https://aws-otel.github.io/docs/setup/ecs#5-custom-opentelemetry-configuration)。有关在配置文件中可使用的选项的详细信息，请参阅 [AWS Container Insights Receiver](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/receiver/awscontainerinsightreceiver/README.md)。

# 设置 Firelens 以向 CloudWatch Logs 发送日志
<a name="deploy-container-insights-ECS-logs"></a>

FireLens for Amazon ECS 使您能够使用任务定义参数将日志路由到 Amazon CloudWatch Logs，以进行日志存储和分析。FireLens 与 [Fluent Bit](https://fluentbit.io/) 和 [Fluentd](https://www.fluentd.org/) 配合使用。我们提供 AWS for Fluent Bit 镜像，您也可以使用自己的 Fluent Bit 或 Fluentd 镜像。支持通过 AWS SDK、AWS CLI 和 AWS 管理控制台 使用 FireLens 配置创建 Amazon ECS 任务定义。有关 CloudWatch Logs 的更多信息，请参阅[什么是 CloudWatch Logs？](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.html)。

使用 FireLens for Amazon ECS 时有一些关键注意事项。有关更多信息，请参阅[注意事项](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_firelens.html#firelens-considerations)。

要查找 AWS for Fluent Bit 镜像，请参阅[使用 AWS for Fluent Bit 镜像](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/firelens-using-fluentbit.html)。

要创建使用 FireLens 配置的任务定义，请参阅[创建使用 FireLens 配置的任务定义](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/firelens-taskdef.html)。

**示例**

以下任务定义示例演示如何指定用于将日志转发到 CloudWatch Logs 日志组的日志配置。如需了解更多信息，请参阅 *Amazon CloudWatch Logs 用户指南*中的[什么是 Amazon CloudWatch Logs？](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.html)

在日志配置选项中，指定日志组名称及其所在的区域。要让 Fluent Bit 代表您创建日志组，请指定 `"auto_create_group":"true"`。您还可以将任务 ID 指定为有助于筛选的日志流前缀。有关更多信息，请参阅[适用于 CloudWatch Logs 的 Fluent Bit 插件](https://github.com/aws/amazon-cloudwatch-logs-for-fluent-bit/blob/mainline/README.md)。

```
{
	"family": "firelens-example-cloudwatch",
	"taskRoleArn": "arn:aws:iam::123456789012:role/ecs_task_iam_role",
	"containerDefinitions": [
		{
			"essential": true,
			"image": "906394416424.dkr.ecr.us-west-2.amazonaws.com/aws-for-fluent-bit:latest",
			"name": "log_router",
			"firelensConfiguration": {
				"type": "fluentbit"
			},
			"logConfiguration": {
				"logDriver": "awslogs",
				"options": {
					"awslogs-group": "firelens-container",
					"awslogs-region": "us-west-2",
					"awslogs-create-group": "true",
					"awslogs-stream-prefix": "firelens"
				}
			},
			"memoryReservation": 50
		 },
		 {
			 "essential": true,
			 "image": "nginx",
			 "name": "app",
			 "logConfiguration": {
				 "logDriver":"awsfirelens",
				 "options": {
					"Name": "cloudwatch_logs",
					"region": "us-west-2",
					"log_key": "log",
                                 "log_group_name": "/aws/ecs/containerinsights/my-cluster/application",
					"auto_create_group": "true",
					"log_stream_name": "my-task-id"
				}
			},
			"memoryReservation": 100
		}
	]
}
```

# 在 Amazon EKS 和 Kubernetes 上设置 Container Insights
<a name="deploy-container-insights-EKS"></a>

Amazon EKS 版本 1.23 及更高版本支持 Container Insights。仅版本 1.24 及更高版本支持快速启动安装方法。

在 Amazon EKS 或 Kubernetes 上设置 Container Insights 的整个过程如下所示：

1. 验证您是否满足所需的先决条件。

1. 在集群上设置 Amazon CloudWatch Observability EKS 附加组件、CloudWatch 代理或 AWS Distro for OpenTelemetry，以将指标发送到 CloudWatch。
**注意**  
要使用针对 Amazon EKS 增强了可观测性的 Container Insights，您必须使用 Amazon CloudWatch Observability EKS 附加组件或 CloudWatch 代理。有关此版本的 Container Insights 的更多信息，请参阅 [针对 Amazon EKS 增强了可观测性的 Container Insights](container-insights-detailed-metrics.md)。  
要将 Container Insights 与 Fargate 一起使用，您必须使用 AWS Distro for OpenTelemetry。Fargate 不支持针对 Amazon EKS 增强了可观测性的 Container Insights。
**注意**  
Container Insights 现在支持 Amazon EKS 集群中的 Windows Worker 节点。Windows 还支持针对 Amazon EKS 增强了可观测性的 Container Insights。有关在 Windows 上启用 Container Insights 的信息，请参阅 [使用启用了 Container Insights 增强可观测性的 CloudWatch 代理](Container-Insights-EKS-agent.md)。

   要使用采用 OpenTelemetry 指标的 Container Insights，请安装 Amazon CloudWatch Observability EKS 附加组件版本 `v6.0.1-eksbuild.1` 或更新版本。有关更多信息，请参阅 [适用于 Amazon EKS 的采用 OpenTelemetry 指标的 Container Insights](container-insights-otel-metrics.md)。

   设置 Fluent Bit 或 Fluentd 以将日志发送到 CloudWatch Logs。（如果您安装了 Amazon CloudWatch Observabity EKS 附加组件，则默认启用此功能。）

   如果您正在使用 CloudWatch 代理，您可以作为快速入门设置的一部分立即执行这些步骤，也可以单独执行这些步骤。

1. （可选）设置 Amazon EKS 控制面板日志记录。

1. （可选）在集群上将 CloudWatch 代理设置为 StatsD 端点以将 StatsD 指标发送到 CloudWatch。

1. （可选）启用 App Mesh Envoy 访问日志。

在 Container Insights 的原始版本中，收集的指标和摄取的日志将作为自定义指标收费。借助针对 Amazon EKS 增强了可观测性的 Container Insights，Container Insights 指标和日志按每次观测收费，而不是按存储的指标或摄取的日志收费。有关 CloudWatch 定价的信息，请参阅 [Amazon CloudWatch 定价](https://aws.amazon.com/cloudwatch/pricing/)。

**Topics**
+ [在 CloudWatch 中验证 Container Insights 的先决条件](Container-Insights-prerequisites.md)
+ [使用启用了 Container Insights 增强可观测性的 CloudWatch 代理](Container-Insights-EKS-agent.md)
+ [使用 AWS Distro for OpenTelemetry](Container-Insights-EKS-otel.md)
+ [将日志发送到 CloudWatch Logs](Container-Insights-EKS-logs.md)
+ [在 Amazon EKS 和 Kubernetes 上更新或删除 Container Insights](ContainerInsights-update-delete.md)

# 在 CloudWatch 中验证 Container Insights 的先决条件
<a name="Container-Insights-prerequisites"></a>

在 Amazon EKS 或 Kubernetes 上安装 Container Insights 之前，请验证以下内容。无论您是使用 CloudWatch 代理还是 AWS Distro for OpenTelemetry 在 Amazon EKS 集群上设置 Container Insights，这些先决条件都适用。
+ 在其中一个支持适用于 Amazon EKS 和 Kubernetes 的 Container Insights 的区域中，您具有正常工作的 Amazon EKS 集群或 Kubernetes 集群并附加了节点。有关支持的区域列表，请参阅[Container Insights](ContainerInsights.md)。
+ 您已安装并正在运行 `kubectl`。有关更多信息，请参阅 *Amazon EKS 用户指南* 中的[安装 `kubectl`](https://docs.aws.amazon.com/eks/latest/userguide/install-kubectl.html)。
+ 如果您使用在 AWS 上运行的 Kubernetes，而不是使用 Amazon EKS，则还需要满足以下先决条件：
  + 确保您的 Kubernetes 集群已启用基于角色的访问控制 (RBAC)。有关更多信息，请参阅《Kubernetes 参考》中的 [使用 RBAC 授权](https://kubernetes.io/docs/reference/access-authn-authz/rbac/)。
  + 您的 kubelet 已启用 Webhook 授权模式。有关更多信息，请参阅《Kubernetes 参考》中的 [Kubelet 身份验证/授权](https://kubernetes.io/docs/reference/access-authn-authz/kubelet-authn-authz/)。

您还必须授予 IAM 权限，以使 Amazon EKS Worker 节点能够向 CloudWatch 发送指标和日志。有两种方式可执行此操作：
+ 将策略附加到 Worker 节点的 IAM 角色。这同时适用于 Amazon EKS 集群和其他 Kubernetes 集群。
+ 对集群的服务账户使用 IAM 角色，并将策略附加到此角色。这仅适用于 Amazon EKS 集群。

第一个选项授予 CloudWatch 对整个节点的权限，而对服务账户使用 IAM 角色仅授予 CloudWatch 对相应守护程序集 Pod 的访问权限。

**将策略附加到 Worker 节点的 IAM 角色**

按照以下步骤将策略附加到 Worker 节点的 IAM 角色。这同时适用于 Amazon EKS 外部的 Amazon EKS 集群和 Kubernetes 集群。

**将所需的策略附加到 Worker 节点的 IAM 角色**

1. 通过以下网址打开 Amazon EC2 控制台：[https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/)。

1. 选择其中的一个 Worker 节点实例，然后在描述中选择 IAM 角色。

1. 在 IAM 角色页面上，选择 **Attach policies（附加策略）**。

1. 在策略列表中，选中 **CloudWatchAgentServerPolicy** 旁边的复选框。如有必要，请使用搜索框查找该策略。

1. 选择**附加策略**。

如果您在 Amazon EKS 外部运行 Kubernetes 集群，则可能无法将 IAM 角色附加到 Worker 节点。如果没有，您必须先将一个 IAM 角色附加到实例，然后按照前面步骤中所述添加策略。有关将角色附加到实例的更多信息，请参阅《Amazon EC2 用户指南》**中的[将 IAM 角色附加到实例](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/iam-roles-for-amazon-ec2.html#attach-iam-role)。

如果您在 Amazon EKS 外部运行 Kubernetes 集群，并且希望在指标中收集 EBS 卷 ID，则必须向附加到该实例的 IAM 角色添加另一个策略。添加以下内容作为内联策略。有关更多信息，请参阅 *IAM 用户指南*中的[添加和删除 IAM 身份权限](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage-attach-detach.html)。

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Action": [
                "ec2:DescribeVolumes"
            ],
            "Resource": "*",
            "Effect": "Allow"
        }
    ]
}
```

------

**使用 IAM 服务账户角色**

此方法仅适用于 Amazon EKS 集群。

**使用 IAM 服务账户角色向 CloudWatch 授予权限**

1. 为集群上的服务账户启用 IAM 角色（如果尚未执行此操作）。有关更多信息，请参阅[为集群上的服务账户启用 IAM 角色](https://docs.aws.amazon.com/eks/latest/userguide/enable-iam-roles-for-service-accounts.html)。

1. 配置服务账户以使用 IAM 角色（如果尚未进行此配置）。有关更多信息，请参阅[配置 Kubernetes 服务账户以代入 IAM 角色](https://docs.aws.amazon.com/eks/latest/userguide/associate-service-account-role.html)。

   创建角色时，除了您为角色创建的策略外，还将 **CloudWatchAgentServerPolicy** IAM 策略附加到角色。此外，应在 `amazon-cloudwatch` 命名空间中创建链接至此角色的关联 Kubernetes 服务账户，在接下来的步骤中，CloudWatch 和 Fluent Bit 进程守护程序集将在其中部署

1. 将 IAM 角色与集群中的服务账户相关联（如果尚未执行此操作）。有关更多信息，请参阅[配置 Kubernetes 服务账户以代入 IAM 角色](https://docs.aws.amazon.com/eks/latest/userguide/associate-service-account-role.html)。

# 使用启用了 Container Insights 增强可观测性的 CloudWatch 代理
<a name="Container-Insights-EKS-agent"></a>

按照以下任一部分中的说明，使用 CloudWatch 代理在 Amazon EKS 集群或 Kubernetes 集群上设置 Container Insights。仅 Amazon EKS 版本 1.24 及更高版本支持快速启动指令。

**注意**  
您可以按照以下任一部分中的说明安装 Container Insights。您无需遵循所有三组说明。

**Topics**
+ [Amazon CloudWatch 可观测性 EKS 插件快速入门](Container-Insights-setup-EKS-addon.md)
+ [Amazon EKS 和 Kubernetes 上的 Container Insights 的快速入门设置](Container-Insights-setup-EKS-quickstart.md)
+ [设置 CloudWatch 代理以收集集群指标](Container-Insights-setup-metrics.md)

# Amazon CloudWatch 可观测性 EKS 插件快速入门
<a name="Container-Insights-setup-EKS-addon"></a>

您可以使用 Amazon EKS 附加组件安装针对 Amazon EKS 增强了可观测性的 Container Insights。该附加组件会安装 CloudWatch 代理以从集群发送基础设施指标、安装 Fluent Bit 以发送容器日志，还会启用 CloudWatch [Application Signals](CloudWatch-Application-Monitoring-Sections.md) 以发送应用程序性能遥测。

当您使用 Amazon EKS 附加组件 1.5.0 版或更高版本时，集群中的 Linux 和 Windows Worker 节点上都将启用 Container Insights。在 Amazon EKS 中，Windows 节点上暂不支持 Application Signals。

运行 Kubernetes 而不是 Amazon EKS 的集群不支持 Amazon EKS 附加组件。

有关 Amazon CloudWatch Observability EKS 附加组件的更多信息，请参阅 [使用 Amazon CloudWatch Observability EKS 附加组件或 Helm 图表安装 CloudWatch 代理](install-CloudWatch-Observability-EKS-addon.md)。

如果您使用的插件版本为 3.1.0 或更高版本，则可以使用 EKS 容器组身份向该插件授予所需的权限。推荐使用 EKS 容器组身份，它具有诸如最低权限、凭证轮换和可审计性等优点。此外，使用 EKS 容器组身份，您可以在集群创建过程中安装 EKS 插件。

**安装 Amazon CloudWatch Observability EKS 附加组件**

1. 按照 [EKS 容器组身份关联](https://docs.aws.amazon.com/eks/latest/userguide/pod-id-association.html#pod-id-association-create/)步骤创建 IAM 角色并设置 EKS 容器组身份代理。

1. 附加一个向角色授予所需权限的 IAM 策略。将 *my-role* 替换为上一步中 IAM 角色的名称。

   ```
   aws iam attach-role-policy \
    --role-name my-role \
   --policy-arn=arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy
   ```

1. 输入以下命令，使用您在上一步中创建的 IAM 角色：

   ```
   aws eks create-addon \
   --addon-name amazon-cloudwatch-observability \
   --cluster-name my-cluster-name \
   --pod-identity-associations serviceAccount=cloudwatch-agent,roleArn=arn:aws:iam::111122223333:role/my-role
   ```

# Amazon EKS 和 Kubernetes 上的 Container Insights 的快速入门设置
<a name="Container-Insights-setup-EKS-quickstart"></a>

**重要**  
如果您要在 Amazon EKS 集群上安装 Container Insights，我们建议您使用 Amazon CloudWatch Observability EKS 附加组件进行安装，而不是按照本部分中的说明进行安装。此外，要检索加速计算网络，必须使用 Amazon CloudWatch 可观测性 EKS 附加组件。有关更多信息和说明，请参阅 [Amazon CloudWatch 可观测性 EKS 插件快速入门](Container-Insights-setup-EKS-addon.md)。

要完成 Container Insights 的设置，您可以按照本节中的快速入门说明进行操作。如果您要在 Amazon EKS 集群中进行安装，并且在 2023 年 11 月 6 日当天或之后按照本部分中的说明进行操作，则可以在集群中安装针对 Amazon EKS 增强了可观测性的 Container Insights。

**重要**  
在完成本节中的步骤之前，您必须已对 IAM 权限等先决条件进行验证。有关更多信息，请参阅 [在 CloudWatch 中验证 Container Insights 的先决条件](Container-Insights-prerequisites.md)。

或者，您可以按照以下两节中的说明操作：[设置 CloudWatch 代理以收集集群指标](Container-Insights-setup-metrics.md)和 [将日志发送到 CloudWatch Logs](Container-Insights-EKS-logs.md)。这些章节提供有关 CloudWatch 代理如何与 Amazon EKS 和 Kubernetes 结合使用的更多配置详细信息，但需要您执行更多安装步骤。

在 Container Insights 的原始版本中，收集的指标和摄取的日志将作为自定义指标收费。借助针对 Amazon EKS 增强了可观测性的 Container Insights，Container Insights 指标和日志按每次观测收费，而不是按存储的指标或摄取的日志收费。有关 CloudWatch 定价的信息，请参阅 [Amazon CloudWatch 定价](https://aws.amazon.com/cloudwatch/pricing/)。

**注意**  
Amazon 现已推出 Fluent Bit 作为 Container Insights 的默认日志解决方案，其性能显着提高。我们建议您使用 Fluent Bit 而不是 Fluentd。

## 使用 CloudWatch 代理 operator 和 Fluent Bit 快速入门
<a name="Container-Insights-setup-EKS-quickstart-FluentBit"></a>

Fluent Bit 有两种配置：优化版本和更类似于 Fluentd 的体验的版本。快速入门配置使用优化版本。有关 Fluentd 兼容配置的详细信息，请参阅 [将 Fluent Bit 设置为 DaemonSet 以将日志发送到 CloudWatch Logs](Container-Insights-setup-logs-FluentBit.md)。

CloudWatch 代理 operator 是安装到 Amazon EKS 集群的附加容器。它以 OpenTelemetry Operator for Kubernetes 为模型。Operator 管理集群中 Kubernetes 资源的生命周期。它在 Amazon EKS 集群上安装 CloudWatch 代理、DCGM Exporter（NVIDIA）和 AWS Neuron Monitor 并对其进行管理。Fluent Bit 和 CloudWatch Agent for Windows 可以直接安装到 Amazon EKS 集群中，而无需 operator 对其进行管理。

为了获得更安全、功能更丰富的凭证颁发机构解决方案，CloudWatch 代理 operator 需要使用 cert-manager，这是 Kubernetes 中广泛采用的 TLS 证书管理解决方案。使用 cert-manager 可简化获取、续订、管理和使用这些证书的过程。此解决方案可确保证书有效且最新，并尝试在证书到期前的配置时间续订证书。cert-manager 还便于从各种支持的来源（包括 AWS Certificate Manager Private Certificate Authority）颁发证书。

**使用快速入门部署 Container Insights**

1. 如果 cert-manager 尚未安装到集群中，则请安装。有关更多信息，请参阅 [cert-manager Installation](https://cert-manager.io/docs/installation/)。

1. 通过输入以下命令安装自定义资源定义（CRD）。

   ```
   curl https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/main/k8s-quickstart/cwagent-custom-resource-definitions.yaml | kubectl apply --server-side -f -
   ```

1. 通过输入以下命令安装 operator。将 *my-cluster-name* 替换为 Amazon EKS 或 Kubernetes 集群的名称，将 *my-cluster-region* 替换为在其中发布日志的区域的名称。我们建议您使用在其中部署集群的同一个区域来降低 AWS 出站数据传输成本。

   ```
   ClusterName=my-cluster-name
   RegionName=my-cluster-region
   curl https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/main/k8s-quickstart/cwagent-operator-rendered.yaml | sed 's/{{cluster_name}}/'${ClusterName}'/g;s/{{region_name}}/'${RegionName}'/g' | kubectl apply -f -
   ```

   例如，要在名为 `MyCluster` 的集群上部署 Container Insights 并将日志和指标发布到美国西部（俄勒冈），请输入以下命令。

   ```
   ClusterName='MyCluster'
   RegionName='us-west-2'
   curl https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/main/k8s-quickstart/cwagent-operator-rendered.yaml | sed 's/{{cluster_name}}/'${ClusterName}'/g;s/{{region_name}}/'${RegionName}'/g' | kubectl apply -f -
   ```

**从 Container Insights 迁移**

如果您已经在 Amazon EKS 集群中配置了 Container Insights，并想要迁移到针对 Amazon EKS 增强了可观测性的 Container Insights，则请参阅 [在 CloudWatch 中升级到针对 Amazon EKS 增强了可观测性的 Container Insights](Container-Insights-upgrade-enhanced.md)

**删除 Container Insights**

如果您想使用快速入门设置删除 Container Insights，则请输入以下命令。

```
ClusterName=my-cluster-name 
RegionName=my-cluster-region
curl https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/main/k8s-quickstart/cwagent-operator-rendered.yaml | sed 's/{{cluster_name}}/'${ClusterName}'/g;s/{{region_name}}/'${RegionName}'/g' | kubectl delete -f -
curl https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/main/k8s-quickstart/cwagent-custom-resource-definitions.yaml | kubectl delete -f -
```

# 设置 CloudWatch 代理以收集集群指标
<a name="Container-Insights-setup-metrics"></a>

**重要**  
如果您要在 Amazon EKS 集群上安装 Container Insights，我们建议您使用 Amazon CloudWatch Observability EKS 附加组件进行安装，而不是按照本部分中的说明进行安装。有关更多信息和说明，请参阅 [Amazon CloudWatch 可观测性 EKS 插件快速入门](Container-Insights-setup-EKS-addon.md)。

要设置 Container Insights 以收集指标，您可以按照[Amazon EKS 和 Kubernetes 上的 Container Insights 的快速入门设置](Container-Insights-setup-EKS-quickstart.md)中的步骤操作，也可以按照本节中的步骤操作。在以下步骤中，您设置 CloudWatch 代理以便能够从集群中收集指标。

如果您要在 Amazon EKS 集群中进行安装，并且在 2023 年 11 月 6 日当天或之后按照本部分中的说明进行操作，则可以在集群中安装针对 Amazon EKS 增强了可观测性的 Container Insights。

## 步骤 1：为 CloudWatch 创建命名空间
<a name="create-namespace-metrics"></a>

使用以下步骤为 CloudWatch 创建名为 `amazon-cloudwatch` 的 Kubernetes 命名空间。如果已创建该命名空间，您可以跳过此步骤。

**为 CloudWatch 创建命名空间**
+ 输入如下命令。

  ```
  kubectl apply -f https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/daemonset/container-insights-monitoring/cloudwatch-namespace.yaml
  ```

## 步骤 2：在集群中创建服务账户
<a name="create-service-account"></a>

如果您还没有服务账户，请使用以下方法之一为 CloudWatch 代理创建一个服务账户。
+ 使用 `kubectl`
+ 使用 `kubeconfig` 文件。

### 使用 `kubectl` 进行身份验证
<a name="use-kubectl"></a>

**要使用 `kubectl` 为 CloudWatch 代理创建服务账户**
+ 输入如下命令。

  ```
  kubectl apply -f https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/daemonset/container-insights-monitoring/cwagent/cwagent-serviceaccount.yaml
  ```

如果您没有按照前面的步骤进行操作，而是已具有要使用的 CloudWatch 代理的服务账户，则必须确保该账户具有以下规则。此外，在 Container Insights 安装的其余步骤中，您必须使用该服务账户的名称，而不是 `cloudwatch-agent`。

```
rules:
  - apiGroups: [""]
    resources: ["pods", "nodes", "endpoints"]
    verbs: ["list", "watch"]
  - apiGroups: [ "" ]
    resources: [ "services" ]
    verbs: [ "list", "watch" ]
  - apiGroups: ["apps"]
    resources: ["replicasets", "daemonsets", "deployments", "statefulsets"]
    verbs: ["list", "watch"]
  - apiGroups: ["batch"]
    resources: ["jobs"]
    verbs: ["list", "watch"]
  - apiGroups: [""]
    resources: ["nodes/proxy"]
    verbs: ["get"]
  - apiGroups: [""]
    resources: ["nodes/stats", "configmaps", "events"]
    verbs: ["create", "get"]
  - apiGroups: [""]
    resources: ["configmaps"]
    resourceNames: ["cwagent-clusterleader"]
    verbs: ["get","update"]
  - nonResourceURLs: ["/metrics"]
    verbs: ["get", "list", "watch"]
  - apiGroups: [ "discovery.k8s.io" ]
    resources: [ "endpointslices" ]
    verbs: [ "list", "watch", "get" ]
```

### 使用 `kubeconfig` 进行身份验证
<a name="use-kubeconfig"></a>

或者，您也可以使用 `kubeconfig` 文件进行身份验证。此方法让您可以直接在 CloudWatch 代理配置中指定 `kubeconfig` 路径，从而避免需要使用服务账户。它还允许您消除对 Kubernetes 控制面板 API 进行身份验证的依赖，从而简化设置，并通过以 kubeconfig 文件管理身份验证来潜在提高安全性。

要使用此方法，请更新您的 CloudWatch 代理配置文件以指定 `kubeconfig` 文件路径，如以下示例所示。

```
{
  "logs": {
    "metrics_collected": {
      "kubernetes": {
        "cluster_name": "YOUR_CLUSTER_NAME",
        "enhanced_container_insights": false,
        "accelerated_compute_metrics": false,
        "tag_service": false,
        "kube_config_path": "/path/to/your/kubeconfig" 
        "host_ip": "HOSTIP"
      }
    }
  }
}
```

要创建 `kubeconfig` 文件，请为具有 `system:masters` Kubernetes 角色的 `admin/{create_your_own_user}` 用户创建证书签名请求（CSR）。然后，使用 Kubernetes 集群的证书颁发机构（CA）签名并创建 `kubeconfig` 文件。

## 步骤 3：为 CloudWatch 代理创建 ConfigMap
<a name="create-configmap"></a>

可以使用以下步骤为 CloudWatch 代理创建 ConfigMap。

**为 CloudWatch 代理创建 ConfigMap**

1. 运行以下命令以将 ConfigMap YAML 下载到 `kubectl` 客户端主机中：

   ```
   curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/daemonset/container-insights-monitoring/cwagent/cwagent-configmap-enhanced.yaml
   ```

1. 编辑下载的 YAML 文件，如下所示：
   + **cluster\$1name** – 在 `kubernetes` 部分中，将 `{{cluster_name}}` 替换为您的集群的名称。删除 `{{}}` 字符。或者，如果使用的是 Amazon EKS 集群，您可以删除 `"cluster_name"` 字段和值。如果这样做，CloudWatch 代理将从 Amazon EC2 标签中检测集群名称。

1. （可选）根据您的监控要求，对 ConfigMap 进行进一步的更改，如下所示：
   + **metrics\$1collection\$1interval** – 在 `kubernetes` 部分中，您可以指定代理收集指标的频率。默认值为 60 秒。kubelet 中的默认 cadvisor 收集间隔为 15 秒，因此，请不要将该值设置为小于 15 秒。
   + **endpoint\$1override** – 在 `logs` 部分中，如果要覆盖默认端点，您可以指定 CloudWatch Logs 端点。如果您从 VPC 的集群中发布并希望将数据传输到 VPC 终端节点，则可能需要执行该操作。
   + **force\$1flush\$1interval** – 在 `logs` 部分中，您可以指定在将日志事件发布到 CloudWatch Logs 之前批量处理这些事件的间隔。默认值为 5 秒。
   + **region** – 默认情况下，代理将指标发布到 Worker 节点所在的区域。要覆盖该区域，您可以在 `agent` 部分中添加 `region` 字段：例如，`"region":"us-west-2"`。
   + **statsd** 部分 – 如果希望 CloudWatch Logs 代理还在集群的每个 Worker 节点中作为 StatsD 侦听器运行，您可以将 `statsd` 部分添加到 `metrics` 部分中，如以下示例中所示。有关该部分的其他 StatsD 选项的信息，请参阅 [使用 StatsD 检索自定义指标](CloudWatch-Agent-custom-metrics-statsd.md)。

     ```
     "metrics": {
       "metrics_collected": {
         "statsd": {
           "service_address":":8125"
         }
       }
     }
     ```

     JSON 部分的完整示例如下所示。如果您使用 `kubeconfig` 文件进行身份验证，请添加 `kube_config_path` 参数以指定 kubeconfig 文件的路径。

     ```
     {
         "agent": {
             "region": "us-east-1"
         },
         "logs": {
             "metrics_collected": {
                 "kubernetes": {
                     "cluster_name": "MyCluster",
                     "metrics_collection_interval": 60,
                     "kube_config_path": "/path/to/your/kubeconfig" //if using kubeconfig for authentication
                 }
             },
             "force_flush_interval": 5,
             "endpoint_override": "logs.us-east-1.amazonaws.com"
         },
         "metrics": {
             "metrics_collected": {
                 "statsd": {
                     "service_address": ":8125"
                 }
             }
         }
     }
     ```

1. 运行以下命令以在集群中创建 ConfigMap。

   ```
   kubectl apply -f cwagent-configmap-enhanced.yaml
   ```

## 步骤 4：将 CloudWatch 代理部署为 DaemonSet
<a name="deploy-agent-yaml"></a>

要完成 CloudWatch 代理安装并开始收集容器指标，请使用以下步骤。

**将 CloudWatch 代理部署为 DaemonSet**

1. 
   + 如果您不想在集群上使用 StatsD，请输入以下命令。

     ```
     kubectl apply -f https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/daemonset/container-insights-monitoring/cwagent/cwagent-daemonset.yaml
     ```
   + 如果您想要使用 StatsD，请执行以下步骤：

     1. 运行以下命令以将 DaemonSet YAML 下载到 `kubectl` 客户端主机中。

        ```
        curl -O  https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/daemonset/container-insights-monitoring/cwagent/cwagent-daemonset.yaml
        ```

     1. 取消注释 `port` 文件中的 `cwagent-daemonset.yaml` 部分，如下所示：

        ```
        ports:
          - containerPort: 8125
            hostPort: 8125
            protocol: UDP
        ```

     1. 运行以下命令以在集群中部署 CloudWatch 代理。

        ```
        kubectl apply -f cwagent-daemonset.yaml
        ```

     1. 运行以下命令以在集群中的 Windows 节点上部署 CloudWatch 代理。Windows 上的 CloudWatch 代理不支持 StatSD 侦听器。

        ```
        kubectl apply -f cwagent-daemonset-windows.yaml
        ```

1. 运行以下命令以验证是否部署了该代理。

   ```
   kubectl get pods -n amazon-cloudwatch
   ```

在完成后，CloudWatch 代理创建一个名为 `/aws/containerinsights/Cluster_Name/performance` 的日志组，并将性能日志事件发送到该日志组。如果还将该代理设置为 StatsD 侦听器，该代理还会在端口 8125（具有计划运行应用程序 pod 的节点的 IP 地址）上侦听 StatsD 指标。

### 问题排查
<a name="ContainerInsights-deploy-troubleshooting"></a>

如果未正确部署该代理，请尝试执行以下操作：
+ 运行以下命令以获取 pod 列表。

  ```
  kubectl get pods -n amazon-cloudwatch
  ```
+ 运行以下命令并在输出底部检查事件。

  ```
  kubectl describe pod pod-name -n amazon-cloudwatch
  ```
+ 运行以下命令以检查日志。

  ```
  kubectl logs pod-name  -n amazon-cloudwatch
  ```

# 使用 AWS Distro for OpenTelemetry
<a name="Container-Insights-EKS-otel"></a>

您可以通过使用 AWS Distro for OpenTelemetry 收集器设置 Container Insights 从 Amazon EKS 集群收集指标。有关 AWS Distro for OpenTelemetry 的更多信息，请参阅 [AWS Distro for OpenTelemetry](https://aws.amazon.com/otel/)。

**重要**  
如果您使用 AWS Distro for OpenTelemetry 进行安装，则会安装 Container Insights，但无法获取针对 Amazon EKS 增强了可观测性的 Container Insights。您将不会收集针对 Amazon EKS 增强了可观测性的 Container Insights 中支持的详细指标。

如何设置 Container Insights 取决于集群托管在 Amazon EC2 实例上还是 AWS Fargate 上。

## 托管在 Amazon EC2 上的 Amazon EKS 集群
<a name="Container-Insights-EKS-otel-EC2"></a>

如果您尚未执行此操作，请确保您已满足先决条件，例如必要的 IAM 角色。有关更多信息，请参阅 [在 CloudWatch 中验证 Container Insights 的先决条件](Container-Insights-prerequisites.md)。

Amazon 提供 Helm Chart，您可以用它来设置对 Amazon EC2 上的 Amazon Elastic Kubernetes Service 的监控。此监控使用 AWS Distro for OpenTelemetry(ADOT) 收集器用于指标，使用 Fluent Bit 用于日志。因此，Helm Chart 对使用 Amazon EC2 上的 Amazon EKS 并希望收集指标和日志以发送到 CloudWatch Container Insights 的客户非常有用。有关此 Helm Chart 的更多信息，请参阅[发送到 Amazon CloudWatch Container Insights 的 EC2 上 EKS 的指标和日志的 ADOT Helm chart](https://github.com/aws-observability/aws-otel-helm-charts/tree/main/charts/adot-exporter-for-eks-on-ec2)。

或者，您也可以使用本部分剩余内容中的说明。

首先，通过输入以下命令将 AWS Distro for OpenTelemetry 收集器部署为 DaemonSet。

```
curl https://raw.githubusercontent.com/aws-observability/aws-otel-collector/main/deployment-template/eks/otel-container-insights-infra.yaml |
kubectl apply -f -
```

要确认该收集器正在运行，请输入以下命令。

```
kubectl get pods -l name=aws-otel-eks-ci -n aws-otel-eks
```

如果此命令的输出包含处于 `Running` 状态的多个 Pod，则收集器正在运行并从集群收集指标。收集器会创建一个名为 `aws/containerinsights/cluster-name/performance` 的日志组并将性能日志事件发送给它。

有关如何在 CloudWatch 中查看 Container Insights 指标的信息，请参阅 [查看 Container Insights 指标](Container-Insights-view-metrics.md)。

AWS 还在 GitHub 上为此情况提供了文档。如果要自定义 Container Insights 发布的指标和日志，请参阅 [https://aws-otel.github.io/docs/getting-started/container-insights/eks-infra](https://aws-otel.github.io/docs/getting-started/container-insights/eks-infra)。

## 托管在 Fargate 上的 Amazon EKS 集群
<a name="Container-Insights-EKS-otel-Fargate"></a>

有关如何配置和部署 ADOT 收集器以从部署到 Fargate 上的 Amazon EKS 集群的工作负载收集系统指标并将其发送到 CloudWatch Container Insights 的说明，请参阅 AWS Distro for OpenTelemetry 文档中的 [Container Insights EKS Fargate](https://aws-otel.github.io/docs/getting-started/container-insights/eks-fargate)。

# 将日志发送到 CloudWatch Logs
<a name="Container-Insights-EKS-logs"></a>

要将日志从您的容器发送到 Amazon CloudWatch Logs，您可以使用 Fluent Bit。有关更多信息，请参阅 [Fluent Bit](https://fluentbit.io/)。

**注意**  
自 2025 年 2 月 10 日起，AWS 已不再支持使用 FluentD 作为 CloudWatch Logs 的日志转发器。我们建议您使用 Fluent Bit，这是一种轻量级的资源高效型替代方案。现有的 FluenTD 部署将继续正常运行。将您的日志记录管道迁移到 Fluent Bit，以确保继续获得支持和实现最佳性能。  
Container Insights 以前还支持使用 FluentD 从容器发送日志。FluenTD 已被弃用，现在不支持 Container Insights。改为使用 Fluent Bit。

**Topics**
+ [将 Fluent Bit 设置为 DaemonSet 以将日志发送到 CloudWatch Logs](Container-Insights-setup-logs-FluentBit.md)
+ [（可选）设置 Amazon EKS 控制面板日志记录](Container-Insights-setup-control-plane-logging.md)
+ [（可选）为大型集群启用 Use\$1Kubelet 功能](ContainerInsights-use-kubelet.md)

# 将 Fluent Bit 设置为 DaemonSet 以将日志发送到 CloudWatch Logs
<a name="Container-Insights-setup-logs-FluentBit"></a>

以下部分帮助您部署 Fluent Bit 以将日志从容器发送到 CloudWatch Logs。

**Topics**
+ [设置 Fluent Bit](#Container-Insights-FluentBit-setup)
+ [多行日志支持](#ContainerInsights-fluentbit-multiline)
+ [（可选）从 Fluent Bit 减少日志卷](#ContainerInsights-fluentbit-volume)
+ [问题排查](#Container-Insights-FluentBit-troubleshoot)
+ [控制面板](#Container-Insights-FluentBit-dashboard)

## 设置 Fluent Bit
<a name="Container-Insights-FluentBit-setup"></a>

要设置 Fluent Bit 以从容器中收集日志，您可以按照 [Amazon EKS 和 Kubernetes 上的 Container Insights 的快速入门设置](Container-Insights-setup-EKS-quickstart.md) 中的步骤操作，也可以按照本节中的步骤操作。

无论使用哪种方法，附加到集群节点的 IAM 角色必须具有足够的权限。有关运行 Amazon EKS 集群所需权限的更多信息，请参阅 *Amazon EKS 用户指南*中的 [Amazon EKS IAM 策略、角色和权限](https://docs.aws.amazon.com/eks/latest/userguide/IAM_policies.html)。

在以下步骤中，您将 Fluent Bit 设置为 daemonSet 以将日志发送到 CloudWatch Logs。在完成该步骤时，Fluent Bit 将创建以下日志组（如果尚不存在）。

**重要**  
如果您已经在 Container Insights 中配置了 FluentD 并且 FluentD DaemonSet 没有按预期运行（如果您使用 `containerd` 运行时系统可能会发生这种情况），则必须在安装 Fluent Bit 之前将其卸载，以防止 Fluent Bit 处理 FluentD 错误日志消息。否则，您必须在成功安装 Fluent Bit 后立即卸载 FluentD。在安装 Fluent Bit 后卸载 Fluentd 可确保在此迁移过程中日志记录的连续性。将日志发送到 CloudWatch Logs 只需要 Fluent Bit 或 FluentD 中的其中一个。


| 日志组名称 | 日志源 | 
| --- | --- | 
|  `/aws/containerinsights/Cluster_Name/application`  |  `/var/log/containers` 中的所有日志文件  | 
|  `/aws/containerinsights/Cluster_Name/host`  |  `/var/log/dmesg`、`/var/log/secure` 和 `/var/log/messages` 中的日志  | 
|  `/aws/containerinsights/Cluster_Name/dataplane`  |  `kubelet.service`、`kubeproxy.service` 和 `docker.service` 的 `/var/log/journal` 中的日志。  | 

**安装 Fluent Bit 以将日志从容器发送到 CloudWatch Logs**

1. 如果您还没有名为 `amazon-cloudwatch` 的命名空间，请通过输入以下命令创建一个：

   ```
   kubectl apply -f https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/daemonset/container-insights-monitoring/cloudwatch-namespace.yaml
   ```

1. 运行以下命令以创建一个名为 `cluster-info` 的 ConfigMap，该 ConfigMap 以集群名称和要向其发送日志的区域命名。将 *cluster-name* 和 *cluster-region* 分别替换为您的集群的名称和区域。

   ```
   ClusterName=cluster-name
   RegionName=cluster-region
   FluentBitHttpPort='2020'
   FluentBitReadFromHead='Off'
   [[ ${FluentBitReadFromHead} = 'On' ]] && FluentBitReadFromTail='Off'|| FluentBitReadFromTail='On'
   [[ -z ${FluentBitHttpPort} ]] && FluentBitHttpServer='Off' || FluentBitHttpServer='On'
   kubectl create configmap fluent-bit-cluster-info \
   --from-literal=cluster.name=${ClusterName} \
   --from-literal=http.server=${FluentBitHttpServer} \
   --from-literal=http.port=${FluentBitHttpPort} \
   --from-literal=read.head=${FluentBitReadFromHead} \
   --from-literal=read.tail=${FluentBitReadFromTail} \
   --from-literal=logs.region=${RegionName} -n amazon-cloudwatch
   ```

   在此命令中，默认情况下，用于监控插件指标的 `FluentBitHttpServer` 处于启用状态。要将其关闭，请将命令中的第三行更改为命令中的 `FluentBitHttpPort=''`（空字符串）。

   同样，默认情况下，Fluent Bit 从尾部读取日志文件，并在部署后仅捕获新日志。如果您想要相反的设置，请设置 `FluentBitReadFromHead='On'`，它将收集文件系统中的所有日志。

1. 运行以下任一命令，将 Fluent Bit daemonset 下载并部署到集群中。
   + 如果需要针对 Linux 计算机的 Fluent Bit 优化配置，则请运行此命令。

     ```
     kubectl apply -f https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/daemonset/container-insights-monitoring/fluent-bit/fluent-bit.yaml
     ```
   + 如果需要针对 Windows 计算机的 Fluent Bit 优化配置，则请运行此命令。

     ```
     kubectl apply -f https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/daemonset/container-insights-monitoring/fluent-bit/fluent-bit-windows.yaml
     ```
   + 如果使用 Linux 计算机且需要更类似于 Fluentd 的 Fluent Bit 配置，则请运行此命令。

     ```
     kubectl apply -f https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/daemonset/container-insights-monitoring/fluent-bit/fluent-bit-compatible.yaml
     ```
**重要**  
默认情况下，Fluent Bit 守护程序集配置会将日志级别设置为 INFO，这可能会导致 CloudWatch Logs 摄取成本增加。要减少日志摄取量和成本，您可以将日志级别更改为 ERROR。  
有关如何减少日志量的更多信息，请参阅 [（可选）从 Fluent Bit 减少日志卷](#ContainerInsights-fluentbit-volume)。

1. 运行以下命令以验证部署。每个节点应具有一个名为 **fluent-bit-\$1** 的 pod。

   ```
   kubectl get pods -n amazon-cloudwatch
   ```

上述步骤在集群中创建了以下资源：
+ `amazon-cloudwatch` 命名空间中名为 `Fluent-Bit` 的服务账户。该服务账户用于运行 Fluent Bit daemonSet。有关更多信息，请参阅《Kubernetes 参考》中的 [管理服务账户](https://kubernetes.io/docs/reference/access-authn-authz/service-accounts-admin/)。
+ `amazon-cloudwatch` 命名空间中名为 `Fluent-Bit-role` 的集群角色。该集群角色为 `Fluent-Bit` 服务账户授予有关 pod 日志的 `get`、`list` 和 `watch` 权限。有关更多信息，请参阅《Kubernetes 参考》中的 [API 概述](https://kubernetes.io/docs/reference/access-authn-authz/rbac/#api-overview/)。
+ `amazon-cloudwatch` 命名空间中的名为 `Fluent-Bit-config` 的 ConfigMap。该 ConfigMap 包含由 Fluent Bit 使用的配置。有关更多信息，请参阅《Kubernetes 任务》文档中的 [配置 Pod 以使用 ConfigMap](https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/)。

如果要验证 Fluent Bit 设置，请按照下列步骤操作。

**验证 Fluent Bit 设置**

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 在导航窗格中，选择 **Log groups（日志组）**。

1. 确保您位于部署 Fluent Bit 的区域中。

1. 检查区域中的日志组列表。您将看到以下内容：
   + `/aws/containerinsights/Cluster_Name/application`
   + `/aws/containerinsights/Cluster_Name/host`
   + `/aws/containerinsights/Cluster_Name/dataplane`

1. 导航到其中一个日志组，并检查日志流的 **Last Event Time（上次事件时间）**。如果相对于您部署 Fluent Bit 的时间，它是最近的，则会验证设置。

   创建 `/dataplane` 日志组时，可能会稍有延迟。这是正常的，因为只有在 Fluent Bit 开始为该日志组发送日志时才会创建这些日志组。

## 多行日志支持
<a name="ContainerInsights-fluentbit-multiline"></a>

有关如何将 Fluent Bit 用于多行日志的信息，请参阅 Fluent Bit 文档的以下部分：
+ [多行解析](https://docs.fluentbit.io/manual/administration/configuring-fluent-bit/multiline-parsing)
+ [多行和容器（v1.8）](https://docs.fluentbit.io/manual/pipeline/inputs/tail#multiline-and-containers-v1.8)
+ [多行核心（v1.8）](https://docs.fluentbit.io/manual/pipeline/inputs/tail#multiline-core-v1.8)
+ [始终在尾部输入中使用多行](https://github.com/aws/aws-for-fluent-bit/blob/mainline/troubleshooting/debugging.md#always-use-multiline-the-tail-input)

## （可选）从 Fluent Bit 减少日志卷
<a name="ContainerInsights-fluentbit-volume"></a>

默认情况下，我们将 Fluent Bit 应用程序日志和 Kubernetes 元数据发送到 CloudWatch。如果您要减少发送到 CloudWatch 的数据量，可以停止将这些数据源中的一个或两个发送到 CloudWatch。如果您已按照本页上的步骤设置 Fluent Bit，则请通过之前运行的 kubectl `apply` 命令下载 Kubernetes 清单 YAML 文件，并根据您的更改对其进行修改，然后可以将其重新应用到集群。或者，如果您使用的是 Amazon CloudWatch 可观测性 EKS 加载项或 Helm 图表，则请参阅 [（可选）其他配置](install-CloudWatch-Observability-EKS-addon.md#install-CloudWatch-Observability-EKS-addon-configuration)，了解有关使用加载项的高级配置或 Helm 图表管理 Fluent Bit 配置的信息。

要停止 Fluent Bit 应用程序日志，请从 `Fluent Bit configuration` 文件中删除以下部分。

```
[INPUT]
        Name                tail
        Tag                 application.*
        Path                /var/log/containers/fluent-bit*
        Parser              docker
        DB                  /fluent-bit/state/flb_log.db
        Mem_Buf_Limit       5MB
        Skip_Long_Lines     On
        Refresh_Interval    10
```

要取消将 Kubernetes 元数据附加到发送到 CloudWatch 的日志事件，请在 Fluent Bit 配置的 `application-log.conf` 部分中添加以下筛选条件。将 *<Metadata\$11>* 和类似字段替换为实际的元数据标识符。

```
application-log.conf: |
    [FILTER]
        Name                nest
        Match               application.*
        Operation           lift
        Nested_under        kubernetes
        Add_prefix          Kube.

    [FILTER]
        Name                modify
        Match               application.*
        Remove              Kube.<Metadata_1>
        Remove              Kube.<Metadata_2>
        Remove              Kube.<Metadata_3>
    
    [FILTER]
        Name                nest
        Match               application.*
        Operation           nest
        Wildcard            Kube.*
        Nested_under        kubernetes
        Remove_prefix       Kube.
```

## 问题排查
<a name="Container-Insights-FluentBit-troubleshoot"></a>

如果您没有看到这些日志组并且查看的是正确区域，请检查 Fluent Bit daemonSet pod 日志以查找错误。

运行以下命令，并确保状态为 `Running`。

```
kubectl get pods -n amazon-cloudwatch
```

如果日志具有与 IAM 权限相关的错误，请检查附加到集群节点的 IAM 角色。有关运行 Amazon EKS 集群所需权限的更多信息，请参阅 *Amazon EKS 用户指南*中的 [Amazon EKS IAM 策略、角色和权限](https://docs.aws.amazon.com/eks/latest/userguide/IAM_policies.html)。

如果 pod 状态为 `CreateContainerConfigError`，请运行以下命令以获取确切的错误。

```
kubectl describe pod pod_name -n amazon-cloudwatch
```

## 控制面板
<a name="Container-Insights-FluentBit-dashboard"></a>

您可以创建一个控制面板来监控每个正在运行的插件的指标。您可以查看输入和输出字节以及记录处理率以及输出错误和重试/失败率的数据。要查看这些指标，您需要为 Amazon EKS 和 Kubernetes 集群安装带有 Prometheus 指标集合的 CloudWatch 代理。有关如何设置控制面板的更多信息，请参阅 [在 Amazon EKS 和 Kubernetes 集群上安装带有 Prometheus 指标收集功能的 CloudWatch 代理在 Amazon EKS 和 Kubernetes 集群上安装带有 Prometheus 指标收集功能的 CloudWatch 代理](ContainerInsights-Prometheus-Setup.md)。

**注意**  
在设置此控制面板之前，您必须为 Prometheus 指标设置 Container Insights。有关更多信息，请参阅 [Container Insights Prometheus 指标监控](ContainerInsights-Prometheus.md)。

**为 Fluent Bit Prometheus 指标创建控制面板**

1. 创建环境变量，替换以下行中右侧的值以匹配您的部署。

   ```
   DASHBOARD_NAME=your_cw_dashboard_name
   REGION_NAME=your_metric_region_such_as_us-west-1
   CLUSTER_NAME=your_kubernetes_cluster_name
   ```

1. 通过运行以下命令来创建控制面板。

   ```
   curl https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/sample_cloudwatch_dashboards/fluent-bit/cw_dashboard_fluent_bit.json \
   | sed "s/{{YOUR_AWS_REGION}}/${REGION_NAME}/g" \
   | sed "s/{{YOUR_CLUSTER_NAME}}/${CLUSTER_NAME}/g" \
   | xargs -0 aws cloudwatch put-dashboard --dashboard-name ${DASHBOARD_NAME} --dashboard-body
   ```

# （可选）设置 Amazon EKS 控制面板日志记录
<a name="Container-Insights-setup-control-plane-logging"></a>

如果使用的是 Amazon EKS，您可以选择启用 Amazon EKS 控制面板日志记录，以直接从 Amazon EKS 控制面板中向 CloudWatch Logs 提供审计和诊断日志。有关更多信息，请参阅 [Amazon EKS 控制面板日志记录](https://docs.aws.amazon.com/eks/latest/userguide/control-plane-logs.html)。

# （可选）为大型集群启用 Use\$1Kubelet 功能
<a name="ContainerInsights-use-kubelet"></a>

默认情况下，在 FluentBit Kubernetes 插件中禁用 Use\$1Kubelet 功能。启用此功能可以减少 API 服务器的流量，并缓解 API 服务器成为瓶颈的问题。我们建议您为大型集群启用此功能。

要启用 Use\$1Kubelet，请先将节点和节点/代理权限添加到 clusterRole config 中。

```
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: fluent-bit-role
rules:
  - nonResourceURLs:
      - /metrics
    verbs:
      - get
  - apiGroups: [""]
    resources:
      - namespaces
      - pods
      - pods/logs
      - nodes
      - nodes/proxy
    verbs: ["get", "list", "watch"]
```

在 DaemonSet 配置中，此功能需要主机网络访问权限。适用于 `amazon/aws-for-fluent-bit` 的镜像版本应为 2.12.0 或更高版本，或者 fluent bit 镜像版本应为 1.7.2 或更高版本。

```
apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: fluent-bit
  namespace: amazon-cloudwatch
  labels:
    k8s-app: fluent-bit
    version: v1
    kubernetes.io/cluster-service: "true"
spec:
  selector:
    matchLabels:
      k8s-app: fluent-bit
  template:
    metadata:
      labels:
        k8s-app: fluent-bit
        version: v1
        kubernetes.io/cluster-service: "true"
    spec:
      containers:
      - name: fluent-bit
        image: amazon/aws-for-fluent-bit:2.19.0
        imagePullPolicy: Always
        env:
            - name: AWS_REGION
              valueFrom:
                configMapKeyRef:
                  name: fluent-bit-cluster-info
                  key: logs.region
            - name: CLUSTER_NAME
              valueFrom:
                configMapKeyRef:
                  name: fluent-bit-cluster-info
                  key: cluster.name
            - name: HTTP_SERVER
              valueFrom:
                configMapKeyRef:
                  name: fluent-bit-cluster-info
                  key: http.server
            - name: HTTP_PORT
              valueFrom:
                configMapKeyRef:
                  name: fluent-bit-cluster-info
                  key: http.port
            - name: READ_FROM_HEAD
              valueFrom:
                configMapKeyRef:
                  name: fluent-bit-cluster-info
                  key: read.head
            - name: READ_FROM_TAIL
              valueFrom:
                configMapKeyRef:
                  name: fluent-bit-cluster-info
                  key: read.tail
            - name: HOST_NAME
              valueFrom:
                fieldRef:
                  fieldPath: spec.nodeName
            - name: HOSTNAME
              valueFrom:
                fieldRef:
                  apiVersion: v1
                  fieldPath: metadata.name      
            - name: CI_VERSION
              value: "k8s/1.3.8"
        resources:
            limits:
              memory: 200Mi
            requests:
              cpu: 500m
              memory: 100Mi
        volumeMounts:
        # Please don't change below read-only permissions
        - name: fluentbitstate
          mountPath: /var/fluent-bit/state
        - name: varlog
          mountPath: /var/log
          readOnly: true
        - name: varlibdockercontainers
          mountPath: /var/lib/docker/containers
          readOnly: true
        - name: fluent-bit-config
          mountPath: /fluent-bit/etc/
        - name: runlogjournal
          mountPath: /run/log/journal
          readOnly: true
        - name: dmesg
          mountPath: /var/log/dmesg
          readOnly: true
      terminationGracePeriodSeconds: 10
      hostNetwork: true
      dnsPolicy: ClusterFirstWithHostNet
      volumes:
      - name: fluentbitstate
        hostPath:
          path: /var/fluent-bit/state
      - name: varlog
        hostPath:
          path: /var/log
      - name: varlibdockercontainers
        hostPath:
          path: /var/lib/docker/containers
      - name: fluent-bit-config
        configMap:
          name: fluent-bit-config
      - name: runlogjournal
        hostPath:
          path: /run/log/journal
      - name: dmesg
        hostPath:
          path: /var/log/dmesg
      serviceAccountName: fluent-bit
      tolerations:
      - key: node-role.kubernetes.io/master
        operator: Exists
        effect: NoSchedule
      - operator: "Exists"
        effect: "NoExecute"
      - operator: "Exists"
        effect: "NoSchedule"
```

Kubernetes 插件配置应该类似于以下内容：

```
[FILTER]
        Name                kubernetes
        Match               application.*
        Kube_URL            https://kubernetes.default.svc:443
        Kube_Tag_Prefix     application.var.log.containers.
        Merge_Log           On
        Merge_Log_Key       log_processed
        K8S-Logging.Parser  On
        K8S-Logging.Exclude Off
        Labels              Off
        Annotations         Off
        Use_Kubelet         On
        Kubelet_Port        10250 
        Buffer_Size         0
```

# 在 Amazon EKS 和 Kubernetes 上更新或删除 Container Insights
<a name="ContainerInsights-update-delete"></a>

使用这些章节中的步骤更新 CloudWatch 代理容器镜像，或从 Amazon EKS 或 Kubernetes 集群中删除 Container Insights。

**Topics**
+ [在 CloudWatch 中升级到针对 Amazon EKS 增强了可观测性的 Container Insights](Container-Insights-upgrade-enhanced.md)
+ [更新 CloudWatch 代理容器镜像](ContainerInsights-update-image.md)
+ [删除 Container Insights 的 CloudWatch 代理和 Fluent Bit](ContainerInsights-delete-agent.md)

# 在 CloudWatch 中升级到针对 Amazon EKS 增强了可观测性的 Container Insights
<a name="Container-Insights-upgrade-enhanced"></a>

**重要**  
如果您要在 Amazon EKS 集群上升级或安装 Container Insights，则建议您使用 Amazon CloudWatch Observability EKS 附加组件进行安装，而不是按照本部分中的说明进行安装。此外，要检索加速计算指标，必须使用 Amazon CloudWatch Observability EKS 附加组件。有关更多信息和说明，请参阅 [Amazon CloudWatch 可观测性 EKS 插件快速入门](Container-Insights-setup-EKS-addon.md)。

针对 Amazon EKS 增强了可观测性的 Container Insights 是 Container Insights 的最新版本。它从运行 Amazon EKS 的集群收集详细指标，并提供精选的、可立即使用的控制面板，以深入了解应用程序和基础设施的遥测数据。有关此版本的 Container Insights 的更多信息，请参阅 [针对 Amazon EKS 增强了可观测性的 Container Insights](container-insights-detailed-metrics.md)。

如果您已在 Amazon EKS 集群中安装了 Container Insights 的原始版本，并且想要将其升级到增强了可观测性的较新版本，请按照本部分中的说明进行操作。

**重要**  
在完成本节中的步骤之前，您必须已对包含 cert-manager 等先决条件进行验证。有关更多信息，请参阅 [使用 CloudWatch 代理 operator 和 Fluent Bit 快速入门](Container-Insights-setup-EKS-quickstart.md#Container-Insights-setup-EKS-quickstart-FluentBit)。

**将 Amazon EKS 集群升级到针对 Amazon EKS 增强了可观测性的 Container Insights**

1. 输入以下命令以安装 CloudWatch 代理 operator。将 *my-cluster-name* 替换为 Amazon EKS 或 Kubernetes 集群的名称，将 *my-cluster-region* 替换为在其中发布日志的区域的名称。我们建议您使用在其中部署集群的同一个区域来降低 AWS 出站数据传输成本。

   ```
   ClusterName=my-cluster-name
   RegionName=my-cluster-region
   curl https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/main/k8s-quickstart/cwagent-operator-rendered.yaml | sed 's/{{cluster_name}}/'${ClusterName}'/g;s/{{region_name}}/'${RegionName}'/g' | kubectl apply -f -
   ```

   如果您发现由于资源冲突而导致故障，则可能是因为您已在集群上安装了 CloudWatch 代理和 Fluent Bit 及其关联组件（例如 ServiceAccount、ClusterRole 和 ClusterRoleBinding）。当 CloudWatch 代理 operator 尝试安装 CloudWatch 代理及其关联组件时，如果检测到内容有任何变化，则在默认情况下这会使安装或更新失败，以避免覆盖集群上资源的状态。建议您删除之前在集群上安装的带有 Container Insights 设置的所有现有 CloudWatch 代理，然后安装 CloudWatch 代理 operator。

1. （可选）要应用现有的自定义 Fluent Bit 配置，必须更新与 Fluent Bit 守护程序集关联的 configmap。CloudWatch 代理 operator 为 Fluent Bit 提供了默认配置，您可以根据需要覆盖或修改默认配置。要应用自定义配置，请按照以下步骤操作。

   1. 通过输入以下命令打开现有配置。

      ```
      kubectl edit cm fluent-bit-config -n amazon-cloudwatch
      ```

   1. 在文件中进行更改，然后输入 `:wq` 保存文件并退出编辑模式。

   1. 通过输入以下命令重启 Fluent Bit。

      ```
      kubectl rollout restart ds fluent-bit -n amazon-cloudwatch
      ```

# 更新 CloudWatch 代理容器镜像
<a name="ContainerInsights-update-image"></a>

**重要**  
如果您要在 Amazon EKS 集群上升级或安装 Container Insights，则建议您使用 Amazon CloudWatch Observability EKS 附加组件进行安装，而不是按照本部分中的说明进行安装。此外，要检索加速计算指标，必须使用 Amazon CloudWatch Observability EKS 附加组件或 CloudWatch 代理 operator。有关更多信息和说明，请参阅 [Amazon CloudWatch 可观测性 EKS 插件快速入门](Container-Insights-setup-EKS-addon.md)。

如果需要将容器映像更新到最新版本，请使用本节中的步骤。

**更新您的容器映像**

1. 通过输入以下命令，验证 `amazoncloudwatchagent` 客户资源定义（CRD）是否已经存在。

   ```
   kubectl get crds amazoncloudwatchagents.cloudwatch.aws.amazon.com -n amazon-cloudwatch
   ```

   如果此命令返回缺少 CRD 的错误，则集群没有使用 CloudWatch 代理 operator 配置针对 Amazon EKS 增强了可观测性的 Container Insights。在这种情况下，请参阅[在 CloudWatch 中升级到针对 Amazon EKS 增强了可观测性的 Container Insights](Container-Insights-upgrade-enhanced.md)。

1. 输入以下命令，应用最新的 `cwagent-version.yaml` 文件。

   ```
   curl https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/main/k8s-quickstart/cwagent-version.yaml | kubectl apply -f -
   ```

# 删除 Container Insights 的 CloudWatch 代理和 Fluent Bit
<a name="ContainerInsights-delete-agent"></a>

如果您通过安装适用于 Amazon EKS 的 CloudWatch Observability 附加组件来安装 Container Insights，则可以通过输入以下命令删除 Container Insights 和 CloudWatch 代理：

**注意**  
Amazon EKS 附加组件现在支持 Windows Worker 节点上的 Container Insights。如果您删除 Amazon EKS 附加组件，则 Container Insights for Windows 也会被删除。

```
aws eks delete-addon —cluster-name my-cluster —addon-name amazon-cloudwatch-observability
```

否则，要删除与 CloudWatch 代理和 Fluent Bit 相关的所有资源，请输入以下命令。在此命令中，*My\$1Cluster\$1Name* 是 Amazon EKS 或 Kubernetes 集群的名称，*My\$1Region* 是在其中发布日志的区域的名称。

```
ClusterName=My_Cluster_Name
RegionName=My-Region
curl https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/main/k8s-quickstart/cwagent-operator-rendered.yaml | sed 's/{{cluster_name}}/'${ClusterName}'/g;s/{{region_name}}/'${RegionName}'/g' | kubectl delete -f -
curl https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/main/k8s-quickstart/cwagent-custom-resource-definitions.yaml | kubectl delete -f -
```

# 在 RedHat OpenShift on AWS (ROSA) 上设置 Container Insights
<a name="deploy-container-insights-RedHatOpenShift"></a>

具有增强型可观测性的 CloudWatch Container Insights 支持 RedHat OpenShift on AWS (ROSA)。此版本支持 ROSA 集群的增强型可观测性。安装 CloudWatch 代理 operator Helm 图表后，Container Insights 会自动收集环境中从集群级别到容器级别的详细基础设施遥测数据。然后，它会在精选仪表板中显示这些性能数据，从而消除了可观测性设置中的繁重工作。

**注意**  
对于 RedHat for OpenShift on AWS (ROSA)，当您使用 Helm 图表安装 CloudWatch 代理 operator 时，CloudWatch 代理同样默认启用，可接收来自已针对应用程序信号进行检测的应用程序的指标和跟踪信息。如果想选择性地传递自定义配置规则，可以使用 Helm 图表传入自定义代理配置，如（可选）[附加配置] 中所述，如[（可选）其他配置](install-CloudWatch-Observability-EKS-addon.md#install-CloudWatch-Observability-EKS-addon-configuration)中所述。

**在 RedHat OpenShift on AWS (ROSA) 集群上安装具有增强可观测性的 Container Insights**

1. 如有必要，安装 Helm。有关更多信息，请参阅 Helm 文档中的[快速安装指南](https://helm.sh/docs/intro/quickstart/)。

1. 输入以下命令以安装 CloudWatch 代理 operator。将 *my-cluster-name* 替换为集群的名称，并将 *my-cluster-region* 替换为集群在其中运行的区域。

   ```
   helm repo add aws-observability https://aws-observability.github.io/helm-charts
   helm repo update aws-observability
   helm install --wait --create-namespace \
       --namespace amazon-cloudwatch amazon-cloudwatch-observability \
       aws-observability/amazon-cloudwatch-observability \
       --set clusterName=my-cluster-name \
       --set region=my-cluster-region \
       --set k8sMode=ROSA
   ```

1. 按照[使用 Amazon CloudWatch Observability EKS 附加组件或 Helm 图表安装 CloudWatch 代理](install-CloudWatch-Observability-EKS-addon.md)中选项 1、选项 2 或选项 3 中的步骤为代理 operator 设置授权。

# 查看 Container Insights 指标
<a name="Container-Insights-view-metrics"></a>

在设置了 Container Insights 并开始收集指标后，您可以在 CloudWatch 控制台中查看这些指标。

要在控制面板上显示 Container Insights 指标，您必须完成 Container Insights 设置。有关更多信息，请参阅 [设置 Container Insights](deploy-container-insights.md)。

此过程说明如何查看 Container Insights 根据收集的日志数据自动生成的指标。本节的其余部分介绍了如何进一步深入了解您的数据并使用 CloudWatch Logs Insights 查看更多精细级别的指标。

**查看 Container Insights 指标**

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 在导航窗格中，依次选择 **Insights**、**Container Insights**。

1. 使用靠近顶部的下拉框选择要查看的资源类型以及特定资源。

您可以设置 Container Insights 收集的任何指标的 CloudWatch 告警。有关更多信息，请参阅 [使用 Amazon CloudWatch 告警](CloudWatch_Alarms.md)。

**注意**  
如果您已设置 CloudWatch Application Insights 来监控容器化应用程序，Application Insights 控制面板将显示在 Container Insights 控制面板下方。如果尚未启用 Application Insights，可以通过在 Container Insights 控制面板中的性能视图下方选择 **Auto-configure Application Insights**（自动配置 Application Insights）将其启用。  
有关 Application Insights 和容器化应用程序的更多信息，请参阅 [为 Amazon ECS 和 Amazon EKS 资源监控启用 Application Insights](appinsights-setting-up-console.md#appinsights-container-insights)。

## 查看排名靠前的贡献者
<a name="Container-Insights-view-metrics-topn"></a>

对于 Container Insights 性能监控中的某些视图，您还可以通过内存或 CPU 或最近的活动资源查看排名靠前的贡献者。当您在靠近页面顶部的下拉框中选择以下任一控制面板时，此功能可用：
+ ECS 服务
+ ECS 任务
+ EKS 命名空间
+ EKS 服务
+ EKS Pods

当您查看这些类型的任一资源时，页面底部会显示一个最初按 CPU 使用率排序的表格。您可以将其更改为按内存使用情况或最近的活动进行排序。要查看有关表格中某行的详细信息，可以选中该行旁边的复选框，然后选择 **Actions（操作）**，然后选择 **Actions（操作）**菜单中的任一选项。

## 使用 CloudWatch Logs Insights 查看 Container Insights 数据
<a name="Container-Insights-CloudWatch-Logs-Insights"></a>

Container Insights 通过使用[嵌入式指标格式](CloudWatch_Embedded_Metric_Format.md)的性能日志事件来收集指标。日志存储在 CloudWatch Logs 中。CloudWatch 从日志中自动生成多个指标，您可以在 CloudWatch 控制台中查看这些指标。您还可以对使用 CloudWatch Logs Insights 查询收集到的性能数据进行更深入的分析。

有关 CloudWatch Logs Insights 的更多信息，请参阅[使用 CloudWatch Logs Insights 分析日志数据](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AnalyzingLogData.html)。有关您可以在查询中使用的日志字段的更多信息，请参阅 [Amazon EKS 和 Kubernetes 的 Container Insights 性能日志事件](Container-Insights-reference-performance-logs-EKS.md)。

**使用 CloudWatch Logs Insights 查询容器指标数据**

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 在导航窗格中，依次选择**日志**、**Logs Insights**。

   屏幕顶部附近是查询编辑器。当您首次打开 CloudWatch Logs Insights 时，此框包含一个默认查询，该查询将返回 20 个最新的日志事件。

1. 在查询编辑器上方的框中，选择要查询的 Container Insights 日志组之一。要成功执行以下示例查询，日志组名称必须以 **performance** 结尾。

   当您选择日志组时，CloudWatch Logs Insights 会自动检测日志组数据中的字段，并将其显示在右侧窗格中的 **Discovered fields（发现的字段）**中。它还显示此日志组中的日志事件随时间变化的条形图。该条形图显示与您的查询和时间范围匹配的日志组中的事件分布情况，而不仅仅是表中显示的事件。

1. 在查询编辑器中，将默认查询替换为以下查询，然后选择**运行查询**。

   ```
   STATS avg(node_cpu_utilization) as avg_node_cpu_utilization by NodeName
   | SORT avg_node_cpu_utilization DESC
   ```

   该查询显示一个节点列表，它按平均节点 CPU 使用率进行排序。

1. 要尝试使用另一个示例，请将该查询替换为另一个查询，然后选择**运行查询**。本页稍后将列出更多示例查询。

   ```
   STATS avg(number_of_container_restarts) as avg_number_of_container_restarts by PodName
   | SORT avg_number_of_container_restarts DESC
   ```

   该查询显示一个 pod 列表，它按平均容器重新启动次数进行排序。

1. 如果要尝试使用另一个查询，您可以使用屏幕右侧的列表中的包含字段。有关查询语法的更多信息，请参阅 [CloudWatch Logs Insights 查询语法](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_QuerySyntax.html)。

**查看资源列表**

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 在导航窗格中，选择**资源**。

1. 默认视图是由 Container Insights 监控的资源列表，以及您在这些资源上设置的警报。要查看资源的可视映射，请选择**地图视图**。

1. 在地图视图中，您可以将指针悬停在地图中的任何资源上，查看有关该资源的基本指标。您可以选择任意资源来查看有关该资源的详细图形。

## 使用案例：查看 Amazon ECS 容器中的任务级指标
<a name="Container-Insights-CloudWatch-Logs-Insights-example"></a>

以下示例说明了如何使用 CloudWatch Logs Insights 深入了解 Container Insights 日志。有关更多示例，请参阅博客[推出适用于 Amazon ECS 的 Amazon CloudWatch Container Insights](https://aws.amazon.com/blogs/mt/introducing-container-insights-for-amazon-ecs/)。

 Container Insights 不会在精细的任务级别自动生成指标。以下查询显示 CPU 和内存使用率的任务级指标。

```
stats avg(CpuUtilized) as CPU, avg(MemoryUtilized) as Mem by TaskId, ContainerName
| sort Mem, CPU desc
```

## Container Insights 的其他示例查询
<a name="Container-Insights-sample-queries"></a>

**pod 列表，按平均容器重新启动次数排序**

```
STATS avg(number_of_container_restarts) as avg_number_of_container_restarts by PodName
| SORT avg_number_of_container_restarts DESC
```

**请求的 Pod 与运行的 pod**

```
fields @timestamp, @message 
| sort @timestamp desc 
| filter Type="Pod" 
| stats min(pod_number_of_containers) as requested, min(pod_number_of_running_containers) as running, ceil(avg(pod_number_of_containers-pod_number_of_running_containers)) as pods_missing by kubernetes.pod_name 
| sort pods_missing desc
```

**集群节点故障计数**

```
stats avg(cluster_failed_node_count) as CountOfNodeFailures 
| filter Type="Cluster" 
| sort @timestamp desc
```

**按容器名称的应用程序日志错误**

```
stats count() as countoferrors by kubernetes.container_name 
| filter stream="stderr" 
| sort countoferrors desc
```

# Container Insights 收集的指标
<a name="Container-Insights-metrics"></a>

Container Insights 为 Amazon ECS 和 Amazon ECS 上的 AWS Fargate 收集一组指标，并为 Amazon EKS、Amazon EKS 上的 AWS Fargate、RedHat OpenShift on AWS (ROSA) 和 Kubernetes 收集另一组指标。

容器任务运行一段时间后，指标才可见。

**Topics**
+ [具有增强型可观测性的 Amazon ECS Container Insights](Container-Insights-enhanced-observability-metrics-ECS.md)
+ [Amazon ECS Container Insights 指标](Container-Insights-metrics-ECS.md)
+ [具有增强型可观测性的 Amazon EKS 和 Kubernetes Container Insights](Container-Insights-metrics-enhanced-EKS.md)
+ [Amazon EKS 和 Kubernetes Container Insights 指标](Container-Insights-metrics-EKS.md)
+ [Container Insights 性能日志参考](Container-Insights-reference.md)
+ [Container Insights Prometheus 指标监控](ContainerInsights-Prometheus.md)
+ [与 Application Insights 集成](container-insights-appinsights.md)
+ [在 Container Insights 内查看 Amazon ECS 生命周期事件](container-insights-ECS-lifecycle-events.md)
+ [Container Insights 问题排查](ContainerInsights-troubleshooting.md)
+ [构建您自己的 CloudWatch 代理 Docker 镜像](ContainerInsights-build-docker-image.md)
+ [在容器中部署其他 CloudWatch 代理功能](ContainerInsights-other-agent-features.md)

# 具有增强型可观测性的 Amazon ECS Container Insights
<a name="Container-Insights-enhanced-observability-metrics-ECS"></a>

具有增强型可观测性的 Container Insights 具备以下特点，可以帮助用户更深入地了解容器化工作负载：
+ 任务和容器级别的更高指标粒度
+ 改进的监控和问题排查功能
+ 与 CloudWatch Logs 集成，可用于：
  + 将指标异常与日志条目相关联
  + 更快地进行根本原因分析
  + 缩短复杂容器问题的解决时间

**使用案例**

具有增强型可观测性的 Container Insights 扩展了标准 Container Insights 的功能，并且支持以下使用案例：
+ **任务级别问题排查**：确定任务级别的性能瓶颈。分析任务级别指标并将指标与预留资源进行比较，确定任务是否有足够的处理能力 
+ **容器级别资源优化**：跟踪预留级别的利用率，确定资源受限或过度预置的容器 
+ **容器运行状况评测**：监控重启计数和状态转换，检测需要干预的不稳定容器 
+ **应用程序性能监控**：跟踪应用程序如何相互通信，监控资源使用模式并优化数据存储性能
+ **运行监控**：监控部署，跟踪蓝色或绿色部署的任务集，并通过服务指标维护平台运行状况

有关 Amazon ECS 指标的更多信息，请参阅 [Amazon ECS 服务利用率指标使用案例](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service_utilization-metrics-explanation.html)；有关具有增强型可观测性的 Container Insights 的信息，请参阅[具有增强型可观测性的 Amazon ECS Container Insights 指标](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Container-Insights-enhanced-observability-metrics-ECS.html)。

Container Insights 还会计算所有任务的数据平均值，以显示集群、服务和进程守护程序范围的统计数据。这有助于更深入地了解服务和进程守护程序的运行状况，为环境监控和容量规划提供支持。

**注意**  
Amazon ECS 托管进程守护程序指标使用与服务指标相同的 `ECS/ContainerInsights` 命名空间和 `ServiceName` 维度。对于进程守护程序指标，`ServiceName` 维度值使用 `daemon:daemon-name` 格式。例如，名为 `my-daemon` 的进程守护程序的 `ServiceName` 维度值为 `daemon:my-daemon`。下表中包含 `ServiceName` 维度的所有指标也适用于托管进程守护程序。

下表列出了具有增强型可观测性的 Container Insights 针对 Amazon ECS 收集的指标和维度。这些指标位于 `ECS/ContainerInsights` 命名空间中。有关更多信息，请参阅 [指标](cloudwatch_concepts.md#Metric)。

如果在控制台中未看到任何 Container Insights 指标，请确保已完成具有增强型可观测性的 Container Insights 的设置。在完全设置具有增强型可观测性的 Container Insights 之前，指标不会显示。有关更多信息，请参阅 [设置具有增强型可观测性的 Container Insights](deploy-container-insights-ECS-cluster.md#set-container-insights-ECS-cluster-enhanced)。

以下指标适用于所有启动类型。


| 指标名称 | Dimensions | 说明 | 
| --- | --- | --- | 
|  `ContainerInstanceCount`  |  `ClusterName`  |  注册到集群的运行 Amazon ECS 代理的 EC2 实例的数目。 仅针对在集群中运行 Amazon ECS 任务的容器实例收集此指标。对于没有任何 Amazon ECS 任务的空容器实例，不会收集此指标。 单位：个  | 
|  `ContainerCpuUtilized`  |  `ClusterName` `ContainerName`, `TaskId`, `ServiceName`, `ClusterName` `ContainerName`, `TaskDefinitionFamily`, `ClusterName`, `TaskId` `TaskDefinitionFamily`, `ClusterName`, `ContainerName` `ServiceName`, `ClusterName`, `ContainerName`  |  您正在使用的维度集指定资源中容器使用的 CPU 单元。 也适用于托管进程守护程序。 单位：无  | 
|  `ContainerCpuReserved`  |  `ClusterName` `ContainerName`, `TaskId`, `ServiceName`, `ClusterName` `ContainerName`, `TaskDefinitionFamily`, `ClusterName`, `TaskId` `TaskDefinitionFamily`, `ClusterName`, `ContainerName` `ServiceName`, `ClusterName`, `ContainerName`  |  您正在使用的维度集指定资源中容器预留的 CPU 单元。根据任务定义（例如任务级别或所有容器级别）中指定的 CPU 预留收集此指标。如果未在任务定义中指定 CPU 预留，则会使用实例 CPU 预留。 也适用于托管进程守护程序。 单位：无  | 
|  `ContainerCpuUtilization`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName` `ClusterName`, `ServiceName`, `TaskId` `ClusterName`, `TaskDefinitionFamily`, `TaskId`   | 您正在使用的维度集指定资源中容器正在使用的 CPU 单元总百分比。 单位：百分比 | 
|  `ContainerMemoryUtilized`  |  `ClusterName` `ContainerName`, `TaskId`, `ServiceName`, `ClusterName` `ContainerName`, `TaskDefinitionFamily`, `ClusterName`, `TaskId` `TaskDefinitionFamily`, `ClusterName`, `ContainerName` `ServiceName`, `ClusterName`, `ContainerName`  |  您正在使用的维度集指定资源中容器正在使用的内存。 也适用于托管进程守护程序。 单位：兆字节  | 
|  `ContainerMemoryReserved`  |  `ClusterName` `ContainerName`, `TaskId`, `ServiceName`, `ClusterName` `ContainerName`, `TaskDefinitionFamily`, `ClusterName`, `TaskId` `TaskDefinitionFamily`, `ClusterName`, `ContainerName` `ServiceName`, `ClusterName`, `ContainerName`  |  您正在使用的维度集指定资源中容器预留的内存。 根据任务定义（例如任务级别或所有容器级别）中指定的内存预留收集此指标。如果未在任务定义中指定内存预留，则会使用实例内存预留。 也适用于托管进程守护程序。 单位：兆字节  | 
|  `ContainerMemoryUtilization`  |  `ClusterName` `ContainerName`, `TaskId`, `ServiceName`, `ClusterName` `ContainerName`, `TaskDefinitionFamily`, `ClusterName`, `TaskId` `TaskDefinitionFamily`, `ClusterName`, `ContainerName` `ServiceName`, `ClusterName`, `ContainerName`  | 您正在使用的维度集指定资源中容器正在使用的内存总百分比。 也适用于托管进程守护程序。 单位：百分比 | 
|  `ContainerNetworkRxBytes`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName` `ClusterName`, `ServiceName`, `TaskId` `ClusterName`, `TaskDefinitionFamily`, `TaskId`  |  您正在使用的维度指定容器接收的字节数。该指标是从 Docker 运行时系统获取的。 此指标仅适用于使用 `awsvpc` 或 `bridge` 网络模式的任务中的容器。 也适用于托管进程守护程序。 单位：字节/秒  | 
|  `ContainerNetworkTxBytes`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName` `ClusterName`, `ServiceName`, `TaskId` `ClusterName`, `TaskDefinitionFamily`, `TaskId`  |  您正在使用的维度指定容器传输的字节数。该指标是从 Docker 运行时系统获取的。 此指标仅适用于使用 `awsvpc` 或 `bridge` 网络模式的任务中的容器。 也适用于托管进程守护程序。 单位：字节/秒  | 
|  `ContainerStorageReadBytes`  |  `ClusterName` `ClusterName`, `ServiceName`, `ContainerName` `ClusterName`, `TaskDefinitionFamily`, `ContainerName` `ClusterName`, `ServiceName`, `TaskId`, `ContainerName` `ClusterName`, `TaskDefinitionFamily`, `TaskId`, `ContainerName`  |  从您正在使用的维度指定资源中容器上存储读取的字节数。这不包括存储设备的读取字节数。该指标是从 Docker 运行时系统获取的。 也适用于托管进程守护程序。 单位：字节  | 
|  `ContainerStorageWriteBytes`  |  `ClusterName` `ClusterName`, `ServiceName`, `ContainerName` `ClusterName`, `TaskDefinitionFamily`, `ContainerName` `ClusterName`, `ServiceName`, `TaskId`, `ContainerName` `ClusterName`, `TaskDefinitionFamily`, `TaskId`, `ContainerName`  |  写入到您正在使用的维度指定容器中存储的字节数。该指标是从 Docker 运行时系统获取的。 也适用于托管进程守护程序。 单位：字节  | 
|  `CpuUtilized`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName` `ClusterName`, `ServiceName`, `TaskId` `ClusterName`, `TaskDefinitionFamily`, `TaskId`   |  任务在您使用的维度集所指定的资源中使用的 CPU 单元。 也适用于托管进程守护程序。 单位：无  | 
|  `CpuReserved`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName` `ClusterName`, `ServiceName`, `TaskId` `ClusterName`, `TaskDefinitionFamily`, `TaskId`  |  任务在您使用的维度集所指定的资源中预留的 CPU 单元。根据任务定义（例如任务级别或所有容器级别）中指定的 CPU 预留收集此指标。如果未在任务定义中指定 CPU 预留，则会使用实例 CPU 预留。 也适用于托管进程守护程序。 单位：无  | 
|  `DeploymentCount`  |  `ServiceName`, `ClusterName`  |  Amazon ECS 服务中的部署数。 单位：个  | 
|  `DesiredTaskCount`  |  `ServiceName`, `ClusterName`  |  Amazon ECS 服务所需的任务数。 单位：个  | 
|  `EBSFilesystemSize`  |  `ClusterName` ,`TaskDefinitionFamily`, `VolumeName` `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName`  |  分配给您使用的维度所指定资源的 Amazon EBS 文件系统存储总量，以千兆字节（GB）为单位。 该指标仅适用于使用平台版本 `1.4.0` 在 Fargate 上运行的 Amazon ECS 基础设施上运行的任务，或在使用容器代理版本 `1.79.0` 或更高版本的 Amazon EC2 实例上运行的任务。 也适用于托管进程守护程序。 单位：千兆字节（GB）  | 
|  `EBSFilesystemUtilized`  |  `ClusterName` ,`TaskDefinitionFamily`, `VolumeName` `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName`  |  您使用的维度所指定资源使用的 Amazon EBS 文件系统存储总量，以千兆字节（GB）为单位。 该指标仅适用于使用平台版本 `1.4.0` 在 Fargate 上运行的 Amazon ECS 基础设施上运行的任务，或在使用容器代理版本 `1.79.0` 或更高版本的 Amazon EC2 实例上运行的任务。 对于在 Fargate 上运行的任务，Fargate 会在磁盘上预留仅供 Fargate 使用的空间。Fargate 使用的空间不会产生任何成本，但可以使用类似 `df` 的工具看到额外的存储空间。 也适用于托管进程守护程序。 单位：千兆字节（GB）  | 
|  `TaskEBSFilesystemUtilization`  |  `TaskDefinitionFamily`, `ClusterName` `ClusterName`, `ServiceName` `ClusterName` `ClusterName`, `ServiceName`, `TaskId` `TaskDefinitionFamily`, `ClusterName`, `TaskId`  |  您正在使用的维度指定的任务所使用的 Amazon EBS 文件系统存储的百分比。 该指标仅适用于使用平台版本 `1.4.0` 在 Fargate 上运行的 Amazon ECS 基础设施上运行的任务，或在使用容器代理版本 `1.79.0` 或更高版本的 Amazon EC2 实例上运行的任务。 也适用于托管进程守护程序。 单位：百分比  | 
|  EphemeralStorageReserved [1](#ci-enhanced-metrics-ecs-storage-fargate-note)  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName` `ClusterName`, `ServiceName`, `TaskId` `ClusterName`, `TaskDefinitionFamily`, `TaskId`  |  从您使用的维度所指定的资源中临时存储保留的字节数。临时存储用于容器根文件系统以及容器映像和任务定义中所定义的任何绑定装载主机卷。无法在正在运行的任务中更改临时存储量。 该指标仅适用于在 Fargate Linux 平台 1.4.0 或更高版本上运行的任务。 也适用于托管进程守护程序。 单位：千兆字节（GB）  | 
|  EphemeralStorageUtilized [1](Container-Insights-metrics-ECS.md#ci-metrics-ecs-storage-fargate-note)  |  `ClusterName` `ClusterName`, `TaskDefinitionFamily` `ClusterName`, `ServiceName` `ClusterName`, `ServiceName`, `TaskId` `ClusterName`, `TaskDefinitionFamily`, `TaskId`  |  从您使用的维度所指定的资源中临时存储使用的字节数。临时存储用于容器根文件系统以及容器映像和任务定义中所定义的任何绑定装载主机卷。无法在正在运行的任务中更改临时存储量。 该指标仅适用于在 Fargate Linux 平台 1.4.0 或更高版本上运行的任务。 也适用于托管进程守护程序。 单位：千兆字节（GB）  | 
|  `MemoryUtilized`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName` `ClusterName`, `ServiceName`, `TaskId` `ClusterName`, `TaskDefinitionFamily`, `TaskId`  |  任务在您使用的维度集所指定的资源中使用的内存。 也适用于托管进程守护程序。 单位：兆字节  | 
|  `MemoryReserved`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName` `ClusterName`, `ServiceName`, `TaskId` `ClusterName`, `TaskDefinitionFamily`, `TaskId`  |  任务在您使用的维度集所指定的资源中预留的内存。 根据任务定义（例如任务级别或所有容器级别）中指定的内存预留收集此指标。如果未在任务定义中指定内存预留，则会使用实例内存预留。 也适用于托管进程守护程序。 单位：兆字节  | 
|  `NetworkRxBytes`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName` `ClusterName`, `ServiceName`, `TaskId` `ClusterName`, `TaskDefinitionFamily`, `TaskId`  |  您使用的维度所指定的资源接收的字节数。该指标是从 Docker 运行时系统获取的。 此指标仅适用于使用 `awsvpc` 或 `bridge` 网络模式的任务中的容器。 也适用于托管进程守护程序。 单位：字节/秒  | 
|  `NetworkTxBytes`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName` `ClusterName`, `ServiceName`, `TaskId` `ClusterName`, `TaskDefinitionFamily`, `TaskId`  |  您使用的维度所指定的资源传输的字节数。该指标是从 Docker 运行时系统获取的。 此指标仅适用于使用 `awsvpc` 或 `bridge` 网络模式的任务中的容器。 也适用于托管进程守护程序。 单位：字节/秒  | 
|  `PendingTaskCount`  |  `ServiceName`, `ClusterName`  |  当前处于 `PENDING` 状态的任务的数量。 单位：个  | 
|  `RunningTaskCount`  |  `ServiceName`, `ClusterName`  |  当前处于 `RUNNING` 状态的任务的数量。 单位：个  | 
|  `RestartCount`  |  `ClusterName` `ClusterName`, `ServiceName` `ClusterName`, `TaskDefinitionFamily` `ClusterName`, `ServiceName`, `TaskId` `ClusterName`, `TaskDefinitionFamily`, `TaskId` `ClusterName`, `ServiceName`, `ContainerName` `ClusterName`, `ServiceName`, `TaskId`, `ContainerName` `TaskDefinitionFamily`, `ClusterName`, `ContainerName` `TaskDefinitionFamily`, `ClusterName`, `TaskId`, `ContainerName`  |  Amazon ECS 任务中容器重新启动的次数。 仅会对启用了重启策略的容器收集此指标。 也适用于托管进程守护程序。 单位：个  | 
|  `UnHealthyContainerHealthStatus`  |  `ClusterName` `ClusterName`, `ServiceName`, `ContainerName` `ClusterName`, `TaskDefinitionFamily`, `ContainerName` `ClusterName`, `ServiceName`, `TaskId`, `ContainerName` `ClusterName`, `TaskDefinitionFamily`, `TaskId`, `ContainerName`  |  基于容器运行状况检查状态的非正常运行容器的数量。当容器的运行状况检查结果为不正常状态时，该容器就被视为不正常。 此指标仅针对在任务定义中已配置运行状况检查的容器进行收集。 当容器运行状况为 `UNHEALTHY` 时，指标值为 1；当运行状况为 `HEALTHY` 时，指标值为 0。 单位：个  | 
|  `ServiceCount`  |  `ClusterName`  |  集群中的服务数。 单位：个  | 
|  `StorageReadBytes`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName` `ClusterName`, `ServiceName`, `TaskId` `ClusterName`, `TaskDefinitionFamily`, `TaskId`  |  从您使用之维度所指定资源中实例上的存储读取的字节数。这不包括存储设备的读取字节数。该指标是从 Docker 运行时系统获取的。 也适用于托管进程守护程序。 单位：字节  | 
|  `StorageWriteBytes`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName` `ClusterName`, `ServiceName`, `TaskId` `ClusterName`, `TaskDefinitionFamily`, `TaskId`  |  写入到您使用的维度所指定的资源中的存储的字节数。该指标是从 Docker 运行时系统获取的。 也适用于托管进程守护程序。 单位：字节  | 
|  `TaskCount`  |  `ClusterName`  |  正在集群中运行的任务数。 单位：个  | 
|  `TaskCpuUtilization`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName` `ClusterName`, `ServiceName`, `TaskId` `ClusterName`, `TaskDefinitionFamily`, `TaskId`   |  任务使用的 CPU 单元的总百分比。 也适用于托管进程守护程序。 单位：百分比  | 
|  `TaskEphemeralStorageUtilization`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName` `ClusterName`, `ServiceName`, `TaskId` `ClusterName`, `TaskDefinitionFamily`, `TaskId`   |  任务使用的临时存储总百分比。 也适用于托管进程守护程序。 单位：百分比  | 
|  `TaskMemoryUtilization`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName` `ClusterName`, `ServiceName`, `TaskId` `ClusterName`, `TaskDefinitionFamily`, `TaskId`   |  任务使用的内存总百分比。 也适用于托管进程守护程序。 单位：百分比  | 
|  `TaskSetCount`  |  `ServiceName`, `ClusterName`  |  服务中设置的任务数。 单位：个  | 

**注意**  
`EphemeralStorageReserved` 和 `EphemeralStorageUtilized` 指标仅适用于在 Fargate Linux 平台 1.4.0 或更高版本上运行的任务。  
Fargate 可保留磁盘空间。该磁盘空间仅由 Fargate 使用。您无需为此付费。它没有显示在这些指标中。但是，您可以在 `df` 等其他工具中看到这种额外的存储空间。

完成[部署 CloudWatch 代理以收集 Amazon ECS 上的 EC2 实例级别指标](deploy-container-insights-ECS-instancelevel.md)中的步骤并使用 EC2 启动类型后，以下指标将可用。


| 指标名称 | Dimensions | 说明 | 
| --- | --- | --- | 
|  `instance_cpu_limit`  |  `ClusterName`  |  可分配给集群中单个 EC2 实例的 CPU 单元最大数目。 单位：无  | 
|  `instance_cpu_reserved_capacity`  |  `ClusterName` `InstanceId`, `ContainerInstanceId`, `ClusterName`  |  集群中单个 EC2 实例上当前预留的 CPU 的百分比。 单位：百分比  | 
|  `instance_cpu_usage_total`  |  `ClusterName`  |  集群中单个 EC2 实例上正在使用的 CPU 单元的数目。 单位：无  | 
|  `instance_cpu_utilization`  |  `ClusterName` `InstanceId`, `ContainerInstanceId`, `ClusterName`  |  集群中单个 EC2 实例上正在使用的 CPU 单元的总百分比。 单位：百分比  | 
|  `instance_filesystem_utilization`  |  `ClusterName` `InstanceId`, `ContainerInstanceId`, `ClusterName`  |  集群中单个 EC2 实例上正在使用的文件系统容量的总百分比。 单位：百分比  | 
|  `instance_memory_limit`  |  `ClusterName`  |  可分配给此集群中单个 EC2 实例的最大内存量（以字节为单位）。 单位：字节  | 
|  `instance_memory_reserved_capacity`  |  `ClusterName` `InstanceId`, `ContainerInstanceId`, `ClusterName`  |  集群中单个 EC2 实例上当前预留的内存百分比。 单位：百分比  | 
|  `instance_memory_utilization`  |  `ClusterName` `InstanceId`, `ContainerInstanceId`, `ClusterName`  |  集群中单个 EC2 实例上正在使用的内存总百分比。  如果您的应用程序中使用 Java ZGC 垃圾收集器，则该指标可能不准确。  单位：百分比  | 
|  `instance_memory_working_set`  |  `ClusterName`  |  集群中单个 EC2 实例上正在使用的内存量（以字节为单位）。  如果您的应用程序中使用 Java ZGC 垃圾收集器，则该指标可能不准确。  单位：字节  | 
|  `instance_network_total_bytes`  |  `ClusterName`  |  集群中单个 EC2 实例上通过网络传输和接收的每秒总字节数。 单位：字节/秒  | 
|  `instance_number_of_running_tasks`  |  `ClusterName`  |  集群中单个 EC2 实例上正在运行的任务数。 单位：个  | 

# Amazon ECS Container Insights 指标
<a name="Container-Insights-metrics-ECS"></a>

Container Insights 指标提供了额外的网络指标、存储指标和临时存储指标。这些指标提供的信息比标准 Amazon ECS 指标要多。Container Insights 与 CloudWatch Logs 集成。您可以将指标更改与日志条目相关联，以便于进行问题排查。Container Insights 还会计算所有任务的数据平均值，以显示集群、服务和进程守护程序范围的统计数据。这有助于更深入地了解服务和进程守护程序的运行状况，为环境监控和容量规划提供支持。

**使用案例**
+ **问题识别和故障排除**：通过分析任务状态转换模式来跟踪失败的部署，从而快速识别故障点。通过全面检查任务启动顺序和初始化行为来诊断配置问题
+ **集群和服务级别运行状况评测**：显示整个集群的平均任务性能。这种方法可以调节异常值，提供更稳定的集群和服务运行状况视图。使用这些洞察进行一般服务监控，极值在一般服务监控中可能会产生误导 
+ **服务可用性问题**：通过监控正在运行的任务计数指标来检测失败的部署。将服务事件日志与性能指标相关联，了解基础设施的影响。跟踪任务重启模式以发现不稳定的服务或基础设施问题
+ **平均负载的容量规划**：有助于根据典型的任务行为模式确定资源需求，提供适用于有效长期规划的一致指标，并减少短期峰值对容量决策的影响
+ **提供其他指标**：收集公开发布的指标中不可用的其他网络指标、存储指标和临时存储指标

有关 Amazon ECS 指标的更多信息，请参阅 [Amazon ECS 服务利用率指标使用案例](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service_utilization-metrics-explanation.html)；有关具有增强型可观测性的 Container Insights 的信息，请参阅[具有增强型可观测性的 Amazon ECS Container Insights 指标](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Container-Insights-enhanced-observability-metrics-ECS.html)。

**注意**  
Amazon ECS 托管进程守护程序指标使用与服务指标相同的 `ECS/ContainerInsights` 命名空间和 `ServiceName` 维度。对于进程守护程序指标，`ServiceName` 维度值使用 `daemon:daemon-name` 格式。例如，名为 `my-daemon` 的进程守护程序的 `ServiceName` 维度值为 `daemon:my-daemon`。下表中包含 `ServiceName` 维度的所有指标也适用于托管进程守护程序。

下表列出了 Container Insights 收集的针对 Amazon ECS 的指标和维度。这些指标位于 `ECS/ContainerInsights` 命名空间中。有关更多信息，请参阅 [指标](cloudwatch_concepts.md#Metric)。

如果您在控制台中未看到任何 Container Insights 指标，请确保已完成 Container Insights 的设置。在完全设置 Container Insights 之前，指标不会显示。有关更多信息，请参阅 [设置 Container Insights](deploy-container-insights.md)。

完成[在 Amazon ECS 上设置 Container Insights](deploy-container-insights-ECS-cluster.md)中的步骤后，以下指标将可用。


| 指标名称 | Dimensions | 说明 | 
| --- | --- | --- | 
|  `ContainerInstanceCount`  |  `ClusterName`  |  注册到集群的运行 Amazon ECS 代理的 EC2 实例的数目。 仅针对在集群中运行 Amazon ECS 任务的容器实例收集此指标。对于没有任何 Amazon ECS 任务的空容器实例，不会收集此指标。 单位：个  | 
|  `CpuUtilized`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName`  |  任务在您使用的维度集所指定的资源中使用的 CPU 单元。 也适用于托管进程守护程序。 单位：无  | 
|  `CpuReserved`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName`  |  任务在您使用的维度集所指定的资源中预留的 CPU 单元。 根据任务定义（例如任务级别或所有容器级别）中指定的 CPU 预留收集此指标。如果未在任务定义中指定 CPU 预留，则会使用实例 CPU 预留。 也适用于托管进程守护程序。 单位：无  | 
|  `DeploymentCount`  |  `ServiceName`, `ClusterName`  |  Amazon ECS 服务中的部署数。 单位：个  | 
|  `DesiredTaskCount`  |  `ServiceName`, `ClusterName`  |  Amazon ECS 服务所需的任务数。 单位：个  | 
|  `EBSFilesystemSize`  |  `VolumeName`, `TaskDefinitionFamily`, `ClusterName` `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName`  |  分配给您使用的维度所指定资源的 Amazon EBS 文件系统存储总量，以千兆字节（GB）为单位。 该指标仅适用于使用平台版本 `1.4.0` 在 Fargate 上运行的 Amazon ECS 基础设施上运行的任务，或在使用容器代理版本 `1.79.0` 或更高版本的 Amazon EC2 实例上运行的任务。 也适用于托管进程守护程序。 单位：千兆字节（GB）  | 
|  `EBSFilesystemUtilized`  |  `VolumeName`, `TaskDefinitionFamily`, `ClusterName` `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName`  |  您使用的维度所指定资源使用的 Amazon EBS 文件系统存储总量，以千兆字节（GB）为单位。 该指标仅适用于使用平台版本 `1.4.0` 在 Fargate 上运行的 Amazon ECS 基础设施上运行的任务，或在使用容器代理版本 `1.79.0` 或更高版本的 Amazon EC2 实例上运行的任务。 对于在 Fargate 上运行的任务，Fargate 会在磁盘上预留仅供 Fargate 使用的空间。Fargate 使用的空间不会产生任何成本，但可以使用类似 `df` 的工具看到额外的存储空间。 也适用于托管进程守护程序。 单位：千兆字节（GB）  | 
|  EphemeralStorageReserved [1](#ci-metrics-ecs-storage-fargate-note)  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName`  |  从您使用的维度所指定的资源中临时存储保留的字节数。临时存储用于容器根文件系统以及容器映像和任务定义中所定义的任何绑定装载主机卷。无法在正在运行的任务中更改临时存储量。 该指标仅适用于在 Fargate Linux 平台 1.4.0 或更高版本上运行的任务。 也适用于托管进程守护程序。 单位：千兆字节（GB）  | 
|  EphemeralStorageUtilized [1](#ci-metrics-ecs-storage-fargate-note)  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName`  |  从您使用的维度所指定的资源中临时存储使用的字节数。临时存储用于容器根文件系统以及容器映像和任务定义中所定义的任何绑定装载主机卷。无法在正在运行的任务中更改临时存储量。 该指标仅适用于在 Fargate Linux 平台 1.4.0 或更高版本上运行的任务。 也适用于托管进程守护程序。 单位：千兆字节（GB）  | 
|  `InstanceOSFilesystemUtilization`  |  `CapacityProviderName`, `ClusterName`, `ContainerInstanceId`, `EC2InstanceId` `ClusterName`  |  操作系统卷已使用磁盘空间占总磁盘空间的百分比。  | 
|  `InstanceDataFilesystemUtilization`  |  `CapacityProviderName`, `ClusterName`, `ContainerInstanceId`, `EC2InstanceId` `ClusterName`  |  数据卷已使用磁盘空间占总磁盘空间的百分比。  | 
|  `MemoryUtilized`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName`  |  任务在您使用的维度集所指定的资源中使用的内存。  如果您的应用程序中使用 Java ZGC 垃圾收集器，则该指标可能不准确。 尽管 `MemoryUtilized` 和 `MemoryReserved` 都标记为“兆字节”，但实际单位是 MiB（二进制兆字节）。  也适用于托管进程守护程序。 单位：兆字节  | 
|  `MemoryReserved`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName`  |  任务在您使用的维度集所指定的资源中预留的内存。根据任务定义（例如任务级别或所有容器级别）中指定的内存预留收集此指标。如果未在任务定义中指定内存预留，则会使用实例内存预留。 也适用于托管进程守护程序。 单位：兆字节  尽管 `MemoryUtilized` 和 `MemoryReserved` 都标记为“兆字节”，但实际单位是 MiB（二进制兆字节）。   | 
|  `NetworkRxBytes`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName`  |  您使用的维度所指定的资源接收的字节数。该指标是从 Docker 运行时系统获取的。 此指标仅适用于使用 `awsvpc` 或 `bridge` 网络模式的任务中的容器。 也适用于托管进程守护程序。 单位：字节/秒  | 
|  `NetworkTxBytes`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName`  |  您使用的维度所指定的资源传输的字节数。该指标是从 Docker 运行时系统获取的。 此指标仅适用于使用 `awsvpc` 或 `bridge` 网络模式的任务中的容器。 也适用于托管进程守护程序。 单位：字节/秒  | 
|  `PendingTaskCount`  |  `ServiceName`, `ClusterName`  |  当前处于 `PENDING` 状态的任务的数量。 单位：个  | 
|  `RunningTaskCount`  |  `ServiceName`, `ClusterName`  |  当前处于 `RUNNING` 状态的任务的数量。 单位：个  | 
|  `RestartCount`  |  `ClusterName` `ClusterName`, `ServiceName` `ClusterName`, `TaskDefinitionFamily`  |  Amazon ECS 任务中容器重新启动的次数。 仅会对启用了重启策略的容器收集此指标。 也适用于托管进程守护程序。 单位：个  | 
|  `ServiceCount`  |  `ClusterName`  |  集群中的服务数。 单位：个  | 
|  `StorageReadBytes`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName`  |  从您使用之维度所指定资源中实例上的存储读取的字节数。这不包括存储设备的读取字节数。该指标是从 Docker 运行时系统获取的。 也适用于托管进程守护程序。 单位：字节  | 
|  `StorageWriteBytes`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName`  |  写入到您使用的维度所指定的资源中的存储的字节数。该指标是从 Docker 运行时系统获取的。 也适用于托管进程守护程序。 单位：字节  | 
|  `TaskCount`  |  `ClusterName`  |  正在集群中运行的任务数。 单位：个  | 
|  `TaskSetCount`  |  `ServiceName`, `ClusterName`  |  服务中设置的任务数。 单位：个  | 

**注意**  
`EphemeralStorageReserved` 和 `EphemeralStorageUtilized` 指标仅适用于在 Fargate Linux 平台 1.4.0 或更高版本上运行的任务。  
Fargate 可保留磁盘空间。该磁盘空间仅由 Fargate 使用。您无需为此付费。它没有显示在这些指标中。但是，您可以在 `df` 等其他工具中看到这种额外的存储空间。

完成[部署 CloudWatch 代理以收集 Amazon ECS 上的 EC2 实例级别指标](deploy-container-insights-ECS-instancelevel.md)中的步骤后，以下指标将可用


| 指标名称 | Dimensions | 说明 | 
| --- | --- | --- | 
|  `instance_cpu_limit`  |  `ClusterName`  |  可分配给集群中的单个 EC2 实例的 CPU 单元的最大数目。 单位：无  | 
|  `instance_cpu_reserved_capacity`  |  `ClusterName` `InstanceId`, `ContainerInstanceId`, `ClusterName`  |  集群中单个 EC2 实例上当前预留的 CPU 的百分比。 单位：百分比  | 
|  `instance_cpu_usage_total`  |  `ClusterName`  |  集群中单个 EC2 实例上正在使用的 CPU 单元的数目。 单位：无  | 
|  `instance_cpu_utilization`  |  `ClusterName` `InstanceId`, `ContainerInstanceId`, `ClusterName`  |  集群中单个 EC2 实例上正在使用的 CPU 单元的总百分比。 单位：百分比  | 
|  `instance_filesystem_utilization`  |  `ClusterName` `InstanceId`, `ContainerInstanceId`, `ClusterName`  |  集群中单个 EC2 实例上正在使用的文件系统容量的总百分比。 单位：百分比  | 
|  `instance_memory_limit`  |  `ClusterName`  |  可分配给此集群中单个 EC2 实例的最大内存量（以字节为单位）。 单位：字节  | 
|  `instance_memory_reserved_capacity`  |  `ClusterName` `InstanceId`, `ContainerInstanceId`, `ClusterName`  |  集群中单个 EC2 实例上当前预留的内存的百分比。 单位：百分比  | 
|  `instance_memory_utilization`  |  `ClusterName` `InstanceId`, `ContainerInstanceId`, `ClusterName`  |  集群中单个 EC2 实例上正在使用的内存的总百分比。  如果您的应用程序中使用 Java ZGC 垃圾收集器，则该指标可能不准确。  单位：百分比  | 
|  `instance_memory_working_set`  |  `ClusterName`  |  集群中单个 EC2 实例上正在使用的内存量（以字节为单位）。  如果您的应用程序中使用 Java ZGC 垃圾收集器，则该指标可能不准确。  单位：字节  | 
|  `instance_network_total_bytes`  |  `ClusterName`  |  集群中单个 EC2 实例通过网络传输和接收的每秒总字节数。 单位：字节/秒  | 
|  `instance_number_of_running_tasks`  |  `ClusterName`  |  集群中单个 EC2 实例上正在运行的任务的数目。 单位：个  | 

# 具有增强型可观测性的 Amazon EKS 和 Kubernetes Container Insights
<a name="Container-Insights-metrics-enhanced-EKS"></a>

下表列出了具有增强型可观测性的 Container Insights 为 Amazon EKS 和 Kubernetes 收集的指标和维度。这些指标位于 `ContainerInsights` 命名空间中。有关更多信息，请参阅 [指标](cloudwatch_concepts.md#Metric)。

如果在控制台中未看到任何具有增强型可观测性的 Container Insights 指标，请确保已完成具有增强型可观测性的 Container Insights 的设置。在完全设置具有增强型可观测性的 Container Insights 之前，指标不会显示。有关更多信息，请参阅 [设置 Container Insights](deploy-container-insights.md)。

如果您使用 Amazon EKS 附加组件 1.5.0 版或更高版本或者 CloudWatch 代理 1.300035.0 版，则将为 Linux 和 Windows 节点收集下表中列出的大多数指标。请参阅该表的**指标名称**列，了解哪些指标并非为 Windows 收集。

Container Insights 的早期版本在集群和服务级别提供聚合指标，这些指标作为自定义指标收费。借助针对 Amazon EKS 增强了可观测性的 Container Insights，Container Insights 指标按每次观测收费，而不是按存储的指标或摄取的日志收费。有关 CloudWatch 定价的信息，请参阅 [Amazon CloudWatch 定价](https://aws.amazon.com/cloudwatch/pricing/)。

**注意**  
在 Windows 上，不会为主机进程容器收集 `pod_network_rx_bytes` 和 `pod_network_tx_bytes` 等网络指标。  
在 RedHat OpenShift on AWS (ROSA) 集群中，不会收集 `node_diskio_io_serviced_total`、`node_diskio_io_service_bytes_total` 等磁盘指标。


| 指标名称 | Dimensions | 说明 | 
| --- | --- | --- | 
|  `cluster_failed_node_count`  |  `ClusterName`  |  集群中失败的工作线程节点的数目。如果节点遭受任何*节点条件*的影响，则该节点被视为失败。有关更多信息，请参阅 Kubernetes 文档中的[条件](https://kubernetes.io/docs/concepts/architecture/nodes/#condition)。  | 
|  `cluster_node_count`  |  `ClusterName`  |  集群中工作线程节点的总数。  | 
|  `namespace_number_of_running_pods`  |  `Namespace` `ClusterName` `ClusterName`  |  您使用的维度所指定的资源中每个命名空间运行的 pod 的数目。  | 
|  `node_cpu_limit`  |  `ClusterName`  `ClusterName`, `InstanceId`, `NodeName`   |  可以分配给此集群中单个节点的 CPU 单元的最大数目。  | 
|  `node_cpu_reserved_capacity`  |  `NodeName`, `ClusterName`, `InstanceId` `ClusterName`  |  为节点组件保留的 CPU 单元的百分比，例如 kubelet、kube-proxy 和 Docker。 公式：`node_cpu_request / node_cpu_limit`  `node_cpu_request` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `node_cpu_usage_total`  |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`  |  集群中节点上正在使用的 CPU 单元的数目。  | 
|  `node_cpu_utilization`  |  `NodeName`, `ClusterName`, `InstanceId` `ClusterName`  |  集群中节点上正在使用的 CPU 单元的总百分比。 公式：`node_cpu_usage_total / node_cpu_limit`  | 
|  `node_filesystem_utilization`  |  `NodeName`, `ClusterName`, `InstanceId` `ClusterName`  |  集群中节点上正在使用的文件系统容量的总百分比。 公式：`node_filesystem_usage / node_filesystem_capacity`  `node_filesystem_usage` 和 `node_filesystem_capacity` 不是直接作为指标报告，而是性能日志事件中的字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `node_memory_limit`  |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`   |  可以分配给此集群中单个节点的最大内存量（以字节为单位）。  | 
|  `node_filesystem_inodes`  其在 Windows 上不可用。  |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`   |  节点上 inode（已使用和未使用）的总数。  | 
|  `node_filesystem_inodes_free` 其在 Windows 上不可用。  |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`   |  节点上未使用 inode 的总数。  | 
|  `node_gpu_limit` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`  |  节点上可用 GPU 的总数。  | 
|  `node_gpu_usage_total` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`  |  节点上正在运行的容器组 (pod) 正在使用的 GPU 数量。  | 
|  `node_gpu_reserved_capacity` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`  | 
|  `node_memory_reserved_capacity`  |  `NodeName`, `ClusterName`, `InstanceId` `ClusterName`  |  集群中节点上当前正在使用的内存百分比。 公式：`node_memory_request / node_memory_limit`  `node_memory_request` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `node_memory_utilization`  |  `NodeName`, `ClusterName`, `InstanceId` `ClusterName`  |  一个或多个节点当前正在使用的内存百分比。它是节点内存使用量除以节点内存限制的百分比。 公式：`node_memory_working_set / node_memory_limit`。  | 
|  `node_memory_working_set`  |  `ClusterName`  `ClusterName`, `InstanceId`, `NodeName`   |  集群中节点的工作集中正在使用的内存量（以字节为单位）。  | 
|  `node_network_total_bytes`  |  `NodeName`, `ClusterName`, `InstanceId` `ClusterName`  |  集群中每个节点通过网络传输和接收的每秒总字节数。 公式：`node_network_rx_bytes + node_network_tx_bytes`  `node_network_rx_bytes` 和 `node_network_tx_bytes` 不是直接作为指标报告，而是性能日志事件中的字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `node_number_of_running_containers`  |  `NodeName`, `ClusterName`, `InstanceId` `ClusterName`  |  集群中每个节点的正在运行的容器数。  | 
|  `node_number_of_running_pods`  |  `NodeName`, `ClusterName`, `InstanceId` `ClusterName`  |  集群中每个节点上运行的 pod 的数量。  | 
|  `node_status_allocatable_pods`   |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`   |  根据节点的可分配资源可以分配给节点的容器组（pod）数量，这定义为考虑系统进程守护程序预留和硬驱逐阈值后的节点容量余数。  | 
|  `node_status_capacity_pods`  |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`   |  根据节点容量可以分配给节点的容器组（pod）数量。  | 
|  `node_status_condition_ready`   |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`   |  表示 Amazon EC2 节点的节点状态条件 `Ready` 是否为 true。  | 
|  `node_status_condition_memory_pressure`   |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`   |  表示节点状态条件是 `MemoryPressure` 是否为 true。  | 
|  `node_status_condition_pid_pressure`   |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`   |  表示节点状态条件是 `PIDPressure` 是否为 true。  | 
|  `node_status_condition_disk_pressure`   |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`   |  表示节点状态条件是 `OutOfDisk` 是否为 true。  | 
|  `node_status_condition_unknown`   |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`   |  表示是否有任何节点状态条件为“未知”。  | 
|  `node_interface_network_rx_dropped`  |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`   |  节点上的网络接口接收并随后丢弃的数据包数量。  | 
|  `node_interface_network_tx_dropped`  |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`   |  本应传输但被节点上的网络接口丢弃的数据包数量。  | 
|  `node_diskio_io_service_bytes_total`  其在 Windows 或 ROSA 集群上不可用。  |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`   |  节点上所有 I/O 操作传输的总字节数。  | 
|  `node_diskio_io_serviced_total` 其在 Windows 或 ROSA 集群上不可用。  |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`   |  节点上 I/O 操作的总数。  | 
|  `pod_cpu_reserved_capacity`  |  `PodName`, `Namespace`, `ClusterName` `ClusterName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  `ClusterName`, `Namespace`, `Service`   |  集群中每个 pod 预留的 CPU 容量。 公式：`pod_cpu_request / node_cpu_limit`  `pod_cpu_request` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `pod_cpu_utilization`  |  `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName` `Service`, `Namespace`, `ClusterName` `ClusterName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`   |  pod 所使用的 CPU 单元的百分比。 公式：`pod_cpu_usage_total / node_cpu_limit`  | 
|  `pod_cpu_utilization_over_pod_limit`  |  `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName` `Service`, `Namespace`, `ClusterName` `ClusterName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`   |  相对于容器组（pod）限制的容器组（pod）所使用的 CPU 单元的百分比。 公式：`pod_cpu_usage_total / pod_cpu_limit`  | 
|  `pod_memory_reserved_capacity`  |  `PodName`, `Namespace`, `ClusterName` `ClusterName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  `ClusterName`, `Namespace`, `Service`   |  为 pod 预留的内存的百分比。 公式：`pod_memory_request / node_memory_limit`  `pod_memory_request` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `pod_memory_utilization`  |  `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName` `Service`, `Namespace`, `ClusterName` `ClusterName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`   |  一个或多个 pod 当前正在使用的内存百分比。 公式：`pod_memory_working_set / node_memory_limit`  | 
|  `pod_memory_utilization_over_pod_limit`  |  `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName` `Service`, `Namespace`, `ClusterName` `ClusterName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`   |  相对于容器组（pod）限制的容器组（pod）所使用的内存百分比。如果容器组（pod）中的任何容器没有定义内存限制，则不会显示该指标。 公式：`pod_memory_working_set / pod_memory_limit`  | 
|  `pod_network_rx_bytes`  |  `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName` `Service`, `Namespace`, `ClusterName` `ClusterName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`   |  pod 通过网络每秒接收的字节数。 公式：`sum(pod_interface_network_rx_bytes)`  `pod_interface_network_rx_bytes` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `pod_network_tx_bytes`  |  `PodName`, `Namespace`, `ClusterName` `Namespace,` `ClusterName` `Service`, `Namespace`, `ClusterName` `ClusterName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`   |  pod 通过网络每秒传输的字节数。 公式：`sum(pod_interface_network_tx_bytes)`  `pod_interface_network_tx_bytes` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `pod_cpu_request`   |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  容器组（pod）的 CPU 请求。 公式：`sum(container_cpu_request)`  `pod_cpu_request` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `pod_memory_request`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  容器组（pod）的内存请求。 公式：`sum(container_memory_request)`  `pod_memory_request` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `pod_cpu_limit`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  为容器组（pod）中的容器定义的 CPU 限制。如果容器组（pod）中的任何容器没有定义 CPU 限制，则不会显示此指标。 公式：`sum(container_cpu_limit)`  `pod_cpu_limit` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `pod_memory_limit`   |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  为容器组（pod）中的容器定义的内存限制。如果容器组（pod）中的任何容器没有定义内存限制，则不会显示该指标。 公式：`sum(container_memory_limit)`  `pod_cpu_limit` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `pod_status_failed`   |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  表示容器组（pod）中的所有容器都已终止，并且至少有一个容器以非零状态终止或已被系统终止。  | 
|  `pod_status_ready`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  表示容器组（pod）中的所有容器都已准备就绪，且已达到 `ContainerReady` 的条件。  | 
|  `pod_status_running`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  表示容器组（pod）中的所有容器都在运行。  | 
|  `pod_status_scheduled`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  表示容器组（pod）已被调度到某个节点。  | 
|  `pod_status_unknown`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  表示无法获取容器组（pod）的状态。  | 
|  `pod_status_pending`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  表示集群已接受容器组（pod），但其中一个或多个容器尚未准备就绪。  | 
|  `pod_status_succeeded`   |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  表示容器组（pod）中的所有容器都已成功终止并且不会重启。  | 
|  `pod_number_of_containers`   |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  报告容器组（pod）规范中定义的容器数量。  | 
|  `pod_number_of_running_containers`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  报告容器组（pod）中当前处于 `Running` 状态的容器数量。  | 
|  `pod_container_status_terminated`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  报告容器组（pod）中处于 `Terminated` 状态的容器数量。  | 
|  `pod_container_status_running`   |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  报告容器组（pod）中处于 `Running` 状态的容器数量。  | 
|  `pod_container_status_waiting`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  报告容器组（pod）中处于 `Waiting` 状态的容器数量。  | 
|  `pod_container_status_waiting_reason_crash_loop_back_off`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  报告容器组（pod）中因 `CrashLoopBackOff` 错误而处于待处理状态的容器数量，该错误会导致容器反复启动失败。  | 
|  `pod_container_status_waiting_reason_create_container_config_error`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  报告容器组（pod）中因 `CreateContainerConfigError` 而处于待处理状态的容器数量。这是因为创建容器配置时出错。  | 
|  `pod_container_status_waiting_reason_create_container_error`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  报告容器组（pod）中由于创建容器时出错而因 `CreateContainerError` 处于待处理状态的容器数量。  | 
|  `pod_container_status_waiting_reason_image_pull_error`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  报告容器组（pod）中因 `ErrImagePull`、`ImagePullBackOff` 或 `InvalidImageName` 而处于待处理状态的容器数量。这些情况是由于拉取容器映像时出错造成的。  | 
|  `pod_container_status_waiting_reason_start_error`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  报告容器组（pod）中由于启动容器时出错而因 `StartError` 处于待处理状态的容器数量。  | 
|  `pod_container_status_terminated_reason_oom_killed`   |  `ContainerName`, `FullPodName`, `PodName`, `Namespace`, `ClusterName` `ContainerName`, `PodName`, `Namespace`, `ClusterName` `ClusterName`  |  表示容器组 (pod) 因超过内存限制而被终止。仅当发生此问题时才会显示此指标。  | 
|  `pod_interface_network_rx_dropped`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  容器组（pod）的网络接口接收并随后丢弃的数据包数量。  | 
|  `pod_interface_network_tx_dropped`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  本应传输但为容器组（pod）丢弃的数据包数量。  | 
| `pod_memory_working_set` |  `ClusterName` `ClusterName`, `Namespace`, `PodName` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  | 容器组 (pod) 当前正在使用的内存（以字节为单位）。 | 
| `pod_cpu_usage_total` |  `ClusterName` `ClusterName`, `Namespace`, `PodName` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  | 容器组 (pod) 使用的 CPU 单元的数量。 | 
|  `container_cpu_utilization`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName`, `ContainerName` `PodName`, `Namespace`, `ClusterName`, `ContainerName`, `FullPodName`  |  容器所使用的 CPU 单元的百分比。 公式：`container_cpu_usage_total / node_cpu_limit`  `container_cpu_utilization` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `container_cpu_utilization_over_container_limit`   |  `ClusterName` `PodName`, `Namespace`, `ClusterName`, `ContainerName` `PodName`, `Namespace`, `ClusterName`, `ContainerName`, `FullPodName`  |  相对于容器限制，容器所使用的 CPU 单元的百分比。如果容器没有定义 CPU 限制，则不会显示此指标。 公式：`container_cpu_usage_total / container_cpu_limit`  `container_cpu_utilization_over_container_limit` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `container_memory_utilization`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName`, `ContainerName` `PodName`, `Namespace`, `ClusterName`, `ContainerName`, `FullPodName`  |  容器所使用的内存单元的百分比。 公式：`container_memory_working_set / node_memory_limit`  `container_memory_utilization` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `container_memory_utilization_over_container_limit`    |  `ClusterName` `PodName`, `Namespace`, `ClusterName`, `ContainerName` `PodName`, `Namespace`, `ClusterName`, `ContainerName`, `FullPodName`  |  相对于容器限制，容器所使用的内存单元的百分比。如果容器没有定义内存限制，则不会显示此指标。 公式：`container_memory_working_set / container_memory_limit`  `container_memory_utilization_over_container_limit` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `container_memory_failures_total`  其在 Windows 上不可用。  |  `ClusterName` `PodName`, `Namespace`, `ClusterName`, `ContainerName` `PodName`, `Namespace`, `ClusterName`, `ContainerName`, `FullPodName`  |  容器遇到的内存分配失败的次数。  | 
|  `pod_number_of_container_restarts`  |  PodName、`Namespace`、`ClusterName`  |  一个 pod 中容器重新启动的总次数。  | 
|  `service_number_of_running_pods`  |  Service、`Namespace`、`ClusterName` `ClusterName`  |  运行集群中的服务的 pod 的数量。  | 
|  `replicas_desired`   |  `ClusterName` `PodName`, `Namespace`, `ClusterName`  |  工作负载规范中定义的工作负载所需的容器组（pod）数量。  | 
|  `replicas_ready`   |  `ClusterName` `PodName`, `Namespace`, `ClusterName`  |  已达到就绪状态的工作负载的容器组（pod）数量。  | 
|  `status_replicas_available`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName`  |  工作负载可用的容器组（pod）数量。当容器组（pod）已就绪工作负载规范中定义的 `minReadySeconds` 时，容器组（pod）才可用。  | 
|  `status_replicas_unavailable`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName`  |  工作负载不可用的容器组（pod）数量。当容器组（pod）已就绪工作负载规范中定义的 `minReadySeconds` 时，容器组（pod）才可用。如果容器组（pod）不符合此标准，则它们不可用。  | 
|  `apiserver_storage_objects`  |  `ClusterName` `ClusterName`, `resource`  |  上次检查时存储在 etcd 中的对象数量。  | 
|  `apiserver_storage_db_total_size_in_bytes`  |  `ClusterName` `ClusterName`, `endpoint`  |  物理分配的存储数据库文件的总大小（以字节为单位）。此指标是实验性的，在将来的 Kubernetes 版本中可能会发生变化。 单位：字节 有意义的统计数据：总和、平均值、最小值、最大值  | 
|  `apiserver_request_total`  |  `ClusterName` `ClusterName`, `code`, `verb`  |  向 Kubernetes API 服务器发出的 API 请求总数。  | 
|  `apiserver_request_duration_seconds`  |  `ClusterName` `ClusterName`, `verb`  |  向 Kubernetes API 服务器发出的 API 请求的响应延迟。  | 
|  `apiserver_admission_controller_admission_duration_seconds`  |  `ClusterName` `ClusterName`, `operation`  |  准入控制器延迟（以秒为单位）。准入控制器是拦截向 Kubernetes API 服务器发出的请求的代码。  | 
|  `rest_client_request_duration_seconds`   |  `ClusterName` `ClusterName`, `operation`  |  客户端在调用 Kubernetes API 服务器时遇到的响应延迟。此指标是实验性的，在将来的 Kubernetes 版本中可能会发生变化。  | 
|  `rest_client_requests_total`   |  `ClusterName` `ClusterName`, `code`, `method`  |  客户端向 Kubernetes API 服务器发出的 API 请求总数。此指标是实验性的，在将来的 Kubernetes 版本中可能会发生变化。  | 
|  `etcd_request_duration_seconds`   |  `ClusterName` `ClusterName`, `operation`  |  对 Etcd 的 API 调用的响应延迟。此指标是实验性的，在将来的 Kubernetes 版本中可能会发生变化。  | 
|  `apiserver_storage_size_bytes`   |  `ClusterName` `ClusterName`, `endpoint`  |  物理分配的存储数据库文件的大小（以字节为单位）。此指标是实验性的，在将来的 Kubernetes 版本中可能会发生变化。  | 
|  `apiserver_longrunning_requests`  |  `ClusterName` `ClusterName`, `resource`  |  向 Kubernetes API 服务器发出的长时间运行的活跃请求数。  | 
|  `apiserver_current_inflight_requests`  |  `ClusterName` `ClusterName`, `request_kind`  |  Kubernetes API 服务器正在处理的请求数。  | 
|  `apiserver_admission_webhook_admission_duration_seconds`  |  `ClusterName` `ClusterName`, `name`  |  准入 Webhook 延迟（以秒为单位）。准入 Webhook 是 HTTP 回调，用于接收准入请求并对其进行一些处理。  | 
|  `apiserver_admission_step_admission_duration_seconds`   |  `ClusterName` `ClusterName`, `operation`  |  准入子步骤延迟（以秒为单位）。  | 
|  `apiserver_requested_deprecated_apis`   |  `ClusterName` `ClusterName`, `group`  |  向 Kubernetes API 服务器上已弃用的 API 发出的请求数。  | 
|  `apiserver_request_total_5xx`  |  `ClusterName` `ClusterName`, `code`, `verb`  |  向 Kubernetes API 服务器发出的请求数，这些请求以 5XX HTTP 响应代码为响应。  | 
|  `apiserver_storage_list_duration_seconds`   |  `ClusterName` `ClusterName`, `resource`  |  列出 Etc 中的对象的响应延迟。此指标是实验性的，在将来的 Kubernetes 版本中可能会发生变化。  | 
|  `apiserver_flowcontrol_request_concurrency_limit`   |  `ClusterName` `ClusterName`, `priority_level`  |  API 优先级和公平性子系统中当前正在执行的请求使用的线程数。  | 
|  `apiserver_flowcontrol_rejected_requests_total`   |  `ClusterName` `ClusterName`, `reason`  |  API 优先级和公平性子系统拒绝的请求数。此指标是实验性的，在将来的 Kubernetes 版本中可能会发生变化。  | 
|  `apiserver_current_inqueue_requests`   |  `ClusterName` `ClusterName`, `request_kind`  |  Kubernetes API 服务器排队的请求数。此指标是实验性的，在将来的 Kubernetes 版本中可能会发生变化。  | 

## NVIDIA GPU 指标
<a name="Container-Insights-metrics-EKS-GPU"></a>

从 CloudWatch 代理版本 `1.300034.0` 开始，针对 Amazon EKS 增强了可观测性的 Container Insights 默认从 EKS 工作负载收集 NVIDIA GPU 指标。必须使用 CloudWatch Observability EKS 附加组件版本 `v1.3.0-eksbuild.1` 或更高版本安装 CloudWatch 代理。有关更多信息，请参阅 [使用 Amazon CloudWatch Observability EKS 附加组件或 Helm 图表安装 CloudWatch 代理](install-CloudWatch-Observability-EKS-addon.md)。本节的表中列出了这些会被收集的 NVIDIA GPU 指标。

要让 Container Insights 收集 NVIDIA GPU 指标，必须满足以下先决条件：
+ 必须将针对 Amazon EKS 增强了可观测性的 Container Insights 与 Amazon CloudWatch Observability EKS 附加组件版本 `v1.3.0-eksbuild.1` 或更高版本结合使用。
+ 集群中必须安装[适用于 Kubernetes 的 NVIDIA 设备插件](https://github.com/NVIDIA/k8s-device-plugin)。
+ 集群的节点上必须安装 [NVIDIA 容器工具包](https://github.com/NVIDIA/nvidia-container-toolkit)。例如，使用必要的组件构建 Amazon EKS 优化版加速型 AMI。

您可以将起始 CloudWatch 代理配置文件中的 `accelerated_compute_metrics` 选项设置为 `false`，从而选择不收集 NVIDIA GPU 指标。有关更多信息和选择不收集配置的示例，请参阅 [（可选）其他配置](install-CloudWatch-Observability-EKS-addon.md#install-CloudWatch-Observability-EKS-addon-configuration)。


| 指标名称 | Dimensions | 说明 | 
| --- | --- | --- | 
|  `container_gpu_memory_total` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `GpuDevice`  |  分配给容器的 GPU 上的帧缓冲区总大小（以字节为单位）。  | 
|  `container_gpu_memory_used` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `GpuDevice`  |  分配给容器的 GPU 上使用的帧缓冲区字节数。  | 
|  `container_gpu_memory_utilization` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `GpuDevice`  |  分配给容器的 GPU 已使用的帧缓冲区百分比。  | 
|  `container_gpu_power_draw` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `GpuDevice`  |  分配给容器的 GPU 的功耗（以瓦特为单位）。  | 
|  `container_gpu_temperature` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `GpuDevice`  |  分配给容器的 GPU 的温度（以摄氏度为单位）。  | 
|  `container_gpu_utilization` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `GpuDevice`  |  分配给容器的 GPU 的利用率百分比。  | 
|  `container_gpu_tensor_core_utilization` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `GpuDevice`  |  分配给容器的 GPU 张量核心利用率百分比。  | 
|  `node_gpu_memory_total` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceId`, `InstanceType`, `NodeName`, `GpuDevice`  |  分配给节点的 GPU 上的帧缓冲区总大小（以字节为单位）。  | 
|  `node_gpu_memory_used` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceId`, `InstanceType`, `NodeName`, `GpuDevice`  |  分配给节点的 GPU 上使用的帧缓冲区字节数。  | 
|  `node_gpu_memory_utilization` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceId`, `InstanceType`, `NodeName`, `GpuDevice`  |  分配给节点的 GPU 上使用的帧缓冲区百分比。  | 
|  `node_gpu_power_draw` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceId`, `InstanceType`, `NodeName`, `GpuDevice`  |  分配给节点的 GPU 的功耗（以瓦特为单位）。  | 
|  `node_gpu_temperature` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceId`, `InstanceType`, `NodeName`, `GpuDevice`  |  分配给节点的 GPU 的温度（以摄氏度为单位）。  | 
|  `node_gpu_utilization` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceId`, `InstanceType`, `NodeName`, `GpuDevice`  |  分配给节点的 GPU 的利用率百分比。  | 
|  `node_gpu_tensor_core_utilization` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceId`, `InstanceType`, `NodeName`, `GpuDevice`  |  分配给节点的 GPU 张量核心利用率百分比。  | 
|  `pod_gpu_memory_total` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`. `GpuDevice`  |  分配给 Pod 的 GPU 上的帧缓冲区总大小（以字节为单位）。  | 
|  `pod_gpu_memory_used` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`. `GpuDevice`  |  分配给 Pod 的 GPU 上使用的帧缓冲区字节数。  | 
|  `pod_gpu_memory_utilization` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`. `GpuDevice`  |  分配给 Pod 的 GPU 上使用的帧缓冲区百分比。  | 
|  `pod_gpu_power_draw` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`. `GpuDevice`  |  分配给 Pod 的 GPU 的功耗（以瓦特为单位）。  | 
|  `pod_gpu_temperature` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`. `GpuDevice`  |  分配给容器组 (pod) 的 GPU 的温度（以摄氏度为单位）。  | 
|  `pod_gpu_utilization` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `GpuDevice`  |  分配给 Pod 的 GPU 的利用率百分比。  | 
|  `pod_gpu_tensor_core_utilization` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `GpuDevice`  |  分配给容器组（pod）的 GPU 张量核心利用率百分比。  | 

### GPU 精细化监控
<a name="Container-Insights-detailed-GPU-monitoring"></a>

从 CloudWatch 代理 `1.300062.0` 版本开始，适用于 Amazon EKS 的可观测性增强型 Container Insights 支持亚分钟级收集间隔的 GPU 精细化监控。该功能填补了短时机器学习推理工作负载的监控空白；此类工作负载在标准收集间隔下可能被完全遗漏。必须使用 CloudWatch Observability EKS 附加组件版本 `v4.7.0-eksbuild.1` 或更高版本安装 CloudWatch 代理。有关更多信息，请参阅 [使用 Amazon CloudWatch Observability EKS 附加组件或 Helm 图表安装 CloudWatch 代理](install-CloudWatch-Observability-EKS-addon.md)。

默认情况下，GPU 指标的收集与上报间隔为 60 秒。启用精细化监控后，CloudWatch 代理将以亚分钟级间隔（最小 1 秒）收集 GPU 指标，但指标仍以 1 分钟为间隔上报至 CloudWatch。不过，您可对每个 1 分钟周期内的亚分钟级数据点进行统计聚合查询（如最小值、最大值及 P90 等百分位数），以此获取精准的 GPU 利用率数据，实现更优的资源优化。

#### 配置
<a name="Container-Insights-detailed-GPU-monitoring-configuration"></a>

如需启用 GPU 精细化监控，需更新 CloudWatch 代理配置，在 `kubernetes` 配置段中添加 `accelerated_compute_gpu_metrics_collection_interval` 参数，配置示例如下。

```
{  
    "logs": {  
        "metrics_collected": {  
            "kubernetes": {  
                "cluster_name": "MyCluster",  
                "enhanced_container_insights": true,  
                "accelerated_compute_metrics": true,  
                "accelerated_compute_gpu_metrics_collection_interval": 1  
            }  
        }  
    }  
}
```

`accelerated_compute_gpu_metrics_collection_interval` 参数的取值单位为秒，最小值为 1 秒。将此参数设位 `1` 时，即可启用 1 秒的收集间隔。若未指定此参数，则将采用默认的 60 秒采集间隔。

有关完整配置说明，请参阅[设置 CloudWatch 代理以收集集群指标](Container-Insights-setup-metrics.md)。

## AWS Trainium 和 AWS Inferentia 的 AWS Neuron 指标
<a name="Container-Insights-metrics-EKS-Neuron"></a>

从 CloudWatch 代理版本 `1.300036.0` 开始，针对 Amazon EKS 增强了可观测性的 Container Insights 默认从 AWS Trainium 和 AWS Inferentia 加速器收集加速计算指标。必须使用 CloudWatch Observability EKS 附加组件版本 `v1.5.0-eksbuild.1` 或更高版本安装 CloudWatch 代理。有关附加组件的更多信息，请参阅 [使用 Amazon CloudWatch Observability EKS 附加组件或 Helm 图表安装 CloudWatch 代理](install-CloudWatch-Observability-EKS-addon.md)。有关 AWS Trainium 的更多信息，请参阅 [AWS Trainium](https://aws.amazon.com/machine-learning/trainium/)。有关 AWS Inferentia 的更多信息，请参阅 [AWS Inferentia](https://aws.amazon.com/machine-learning/inferentia/)。

要让 Container Insights 收集 AWS Neuron 指标，必须满足以下先决条件：
+ 必须将针对 Amazon EKS 增强了可观测性的 Container Insights 与 Amazon CloudWatch Observability EKS 附加组件版本 `v1.5.0-eksbuild.1` 或更高版本结合使用。
+ [Neuron 驱动程序](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/general/setup/neuron-setup/pytorch/neuronx/ubuntu/torch-neuronx-ubuntu22.html#setup-torch-neuronx-ubuntu22)必须安装在集群的节点上。
+ [Neuron 设备插件](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/containers/kubernetes-getting-started.html)必须安装在集群上。例如，使用必要的组件构建 Amazon EKS 优化版加速型 AMI。

本节的表中列出了将收集的指标。这些指标是为 AWS Trainium、AWS Inferentia 和 AWS Inferentia2 收集的。

CloudWatch 代理从 [Neuron Monitor](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/tools/neuron-sys-tools/neuron-monitor-user-guide.html) 收集这些指标，并进行必要的 Kubernetes 资源关联，以在容器组（pod）和容器级别提供指标


| 指标名称 | Dimensions | 说明 | 
| --- | --- | --- | 
|  `container_neuroncore_utilization` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `NeuronDevice`, `NeuronCore`  |  分配给容器的 NeuronCore 在捕获期内的 NeuronCore 利用率。 单位：百分比  | 
|  `container_neuroncore_memory_usage_constants` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `NeuronDevice`, `NeuronCore`  |  分配给容器的 NeuronCore 在训练期间用于常量的设备内存量（或推理期间的权重）。 单位：字节  | 
|  `container_neuroncore_memory_usage_model_code` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `NeuronDevice`, `NeuronCore`  |  分配给容器的 NeuronCore 用于模型可执行代码的设备内存量。 单位：字节  | 
|  `container_neuroncore_memory_usage_model_shared_scratchpad` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `NeuronDevice`, `NeuronCore`  |  分配给容器的 NeuronCore 用于模型共享暂存器的设备内存量。此内存区域保留用于模型。 单位：字节  | 
|  `container_neuroncore_memory_usage_runtime_memory` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `NeuronDevice`, `NeuronCore`  |  分配给容器的 NeuronCore 用于 Neuron 运行时的设备内存量。 单位：字节  | 
|  `container_neuroncore_memory_usage_tensors` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `NeuronDevice`, `NeuronCore`  |  分配给容器的 NeuronCore 用于张量的设备内存量。 单位：字节  | 
|  `container_neuroncore_memory_usage_total` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `NeuronDevice`, `NeuronCore`  |  分配给容器的 NeuronCore 使用的内存总量。 单位：字节  | 
|  `container_neurondevice_hw_ecc_events_total` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `NeuronDevice`  |  节点上 Neuron 设备的片上 SRAM 和设备内存的已校正和未校正 ECC 事件数。 单位：个  | 
|  `pod_neuroncore_utilization` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `NeuronDevice`, `NeuronCore`  |  分配给容器组（pod）的 NeuronCore 在捕获期内的 NeuronCore 利用率。 单位：百分比  | 
|  `pod_neuroncore_memory_usage_constants` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `NeuronDevice`, `NeuronCore`  |  分配给容器组（pod）的 NeuronCore 在训练期间用于常量的设备内存量（或推理期间的权重）。 单位：字节  | 
|  `pod_neuroncore_memory_usage_model_code` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `NeuronDevice`, `NeuronCore`  |  分配给容器组（pod）的 NeuronCore 用于模型可执行代码的设备内存量。 单位：字节  | 
|  `pod_neuroncore_memory_usage_model_shared_scratchpad` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `NeuronDevice`, `NeuronCore`  |  分配给容器组（pod）的 NeuronCore 用于模型共享暂存器的设备内存量。此内存区域保留用于模型。 单位：字节  | 
|  `pod_neuroncore_memory_usage_runtime_memory` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `NeuronDevice`, `NeuronCore`  |  分配给容器组（pod）的 NeuronCore 用于 Neuron 运行时的设备内存量。 单位：字节  | 
|  `pod_neuroncore_memory_usage_tensors` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `NeuronDevice`, `NeuronCore`  |  分配给容器组（pod）的 NeuronCore 用于张量的设备内存量。 单位：字节  | 
|  `pod_neuroncore_memory_usage_total` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `NeuronDevice`, `NeuronCore`  |  分配给容器组（pod）的 NeuronCore 使用的内存总量。 单位：字节  | 
|  `pod_neurondevice_hw_ecc_events_total` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `NeuronDevice`  |  分配给容器组（pod）的 Neuron 设备的片上 SRAM 和设备内存的已校正和未校正 ECC 事件数。 单位：字节  | 
|  `node_neuroncore_utilization` |  `ClusterName` `ClusterName`, `UltraServer` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceType`, `InstanceId`, `NodeName`, `NeuronDevice`, `NeuronCore`  |  分配给节点的 NeuronCore 在捕获期内的 NeuronCore 利用率。 单位：百分比  | 
|  `node_neuroncore_memory_usage_constants` |  `ClusterName` `ClusterName`, `UltraServer` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceType`, `InstanceId`, `NodeName`, `NeuronDevice`, `NeuronCore`  |  分配给节点的 NeuronCore 在训练期间用于常量的设备内存量（或推理期间的权重）。 单位：字节  | 
|  `node_neuroncore_memory_usage_model_code` |  `ClusterName` `ClusterName`, `UltraServer` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceType`, `InstanceId`, `NodeName`, `NeuronDevice`, `NeuronCore`  |  分配给节点的 NeuronCore 用于模型可执行代码的设备内存量。 单位：字节  | 
|  `node_neuroncore_memory_usage_model_shared_scratchpad` |  `ClusterName` `ClusterName`, `UltraServer` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceType`, `InstanceId`, `NodeName`, `NeuronDevice`, `NeuronCore`  |  分配给节点的 NeuronCore 用于模型共享暂存器的设备内存量。这保留用于模型的内存区域。 单位：字节  | 
|  `node_neuroncore_memory_usage_runtime_memory` |  `ClusterName` `ClusterName`, `UltraServer` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceType`, `InstanceId`, `NodeName`, `NeuronDevice`, `NeuronCore`  |  分配给节点的 NeuronCore 用于 Neuron 运行时的设备内存量。 单位：字节  | 
|  `node_neuroncore_memory_usage_tensors` |  `ClusterName` `ClusterName`, `UltraServer` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceType`, `InstanceId`, `NodeName`, `NeuronDevice`, `NeuronCore`  |  分配给节点的 NeuronCore 用于张量的设备内存量。 单位：字节  | 
|  `node_neuroncore_memory_usage_total` |  `ClusterName` `ClusterName`, `UltraServer` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceType`, `InstanceId`, `NodeName`, `NeuronDevice`, `NeuronCore`  |  分配给节点的 NeuronCore 使用的内存总量。 单位：字节  | 
|  `node_neuron_execution_errors_total` |  `ClusterName` `ClusterName`, `UltraServer` `ClusterName`, `InstanceId`, `NodeName`  |  节点上执行错误的总数。这是由 CloudWatch 代理通过汇总以下类型的错误来计算的：`generic`、`numerical`、`transient`、`model`、`runtime` 和 `hardware` 单位：个  | 
|  `node_neurondevice_runtime_memory_used_bytes` |  `ClusterName` `ClusterName`, `UltraServer` `ClusterName`, `InstanceId`, `NodeName`  |  节点上 Neuron 设备内存使用总量（以字节为单位）。 单位：字节  | 
| `node_neuron_execution_latency` |  `ClusterName` `ClusterName`, `UltraServer` `ClusterName`, `InstanceId`, `NodeName`  |  Neuron 运行时测量的节点上执行的延迟（以秒为单位）。 单位：秒  | 
| `node_neurondevice_hw_ecc_events_total` |  `ClusterName` `ClusterName`, `UltraServer` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceId`, `NodeName`, `NeuronDevice`  |  节点上 Neuron 设备的片上 SRAM 和设备内存的已校正和未校正 ECC 事件数。 单位：个  | 

## AWS Elastic Fabric Adapter（EFA）指标
<a name="Container-Insights-metrics-EFA"></a>

从 CloudWatch 代理版本 `1.300037.0` 开始，针对 Amazon EKS 增强了可观测性的 Container Insights 从 Linux 实例上的 Amazon EKS 集群收集 AWS Elastic Fabric Adapter（EFA）指标。必须使用 CloudWatch Observability EKS 附加组件版本 `v1.5.2-eksbuild.1` 或更高版本安装 CloudWatch 代理。有关附加组件的更多信息，请参阅 [使用 Amazon CloudWatch Observability EKS 附加组件或 Helm 图表安装 CloudWatch 代理](install-CloudWatch-Observability-EKS-addon.md)。有关 AWS Elastic Fabric Adapter（EFA）的更多信息，请参阅 [Elastic Fabric Adapter](https://aws.amazon.com/hpc/efa/)。

要让 Container Insights 收集 AWS Elastic Fabric Adapter 指标，必须满足以下先决条件：
+ 必须将针对 Amazon EKS 增强了可观测性的 Container Insights 与 Amazon CloudWatch Observability EKS 附加组件版本 `v1.5.2-eksbuild.1` 或更高版本结合使用。
+ EFA 设备插件必须安装在集群上。有关更多信息，请参阅 GitHub 上的 [aws-efa-k8s-device-plugin](https://github.com/aws/eks-charts/tree/master/stable/aws-efa-k8s-device-plugin)。

下表中列出了收集的指标。


| 指标名称 | Dimensions | 说明 | 
| --- | --- | --- | 
|  `container_efa_rx_bytes` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `NetworkInterfaceId`   |  分配给容器的 EFA 设备每秒接收的字节数。 单位：字节/秒  | 
|  `container_efa_tx_bytes` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `NetworkInterfaceId`   |  分配给容器的 EFA 设备每秒传输的字节数。 单位：字节/秒  | 
|  `container_efa_rx_dropped` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `NetworkInterfaceId`   |  分配给容器的 EFA 设备接收然后丢弃的数据包数量。 单位：计数/秒  | 
|  `container_efa_rdma_read_bytes` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `NetworkInterfaceId`   |  分配给容器的 EFA 设备使用远程直接内存访问读取操作每秒接收的字节数。 单位：字节/秒  | 
|  `container_efa_rdma_write_bytes` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `NetworkInterfaceId`   |  分配给容器的 EFA 设备使用远程直接内存访问读取操作每秒传输的字节数。 单位：字节/秒  | 
|  `container_efa_rdma_write_recv_bytes` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `NetworkInterfaceId`   |  分配给容器的 EFA 设备在远程直接内存访问写入操作期间每秒接收的字节数。 单位：字节/秒  | 
|  `pod_efa_rx_bytes` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `NetworkInterfaceId`  |  分配给容器组（pod）的 EFA 设备每秒接收的字节数。 单位：字节/秒  | 
|  `pod_efa_tx_bytes` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `NetworkInterfaceId`  |  分配给容器组（pod）的 EFA 设备每秒传输的字节数。 单位：字节/秒  | 
|  `pod_efa_rx_dropped` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `NetworkInterfaceId`  |  分配给容器组（pod）的 EFA 设备接收然后丢弃的数据包数量。 单位：计数/秒  | 
|  `pod_efa_rdma_read_bytes` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `NetworkInterfaceId`  |  分配给容器组（pod）的 EFA 设备使用远程直接内存访问读取操作每秒接收的字节数。 单位：字节/秒  | 
|  `pod_efa_rdma_write_bytes` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `NetworkInterfaceId`  |  分配给容器组（pod）的 EFA 设备使用远程直接内存访问读取操作每秒传输的字节数。 单位：字节/秒  | 
|  `pod_efa_rdma_write_recv_bytes` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `NetworkInterfaceId`  |  分配给容器组（pod）的 EFA 设备在远程直接内存访问写入操作期间每秒接收的字节数。 单位：字节/秒  | 
|  `node_efa_rx_bytes` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceId`, `InstanceType`, `NodeName`, `NetworkInterfaceId`  |  分配给节点的 EFA 设备每秒接收的字节数。 单位：字节/秒  | 
|  `node_efa_tx_bytes` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceId`, `InstanceType`, `NodeName`, `NetworkInterfaceId`  |  分配给节点的 EFA 设备每秒传输的字节数。 单位：字节/秒  | 
|  `node_efa_rx_dropped` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceId`, `InstanceType`, `NodeName`, `NetworkInterfaceId`  |  分配给节点的 EFA 设备接收然后丢弃的数据包数量。 单位：计数/秒  | 
|  `node_efa_rdma_read_bytes` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceId`, `InstanceType`, `NodeName`, `NetworkInterfaceId`  |  分配给节点的 EFA 设备使用远程直接内存访问读取操作每秒接收的字节数。 单位：字节/秒  | 
|  `node_efa_rdma_write_bytes` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceId`, `InstanceType`, `NodeName`, `NetworkInterfaceId`  |  分配给容器组（pod）的 EFA 设备使用远程直接内存访问读取操作每秒传输的字节数。 单位：字节/秒  | 
|  `node_efa_rdma_write_recv_bytes` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceId`, `InstanceType`, `NodeName`, `NetworkInterfaceId`  |  分配给节点的 EFA 设备在远程直接内存访问写入操作期间每秒接收的字节数。 单位：字节/秒  | 

## Amazon SageMaker AI HyperPod 指标
<a name="Container-Insights-metrics-Sagemaker-HyperPod"></a>

从 CloudWatch Observability EKS 附加组件的 `v2.0.1-eksbuild.1` 版本开始，具有 Amazon EKS 增强可观测性的 Container Insights 会自动从 Amazon EKS 集群收集 Amazon SageMaker AI HyperPod 指标。有关附加组件的更多信息，请参阅 [使用 Amazon CloudWatch Observability EKS 附加组件或 Helm 图表安装 CloudWatch 代理](install-CloudWatch-Observability-EKS-addon.md)。有关 Amazon SageMaker AI HyperPod 的更多信息，请参阅 [Amazon SageMaker AI HyperPod](https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-hyperpod-eks.html)。

下表中列出了收集的指标。


| 指标名称 | Dimensions | 说明 | 
| --- | --- | --- | 
|  `hyperpod_node_health_status_unschedulable` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`  |  表示节点是否被 `Unschedulable` HyperPod 标记为 Amazon SageMaker AI。这意味着该节点正在运行深度运行状况检查，无法用于运行的工作负载。 单位：个  | 
|  `hyperpod_node_health_status_schedulable` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`  |  表示节点是否被 `Schedulable` HyperPod 标记为 Amazon SageMaker AI。这意味着该节点已通过基本运行状况检查或深度运行状况检查，可用于运行的工作负载。 单位：个  | 
|  `hyperpod_node_health_status_unschedulable_pending_replacement` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`  |  表示节点是否被 HyperPod 标记为 `UnschedulablePendingReplacement`。这意味着该节点未通过深度运行状况检查或运行状况监测代理检查，需要替换。 如果启用了自动节点恢复，该节点将自动被 Amazon SageMaker AI HyperPod 替换。 单位：个  | 
|  `hyperpod_node_health_status_unschedulable_pending_reboot` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`  |  表示节点是否被 `UnschedulablePendingReboot` HyperPod 标记为 Amazon SageMaker AI。这意味着该节点正在运行深度运行状况检查，需要重启。 如果启用了自动节点恢复，Amazon SageMaker AI HyperPod 将自动重启该节点。 单位：个  | 

## Amazon EBS NVMe 驱动指标
<a name="Container-Insights-metrics-EBS"></a>

从 CloudWatch 代理版本 ` 1.300056.0` 开始，针对 Amazon EKS 增强了可观测性的 Container Insights 从 Linux 实例上的 Amazon EKS 集群自动收集 Amazon EBS NVMe 驱动指标。必须使用 CloudWatch Observability Amazon EKS 附加组件版本 `4.1.0` 或更高版本安装 CloudWatch 代理。有关附加组件的更多信息，请参阅 [使用 Amazon CloudWatch Observability EKS 附加组件或 Helm 图表安装 CloudWatch 代理](install-CloudWatch-Observability-EKS-addon.md)。如需进一步了解 Amazon EBS，请参阅 [Amazon EBS 详细性能统计数据](https://docs.aws.amazon.com/ebs/latest/userguide/nvme-detailed-performance-stats.html)。

要让 Container Insights 收集 Amazon EBS NVMe 驱动指标，必须满足以下先决条件：
+ 必须将针对 Amazon EKS 增强了可观测性的 Container Insights 与 CloudWatch Observability Amazon EKS 附加组件版本 `4.1.0` 或更高版本结合使用。
+ 必须在已启用指标的集群上安装 EBS CSI 驱动程序 `1.42.0` 插件或 Helm 图表。
  + 若要在使用 Amazon EBS CSI 驱动程序插件时启用指标功能，请在创建或更新该插件时配置以下选项。`--configuration-values '{ "node": { "enableMetrics": true } }'`
  + 若要在使用 Helm 图表时启用指标功能，请在创建或更新该插件时配置以下选项。`--set node.enableMetrics=true`

下表中列出了收集的指标。


| 指标名称 | Dimensions | 说明 | 
| --- | --- | --- | 
|  `node_diskio_ebs_total_read_ops` |  `ClusterName` `ClusterName`, `NodeName`, `InstanceId` `ClusterName`, `NodeName`, `InstanceId` `VolumeId`  | 已完成的读取操作总数。 | 
|  `node_diskio_ebs_total_write_ops` |  `ClusterName` `ClusterName`, `NodeName`, `InstanceId` `ClusterName`, `NodeName`, `InstanceId` `VolumeId`  | 已完成的写入操作总数。 | 
|  `node_diskio_ebs_total_read_bytes` |  `ClusterName` `ClusterName`, `NodeName`, `InstanceId` `ClusterName`, `NodeName`, `InstanceId` `VolumeId`  | 传输的读取字节总数。 | 
|  `node_diskio_ebs_total_write_bytes` |  `ClusterName` `ClusterName`, `NodeName`, `InstanceId` `ClusterName`, `NodeName`, `InstanceId` `VolumeId`  | 传输的写入字节总数。 | 
|  `node_diskio_ebs_total_read_time` |  `ClusterName` `ClusterName`, `NodeName`, `InstanceId` `ClusterName`, `NodeName`, `InstanceId` `VolumeId`  | 所有已完成读取操作的总耗时（单位：微秒）。 | 
|  `node_diskio_ebs_total_write_time` |  `ClusterName` `ClusterName`, `NodeName`, `InstanceId` `ClusterName`, `NodeName`, `InstanceId` `VolumeId`  | 所有已完成写入操作的总耗时（单位：微秒）。 | 
|  `node_diskio_ebs_volume_performance_exceeded_iops` |  `ClusterName` `ClusterName`, `NodeName`, `InstanceId` `ClusterName`, `NodeName`, `InstanceId` `VolumeId`  | IOPS 需求超出存储卷预调配 IOPS 性能的总时长（单位：微秒）。 | 
|  `node_diskio_ebs_volume_performance_exceeded_tp` |  `ClusterName` `ClusterName`, `NodeName`, `InstanceId` `ClusterName`, `NodeName`, `InstanceId` `VolumeId`  | 吞吐量需求超出存储卷预配置吞吐量性能的总时长（单位：微秒）。 | 
|  `node_diskio_ebs_ec2_instance_performance_exceeded_iops` |  `ClusterName` `ClusterName`, `NodeName`, `InstanceId` `ClusterName`, `NodeName`, `InstanceId` `VolumeId`  | EBS 卷超出所附加的 Amazon EC2 实例最大 IOPS 性能的总时长（单位：微秒）。 | 
|  `node_diskio_ebs_ec2_instance_performance_exceeded_tp` |  `ClusterName` `ClusterName`, `NodeName`, `InstanceId` `ClusterName`, `NodeName`, `InstanceId` `VolumeId`  | EBS 卷超出所附加的 Amazon EC2 实例最大吞吐量性能的总时长（单位：微秒）。 | 
|  `node_diskio_ebs_volume_queue_length` |  `ClusterName` `ClusterName`, `NodeName`, `InstanceId` `ClusterName`, `NodeName`, `InstanceId` `VolumeId`  | 待完成的读取与写入操作的数量。 | 

# Amazon EKS 和 Kubernetes Container Insights 指标
<a name="Container-Insights-metrics-EKS"></a>

下表列出了 Container Insights 为 Amazon EKS 和 Kubernetes 收集的指标和维度。这些指标位于 `ContainerInsights` 命名空间中。有关更多信息，请参阅 [指标](cloudwatch_concepts.md#Metric)。

如果您在控制台中未看到任何 Container Insights 指标，请确保已完成 Container Insights 的设置。在完全设置 Container Insights 之前，指标不会显示。有关更多信息，请参阅 [设置 Container Insights](deploy-container-insights.md)。


| 指标名称 | Dimensions | 说明 | 
| --- | --- | --- | 
|  `cluster_failed_node_count`  |  `ClusterName`  |  集群中失败的工作线程节点的数目。如果节点遭受任何*节点条件*的影响，则该节点被视为失败。有关更多信息，请参阅 Kubernetes 文档中的[条件](https://kubernetes.io/docs/concepts/architecture/nodes/#condition)。  | 
|  `cluster_node_count`  |  `ClusterName`  |  集群中工作线程节点的总数。  | 
|  `namespace_number_of_running_pods`  |  `Namespace` `ClusterName` `ClusterName`  |  您使用的维度所指定的资源中每个命名空间运行的 pod 的数目。  | 
|  `node_cpu_limit`  |  `ClusterName`   |  可以分配给此集群中单个节点的 CPU 单元的最大数目。  | 
|  `node_cpu_reserved_capacity`  |  `NodeName`, `ClusterName`, `InstanceId` `ClusterName`  |  为节点组件保留的 CPU 单元的百分比，例如 kubelet、kube-proxy 和 Docker。 公式：`node_cpu_request / node_cpu_limit`  `node_cpu_request` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `node_cpu_usage_total`  |  `ClusterName`  |  集群中节点上正在使用的 CPU 单元的数目。  | 
|  `node_cpu_utilization`  |  `NodeName`, `ClusterName`, `InstanceId` `ClusterName`  |  集群中节点上正在使用的 CPU 单元的总百分比。 公式：`node_cpu_usage_total / node_cpu_limit`  | 
|  `node_gpu_limit` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`  |  节点上可用 GPU 的总数。  | 
|  `node_gpu_usage_total` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`  |  节点上正在运行的容器组 (pod) 正在使用的 GPU 数量。  | 
|  `node_gpu_reserved_capacity` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`  |  节点上当前预留的 GPU 百分比。公式是 `node_gpu_request / node_gpu_limit`。  `node_gpu_request` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `node_filesystem_utilization`  |  `NodeName`, `ClusterName`, `InstanceId` `ClusterName`  |  集群中节点上正在使用的文件系统容量的总百分比。 公式：`node_filesystem_usage / node_filesystem_capacity`  `node_filesystem_usage` 和 `node_filesystem_capacity` 不是直接作为指标报告，而是性能日志事件中的字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `node_memory_limit`  |  `ClusterName`  |  可以分配给此集群中单个节点的最大内存量（以字节为单位）。  | 
|  `node_memory_reserved_capacity`  |  `NodeName`, `ClusterName`, `InstanceId` `ClusterName`  |  集群中节点上当前正在使用的内存百分比。 公式：`node_memory_request / node_memory_limit`  `node_memory_request` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `node_memory_utilization`  |  `NodeName`, `ClusterName`, `InstanceId` `ClusterName`  |  一个或多个节点当前正在使用的内存百分比。它是节点内存使用量除以节点内存限制的百分比。 公式：`node_memory_working_set / node_memory_limit`。  | 
|  `node_memory_working_set`  |  `ClusterName`   |  集群中节点的工作集中正在使用的内存量（以字节为单位）。  | 
|  `node_network_total_bytes`  |  `NodeName`, `ClusterName`, `InstanceId` `ClusterName`  |  集群中每个节点通过网络传输和接收的每秒总字节数。 公式：`node_network_rx_bytes + node_network_tx_bytes`  `node_network_rx_bytes` 和 `node_network_tx_bytes` 不是直接作为指标报告，而是性能日志事件中的字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `node_number_of_running_containers`  |  `NodeName`, `ClusterName`, `InstanceId` `ClusterName`  |  集群中每个节点的正在运行的容器数。  | 
|  `node_number_of_running_pods`  |  `NodeName`, `ClusterName`, `InstanceId` `ClusterName`  |  集群中每个节点上运行的 pod 的数量。  | 
|  `pod_cpu_reserved_capacity`  |  `PodName`, `Namespace`, `ClusterName` `ClusterName`  |  集群中每个 pod 预留的 CPU 容量。 公式：`pod_cpu_request / node_cpu_limit`  `pod_cpu_request` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `pod_cpu_utilization`  |  `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName` `Service`, `Namespace`, `ClusterName` `ClusterName`  |  pod 所使用的 CPU 单元的百分比。 公式：`pod_cpu_usage_total / node_cpu_limit`  | 
|  `pod_cpu_utilization_over_pod_limit`  |  `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName` `Service`, `Namespace`, `ClusterName` `ClusterName`  |  相对于容器组（pod）限制的容器组（pod）所使用的 CPU 单元的百分比。 公式：`pod_cpu_usage_total / pod_cpu_limit`  | 
|  `pod_gpu_request` |  `ClusterName` `ClusterName`, `Namespace`, `PodName` `ClusterName`, `FullPodName`, `Namespace`, `PodName`  |  容器组 (pod) 的 CPU 请求。此值必须始终等于 `pod_gpu_limit`。  | 
|  `pod_gpu_limit` |  `ClusterName` `ClusterName`, `Namespace`, `PodName` `ClusterName`, `FullPodName`, `Namespace`, `PodName`  |  可以分配给节点中容器组 (pod) 的 GPU 的最大数量。  | 
|  `pod_gpu_usage_total` |  `ClusterName` `ClusterName`, `Namespace`, `PodName` `ClusterName`, `FullPodName`, `Namespace`, `PodName`  |  在 Pod 上分配的 GPU 数量。  | 
|  `pod_gpu_reserved_capacity` |  `ClusterName` `ClusterName`, `Namespace`, `PodName` `ClusterName`, `FullPodName`, `Namespace`, `PodName`  |  当前为容器组 (pod) 预留的 GPU 百分比。公式是 pod\$1gpu\$1request / node\$1gpu\$1reserved\$1capacity。  | 
|  `pod_memory_reserved_capacity`  |  `PodName`, `Namespace`, `ClusterName` `ClusterName`  |  为 pod 预留的内存的百分比。 公式：`pod_memory_request / node_memory_limit`  `pod_memory_request` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `pod_memory_utilization`  |  `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName` `Service`, `Namespace`, `ClusterName` `ClusterName`  |  一个或多个 pod 当前正在使用的内存百分比。 公式：`pod_memory_working_set / node_memory_limit`  | 
|  `pod_memory_utilization_over_pod_limit`  |  `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName` `Service`, `Namespace`, `ClusterName` `ClusterName`  |  相对于容器组（pod）限制的容器组（pod）所使用的内存百分比。如果容器组（pod）中的任何容器没有定义内存限制，则不会显示该指标。 公式：`pod_memory_working_set / pod_memory_limit`  | 
|  `pod_network_rx_bytes`  |  `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName` `Service`, `Namespace`, `ClusterName` `ClusterName`  |  pod 通过网络每秒接收的字节数。 公式：`sum(pod_interface_network_rx_bytes)`  `pod_interface_network_rx_bytes` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `pod_network_tx_bytes`  |  `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName` `Service`, `Namespace`, `ClusterName` `ClusterName`  |  pod 通过网络每秒传输的字节数。 公式：`sum(pod_interface_network_tx_bytes)`  `pod_interface_network_tx_bytes` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `pod_number_of_container_restarts`  |  `PodName`, `Namespace`, `ClusterName`  |  一个 pod 中容器重新启动的总次数。  | 
|  `service_number_of_running_pods`  |  `Service`, `Namespace`, `ClusterName` `ClusterName`  |  运行集群中的服务的 pod 的数量。  | 

## Kueue 指标
<a name="Container-Insights-metrics-Kueue"></a>

从 CloudWatch 可观测性 EKS 附加组件的 `v2.4.0-eksbuild.1` 版本开始，适用于 Amazon EKS 的 Container Insights 支持从 Amazon EKS 集群收集 Kueue 指标。有关附加组件的更多信息，请参阅 [使用 Amazon CloudWatch Observability EKS 附加组件或 Helm 图表安装 CloudWatch 代理](install-CloudWatch-Observability-EKS-addon.md)。

有关启用这些指标的信息，请参阅[启用 Kueue 指标](install-CloudWatch-Observability-EKS-addon.md#enable-Kueue-metrics)来启用这些指标。

下表中列出了收集的 Kueue 指标。这些指标将发布到 CloudWatch 中的 `ContainerInsights/Prometheus` 命名空间中。其中一些指标使用以下维度：
+ `ClusterQueue` 是 ClusterQueue 的名称
+ `Status` 的可能值为 `active` 和 `inadmissible`
+ `Reason` 的可能值为 `Preempted`、`PodsReadyTimeout`、`AdmissionCheck`、`ClusterQueueStopped` 和 `InactiveWorkload`
+ `Flavor` 是引用的风格。
+ `Resource` 指集群计算机资源，例如 `cpu`、`memory`、`gpu` 等。


| 指标名称 | Dimensions | 说明 | 
| --- | --- | --- | 
|  `kueue_pending_workloads` |  `ClusterName`, `ClusterQueue`, `Status` `ClusterName`, `ClusterQueue` `ClusterName`, `Status` `ClusterName`  |  待处理的工作负载数量。  | 
|  `kueue_evicted_workloads_total` |  `ClusterName`, `ClusterQueue`, `Reason` `ClusterName`, `ClusterQueue` `ClusterName`, `Reason` `ClusterName`  |  已驱逐工作负载总数。  | 
|  `kueue_admitted_active_workloads` |  `ClusterName`, `ClusterQueue` `ClusterName`  |  允许的处于活动状态（未暂停和未完成）的工作负载数量。  | 
|  `kueue_cluster_queue_resource_usage` |  `ClusterName`, `ClusterQueue`, `Resource`, `Flavor` `ClusterName`, `ClusterQueue`, `Resource` `ClusterName`, `ClusterQueue`, `Flavor` `ClusterName`, `ClusterQueue` `ClusterName`  |  报告 ClusterQueue 的总资源使用情况。  | 
|  `kueue_cluster_queue_nominal_quota` |  `ClusterName`, `ClusterQueue`, `Resource`, `Flavor` `ClusterName`, `ClusterQueue`, `Resource` `ClusterName`, `ClusterQueue`, `Flavor` `ClusterName`, `ClusterQueue` `ClusterName`  |  报告 ClusterQueue 的资源配额。  | 

# Container Insights 性能日志参考
<a name="Container-Insights-reference"></a>

本节包含有关 Container Insights 如何使用性能日志事件来收集指标的参考信息。当您部署 Container Insights 时，它会自动为性能日志事件创建日志组。您无需自行创建该日志组。

**Topics**
+ [Amazon ECS 的 Container Insights 性能日志事件](Container-Insights-reference-performance-logs-ECS.md)
+ [Amazon EKS 和 Kubernetes 的 Container Insights 性能日志事件](Container-Insights-reference-performance-logs-EKS.md)
+ [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)

# Amazon ECS 的 Container Insights 性能日志事件
<a name="Container-Insights-reference-performance-logs-ECS"></a>

以下是 Container Insights 从 Amazon ECS 收集的性能日志事件的实例。

这些日志在 CloudWatch Logs 中位于名为 `/aws/ecs/containerinsights/CLUSTER_NAME/performance` 的日志组中。在该日志组中，每个容器实例都将有一个名为 `AgentTelemetry-CONTAINER_INSTANCE_ID` 的日志流。

您可以使用查询来查询这些日志，例如使用 `{ $.Type = "Container" }` 来查看所有容器日志事件。

**类型：容器**

```
{
	"Version":"0",
	"Type":"Container",
	"ContainerName":"sleep",
	"TaskId":"7ac4dfba69214411b4783a3b8189c9ba",
	"TaskDefinitionFamily":"sleep360",
	"TaskDefinitionRevision":"1",
	"ContainerInstanceId":"0d7650e6dec34c1a9200f72098071e8f",
	"EC2InstanceId":"i-0c470579dbcdbd2f3",
	"ClusterName":"MyCluster",
	"Image":"busybox",
	"ContainerKnownStatus":"RUNNING",
	"Timestamp":1623963900000,
	"CpuUtilized":0.0,
	"CpuReserved":10.0,
	"MemoryUtilized":0,
	"MemoryReserved":10,
	"StorageReadBytes":0,
	"StorageWriteBytes":0,
	"NetworkRxBytes":0,
	"NetworkRxDropped":0,
	"NetworkRxErrors":0,
	"NetworkRxPackets":14,
	"NetworkTxBytes":0,
	"NetworkTxDropped":0,
	"NetworkTxErrors":0,
	"NetworkTxPackets":0
}
```

**类型：任务**

尽管 `StorageReadBytes` 和 `StorageWriteBytes` 以字节/秒为单位，但这些值分别表示从存储中读取和写入存储的累积字节数。

```
{
    "Version": "0",
    "Type": "Task",
    "TaskId": "7ac4dfba69214411b4783a3b8189c9ba",
    "TaskDefinitionFamily": "sleep360",
    "TaskDefinitionRevision": "1",
    "ContainerInstanceId": "0d7650e6dec34c1a9200f72098071e8f",
    "EC2InstanceId": "i-0c470579dbcdbd2f3",
    "ClusterName": "MyCluster",
    "AccountID": "637146863587",
    "Region": "us-west-2",
    "AvailabilityZone": "us-west-2b",
    "KnownStatus": "RUNNING",
    "LaunchType": "EC2",
    "PullStartedAt": 1623963608201,
    "PullStoppedAt": 1623963610065,
    "CreatedAt": 1623963607094,
    "StartedAt": 1623963610382,
    "Timestamp": 1623963900000,
    "CpuUtilized": 0.0,
    "CpuReserved": 10.0,
    "MemoryUtilized": 0,
    "MemoryReserved": 10,
    "StorageReadBytes": 0,
    "StorageWriteBytes": 0,
    "NetworkRxBytes": 0,
    "NetworkRxDropped": 0,
    "NetworkRxErrors": 0,
    "NetworkRxPackets": 14,
    "NetworkTxBytes": 0,
    "NetworkTxDropped": 0,
    "NetworkTxErrors": 0,
    "NetworkTxPackets": 0,
    "EBSFilesystemUtilized": 10,
    "EBSFilesystemSize": 20,
    "CloudWatchMetrics": [
        {
            "Namespace": "ECS/ContainerInsights",
            "Metrics": [
                {
                    "Name": "CpuUtilized",
                    "Unit": "None"
                },
                {
                    "Name": "CpuReserved",
                    "Unit": "None"
                },
                {
                    "Name": "MemoryUtilized",
                    "Unit": "Megabytes"
                },
                {
                    "Name": "MemoryReserved",
                    "Unit": "Megabytes"
                },
                {
                    "Name": "StorageReadBytes",
                    "Unit": "Bytes/Second"
                },
                {
                    "Name": "StorageWriteBytes",
                    "Unit": "Bytes/Second"
                },
                {
                    "Name": "NetworkRxBytes",
                    "Unit": "Bytes/Second"
                },
                {
                    "Name": "NetworkTxBytes",
                    "Unit": "Bytes/Second"
                },
                {
                    "Name": "EBSFilesystemSize",
                    "Unit": "Gigabytes"
                },
                {
                    "Name": "EBSFilesystemUtilzed",
                    "Unit": "Gigabytes"
                }
            ],
            "Dimensions": [
                ["ClusterName"],
                [
                    "ClusterName",
                    "TaskDefinitionFamily"
                ]
            ]
        }
    ]
}
```

**类型：服务**

```
{   
    "Version": "0",
    "Type": "Service",
    "ServiceName": "myCIService",
    "ClusterName": "myCICluster",
    "Timestamp": 1561586460000,
    "DesiredTaskCount": 2,
    "RunningTaskCount": 2,
    "PendingTaskCount": 0,
    "DeploymentCount": 1,
    "TaskSetCount": 0,
    "CloudWatchMetrics": [
        {
            "Namespace": "ECS/ContainerInsights",
            "Metrics": [
                {
                    "Name": "DesiredTaskCount",
                    "Unit": "Count"
                },
                {
                    "Name": "RunningTaskCount",
                    "Unit": "Count"
                },
                {
                    "Name": "PendingTaskCount",
                    "Unit": "Count"
                },
                {
                    "Name": "DeploymentCount",
                    "Unit": "Count"
                },
                {
                    "Name": "TaskSetCount",
                    "Unit": "Count"
                }
            ],
            "Dimensions": [
                [
                    "ServiceName",
                    "ClusterName"
                ]
            ]
        }
    ]
}
```

**类型：卷**

```
{
    "Version": "0",
    "Type": "Volume",
    "TaskDefinitionFamily": "myCITaskDef",
    "TaskId": "7ac4dfba69214411b4783a3b8189c9ba",
    "ClusterName": "myCICluster",
    "ServiceName": "myCIService",
    "VolumeId": "vol-1233436545ff708cb",
    "InstanceId": "i-0c470579dbcdbd2f3",
    "LaunchType": "EC2",
    "VolumeName": "MyVolumeName",
    "EBSFilesystemUtilized": 10,
    "EBSFilesystemSize": 20,
    "CloudWatchMetrics": [
        {
            "Namespace": "ECS/ContainerInsights",
            "Metrics": [
                {
                    "Name": "EBSFilesystemSize",
                    "Unit": "Gigabytes"
                },
                {
                    "Name": "EBSFilesystemUtilzed",
                    "Unit": "Gigabytes"
                }
            ],
            "Dimensions": [
                ["ClusterName"],
                [
                    "VolumeName",
                    "TaskDefinitionFamily",
                    "ClusterName"
                ],
                [
                    "ServiceName",
                    "ClusterName"
                ]
            ]
        }
    ]
}
```

**类型：集群**

```
{
    "Version": "0",
    "Type": "Cluster",
    "ClusterName": "myCICluster",
    "Timestamp": 1561587300000,
    "TaskCount": 5,
    "ContainerInstanceCount": 5,
    "ServiceCount": 2,
    "CloudWatchMetrics": [
        {
            "Namespace": "ECS/ContainerInsights",
            "Metrics": [
                {
                    "Name": "TaskCount",
                    "Unit": "Count"
                },
                {
                    "Name": "ContainerInstanceCount",
                    "Unit": "Count"
                },
                {
                    "Name": "ServiceCount",
                    "Unit": "Count"
                }
            ],
            "Dimensions": [
                [
                    "ClusterName"
                ]
            ]
        }
    ]
}
```

# Amazon EKS 和 Kubernetes 的 Container Insights 性能日志事件
<a name="Container-Insights-reference-performance-logs-EKS"></a>

以下是 Container Insights 从 Amazon EKS 和 Kubernetes 集群中收集的性能日志事件的示例。

**类型：Node**

```
{
  "AutoScalingGroupName": "eksctl-myCICluster-nodegroup-standard-workers-NodeGroup-1174PV2WHZAYU",
  "CloudWatchMetrics": [
    {
      "Metrics": [
        {
          "Unit": "Percent",
          "Name": "node_cpu_utilization"
        },
        {
          "Unit": "Percent",
          "Name": "node_memory_utilization"
        },
        {
          "Unit": "Bytes/Second",
          "Name": "node_network_total_bytes"
        },
        {
          "Unit": "Percent",
          "Name": "node_cpu_reserved_capacity"
        },
        {
          "Unit": "Percent",
          "Name": "node_memory_reserved_capacity"
        },
        {
          "Unit": "Count",
          "Name": "node_number_of_running_pods"
        },
        {
          "Unit": "Count",
          "Name": "node_number_of_running_containers"
        }
      ],
      "Dimensions": [
        [
          "NodeName",
          "InstanceId",
          "ClusterName"
        ]
      ],
      "Namespace": "ContainerInsights"
    },
    {
      "Metrics": [
        {
          "Unit": "Percent",
          "Name": "node_cpu_utilization"
        },
        {
          "Unit": "Percent",
          "Name": "node_memory_utilization"
        },
        {
          "Unit": "Bytes/Second",
          "Name": "node_network_total_bytes"
        },
        {
          "Unit": "Percent",
          "Name": "node_cpu_reserved_capacity"
        },
        {
          "Unit": "Percent",
          "Name": "node_memory_reserved_capacity"
        },
        {
          "Unit": "Count",
          "Name": "node_number_of_running_pods"
        },
        {
          "Unit": "Count",
          "Name": "node_number_of_running_containers"
        },
        {
          "Name": "node_cpu_usage_total"
        },
        {
          "Name": "node_cpu_limit"
        },
        {
          "Unit": "Bytes",
          "Name": "node_memory_working_set"
        },
        {
          "Unit": "Bytes",
          "Name": "node_memory_limit"
        }
      ],
      "Dimensions": [
        [
          "ClusterName"
        ]
      ],
      "Namespace": "ContainerInsights"
    }
  ],
  "ClusterName": "myCICluster",
  "InstanceId": "i-1234567890123456",
  "InstanceType": "t3.xlarge",
  "NodeName": "ip-192-0-2-0.us-west-2.compute.internal",
  "Sources": [
    "cadvisor",
    "/proc",
    "pod",
    "calculated"
  ],
  "Timestamp": "1567096682364",
  "Type": "Node",
  "Version": "0",
  "kubernetes": {
    "host": "ip-192-168-75-26.us-west-2.compute.internal"
  },
  "node_cpu_limit": 4000,
  "node_cpu_request": 1130,
  "node_cpu_reserved_capacity": 28.249999999999996,
  "node_cpu_usage_system": 33.794636630852764,
  "node_cpu_usage_total": 136.47852169244098,
  "node_cpu_usage_user": 71.67075111567326,
  "node_cpu_utilization": 3.4119630423110245,
  "node_memory_cache": 3103297536,
  "node_memory_failcnt": 0,
  "node_memory_hierarchical_pgfault": 0,
  "node_memory_hierarchical_pgmajfault": 0,
  "node_memory_limit": 16624865280,
  "node_memory_mapped_file": 406646784,
  "node_memory_max_usage": 4230746112,
  "node_memory_pgfault": 0,
  "node_memory_pgmajfault": 0,
  "node_memory_request": 1115684864,
  "node_memory_reserved_capacity": 6.7109407818311055,
  "node_memory_rss": 798146560,
  "node_memory_swap": 0,
  "node_memory_usage": 3901444096,
  "node_memory_utilization": 6.601302600149552,
  "node_memory_working_set": 1097457664,
  "node_network_rx_bytes": 35918.392817386324,
  "node_network_rx_dropped": 0,
  "node_network_rx_errors": 0,
  "node_network_rx_packets": 157.67565245448117,
  "node_network_total_bytes": 68264.20276554905,
  "node_network_tx_bytes": 32345.80994816272,
  "node_network_tx_dropped": 0,
  "node_network_tx_errors": 0,
  "node_network_tx_packets": 154.21455923431654,
  "node_number_of_running_containers": 16,
  "node_number_of_running_pods": 13
}
```

**类型：NodeFS**

```
{
  "AutoScalingGroupName": "eksctl-myCICluster-nodegroup-standard-workers-NodeGroup-1174PV2WHZAYU",
  "CloudWatchMetrics": [
    {
      "Metrics": [
        {
          "Unit": "Percent",
          "Name": "node_filesystem_utilization"
        }
      ],
      "Dimensions": [
        [
          "NodeName",
          "InstanceId",
          "ClusterName"
        ],
        [
          "ClusterName"
        ]
      ],
      "Namespace": "ContainerInsights"
    }
  ],
  "ClusterName": "myCICluster",
  "EBSVolumeId": "aws://us-west-2b/vol-0a53108976d4a2fda",
  "InstanceId": "i-1234567890123456",
  "InstanceType": "t3.xlarge",
  "NodeName": "ip-192-0-2-0.us-west-2.compute.internal",
  "Sources": [
    "cadvisor",
    "calculated"
  ],
  "Timestamp": "1567097939726",
  "Type": "NodeFS",
  "Version": "0",
  "device": "/dev/nvme0n1p1",
  "fstype": "vfs",
  "kubernetes": {
    "host": "ip-192-168-75-26.us-west-2.compute.internal"
  },
  "node_filesystem_available": 17298395136,
  "node_filesystem_capacity": 21462233088,
  "node_filesystem_inodes": 10484720,
  "node_filesystem_inodes_free": 10367158,
  "node_filesystem_usage": 4163837952,
  "node_filesystem_utilization": 19.400767547940255
}
```

**类型：NodeDiskIO**

```
{
  "AutoScalingGroupName": "eksctl-myCICluster-nodegroup-standard-workers-NodeGroup-1174PV2WHZAYU",
  "ClusterName": "myCICluster",
  "EBSVolumeId": "aws://us-west-2b/vol-0a53108976d4a2fda",
  "InstanceId": "i-1234567890123456",
  "InstanceType": "t3.xlarge",
  "NodeName": "ip-192-0-2-0.us-west-2.compute.internal",
  "Sources": [
    "cadvisor"
  ],
  "Timestamp": "1567096928131",
  "Type": "NodeDiskIO",
  "Version": "0",
  "device": "/dev/nvme0n1",
  "kubernetes": {
    "host": "ip-192-168-75-26.us-west-2.compute.internal"
  },
  "node_diskio_io_service_bytes_async": 9750.505814277016,
  "node_diskio_io_service_bytes_read": 0,
  "node_diskio_io_service_bytes_sync": 230.6174506688036,
  "node_diskio_io_service_bytes_total": 9981.123264945818,
  "node_diskio_io_service_bytes_write": 9981.123264945818,
  "node_diskio_io_serviced_async": 1.153087253344018,
  "node_diskio_io_serviced_read": 0,
  "node_diskio_io_serviced_sync": 0.03603397666700056,
  "node_diskio_io_serviced_total": 1.1891212300110185,
  "node_diskio_io_serviced_write": 1.1891212300110185
}
```

**类型：NodeNet**

```
{
  "AutoScalingGroupName": "eksctl-myCICluster-nodegroup-standard-workers-NodeGroup-1174PV2WHZAYU",
  "ClusterName": "myCICluster",
  "InstanceId": "i-1234567890123456",
  "InstanceType": "t3.xlarge",
  "NodeName": "ip-192-0-2-0.us-west-2.compute.internal",
  "Sources": [
    "cadvisor",
    "calculated"
  ],
  "Timestamp": "1567096928131",
  "Type": "NodeNet",
  "Version": "0",
  "interface": "eni972f6bfa9a0",
  "kubernetes": {
    "host": "ip-192-168-75-26.us-west-2.compute.internal"
  },
  "node_interface_network_rx_bytes": 3163.008420864309,
  "node_interface_network_rx_dropped": 0,
  "node_interface_network_rx_errors": 0,
  "node_interface_network_rx_packets": 16.575629266820258,
  "node_interface_network_total_bytes": 3518.3935157426017,
  "node_interface_network_tx_bytes": 355.385094878293,
  "node_interface_network_tx_dropped": 0,
  "node_interface_network_tx_errors": 0,
  "node_interface_network_tx_packets": 3.9997714100370625
}
```

**类型：Pod**

```
{
  "AutoScalingGroupName": "eksctl-myCICluster-nodegroup-standard-workers-NodeGroup-1174PV2WHZAYU",
  "CloudWatchMetrics": [
    {
      "Metrics": [
        {
          "Unit": "Percent",
          "Name": "pod_cpu_utilization"
        },
        {
          "Unit": "Percent",
          "Name": "pod_memory_utilization"
        },
        {
          "Unit": "Bytes/Second",
          "Name": "pod_network_rx_bytes"
        },
        {
          "Unit": "Bytes/Second",
          "Name": "pod_network_tx_bytes"
        },
        {
          "Unit": "Percent",
          "Name": "pod_cpu_utilization_over_pod_limit"
        },
        {
          "Unit": "Percent",
          "Name": "pod_memory_utilization_over_pod_limit"
        }
      ],
      "Dimensions": [
        [
          "PodName",
          "Namespace",
          "ClusterName"
        ],
        [
          "Service",
          "Namespace",
          "ClusterName"
        ],
        [
          "Namespace",
          "ClusterName"
        ],
        [
          "ClusterName"
        ]
      ],
      "Namespace": "ContainerInsights"
    },
    {
      "Metrics": [
        {
          "Unit": "Percent",
          "Name": "pod_cpu_reserved_capacity"
        },
        {
          "Unit": "Percent",
          "Name": "pod_memory_reserved_capacity"
        }
      ],
      "Dimensions": [
        [
          "PodName",
          "Namespace",
          "ClusterName"
        ],
        [
          "ClusterName"
        ]
      ],
      "Namespace": "ContainerInsights"
    },
    {
      "Metrics": [
        {
          "Unit": "Count",
          "Name": "pod_number_of_container_restarts"
        }
      ],
      "Dimensions": [
        [
          "PodName",
          "Namespace",
          "ClusterName"
        ]
      ],
      "Namespace": "ContainerInsights"
    }
  ],
  "ClusterName": "myCICluster",
  "InstanceId": "i-1234567890123456",
  "InstanceType": "t3.xlarge",
  "Namespace": "amazon-cloudwatch",
  "NodeName": "ip-192-0-2-0.us-west-2.compute.internal",
  "PodName": "cloudwatch-agent-statsd",
  "Service": "cloudwatch-agent-statsd",
  "Sources": [
    "cadvisor",
    "pod",
    "calculated"
  ],
  "Timestamp": "1567097351092",
  "Type": "Pod",
  "Version": "0",
  "kubernetes": {
    "host": "ip-192-168-75-26.us-west-2.compute.internal",
    "labels": {
      "app": "cloudwatch-agent-statsd",
      "pod-template-hash": "df44f855f"
    },
    "namespace_name": "amazon-cloudwatch",
    "pod_id": "2f4ff5ac-c813-11e9-a31d-06e9dde32928",
    "pod_name": "cloudwatch-agent-statsd-df44f855f-ts4q2",
    "pod_owners": [
      {
        "owner_kind": "Deployment",
        "owner_name": "cloudwatch-agent-statsd"
      }
    ],
    "service_name": "cloudwatch-agent-statsd"
  },
  "pod_cpu_limit": 200,
  "pod_cpu_request": 200,
  "pod_cpu_reserved_capacity": 5,
  "pod_cpu_usage_system": 1.4504841104992765,
  "pod_cpu_usage_total": 5.817016867430125,
  "pod_cpu_usage_user": 1.1281543081661038,
  "pod_cpu_utilization": 0.14542542168575312,
  "pod_cpu_utilization_over_pod_limit": 2.9085084337150624,
  "pod_memory_cache": 8192,
  "pod_memory_failcnt": 0,
  "pod_memory_hierarchical_pgfault": 0,
  "pod_memory_hierarchical_pgmajfault": 0,
  "pod_memory_limit": 104857600,
  "pod_memory_mapped_file": 0,
  "pod_memory_max_usage": 25268224,
  "pod_memory_pgfault": 0,
  "pod_memory_pgmajfault": 0,
  "pod_memory_request": 104857600,
  "pod_memory_reserved_capacity": 0.6307275170893897,
  "pod_memory_rss": 22777856,
  "pod_memory_swap": 0,
  "pod_memory_usage": 25141248,
  "pod_memory_utilization": 0.10988455961791709,
  "pod_memory_utilization_over_pod_limit": 17.421875,
  "pod_memory_working_set": 18268160,
  "pod_network_rx_bytes": 9880.697124714186,
  "pod_network_rx_dropped": 0,
  "pod_network_rx_errors": 0,
  "pod_network_rx_packets": 107.80005532263283,
  "pod_network_total_bytes": 10158.829201483635,
  "pod_network_tx_bytes": 278.13207676944796,
  "pod_network_tx_dropped": 0,
  "pod_network_tx_errors": 0,
  "pod_network_tx_packets": 1.146027574644318,
  "pod_number_of_container_restarts": 0,
  "pod_number_of_containers": 1,
  "pod_number_of_running_containers": 1,
  "pod_status": "Running"
}
```

**类型：PodNet**

```
{
  "AutoScalingGroupName": "eksctl-myCICluster-nodegroup-standard-workers-NodeGroup-1174PV2WHZAYU",
  "ClusterName": "myCICluster",
  "InstanceId": "i-1234567890123456",
  "InstanceType": "t3.xlarge",
  "Namespace": "amazon-cloudwatch",
  "NodeName": "ip-192-0-2-0.us-west-2.compute.internal",
  "PodName": "cloudwatch-agent-statsd",
  "Service": "cloudwatch-agent-statsd",
  "Sources": [
    "cadvisor",
    "calculated"
  ],
  "Timestamp": "1567097351092",
  "Type": "PodNet",
  "Version": "0",
  "interface": "eth0",
  "kubernetes": {
    "host": "ip-192-168-75-26.us-west-2.compute.internal",
    "labels": {
      "app": "cloudwatch-agent-statsd",
      "pod-template-hash": "df44f855f"
    },
    "namespace_name": "amazon-cloudwatch",
    "pod_id": "2f4ff5ac-c813-11e9-a31d-06e9dde32928",
    "pod_name": "cloudwatch-agent-statsd-df44f855f-ts4q2",
    "pod_owners": [
      {
        "owner_kind": "Deployment",
        "owner_name": "cloudwatch-agent-statsd"
      }
    ],
    "service_name": "cloudwatch-agent-statsd"
  },
  "pod_interface_network_rx_bytes": 9880.697124714186,
  "pod_interface_network_rx_dropped": 0,
  "pod_interface_network_rx_errors": 0,
  "pod_interface_network_rx_packets": 107.80005532263283,
  "pod_interface_network_total_bytes": 10158.829201483635,
  "pod_interface_network_tx_bytes": 278.13207676944796,
  "pod_interface_network_tx_dropped": 0,
  "pod_interface_network_tx_errors": 0,
  "pod_interface_network_tx_packets": 1.146027574644318
}
```

**类型：容器**

```
{
  "AutoScalingGroupName": "eksctl-myCICluster-nodegroup-standard-workers-NodeGroup-sample",
  "ClusterName": "myCICluster",
  "InstanceId": "i-1234567890123456",
  "InstanceType": "t3.xlarge",
  "Namespace": "amazon-cloudwatch",
  "NodeName": "ip-192-0-2-0.us-west-2.compute.internal",
  "PodName": "cloudwatch-agent-statsd",
  "Service": "cloudwatch-agent-statsd",
  "Sources": [
    "cadvisor",
    "pod",
    "calculated"
  ],
  "Timestamp": "1567097399912",
  "Type": "Container",
  "Version": "0",
  "container_cpu_limit": 200,
  "container_cpu_request": 200,
  "container_cpu_usage_system": 1.87958283771964,
  "container_cpu_usage_total": 6.159993652997942,
  "container_cpu_usage_user": 1.6707403001952357,
  "container_cpu_utilization": 0.15399984132494854,
  "container_memory_cache": 8192,
  "container_memory_failcnt": 0,
  "container_memory_hierarchical_pgfault": 0,
  "container_memory_hierarchical_pgmajfault": 0,
  "container_memory_limit": 104857600,
  "container_memory_mapped_file": 0,
  "container_memory_max_usage": 24580096,
  "container_memory_pgfault": 0,
  "container_memory_pgmajfault": 0,
  "container_memory_request": 104857600,
  "container_memory_rss": 22736896,
  "container_memory_swap": 0,
  "container_memory_usage": 24453120,
  "container_memory_utilization": 0.10574541028701798,
  "container_memory_working_set": 17580032,
  "container_status": "Running",
  "kubernetes": {
    "container_name": "cloudwatch-agent",
    "docker": {
      "container_id": "8967b6b37da239dfad197c9fdea3e5dfd35a8a759ec86e2e4c3f7b401e232706"
    },
    "host": "ip-192-168-75-26.us-west-2.compute.internal",
    "labels": {
      "app": "cloudwatch-agent-statsd",
      "pod-template-hash": "df44f855f"
    },
    "namespace_name": "amazon-cloudwatch",
    "pod_id": "2f4ff5ac-c813-11e9-a31d-06e9dde32928",
    "pod_name": "cloudwatch-agent-statsd-df44f855f-ts4q2",
    "pod_owners": [
      {
        "owner_kind": "Deployment",
        "owner_name": "cloudwatch-agent-statsd"
      }
    ],
    "service_name": "cloudwatch-agent-statsd"
  },
  "number_of_container_restarts": 0
}
```

**类型：ContainerFS**

```
{
  "AutoScalingGroupName": "eksctl-myCICluster-nodegroup-standard-workers-NodeGroup-1174PV2WHZAYU",
  "ClusterName": "myCICluster",
  "EBSVolumeId": "aws://us-west-2b/vol-0a53108976d4a2fda",
  "InstanceId": "i-1234567890123456",
  "InstanceType": "t3.xlarge",
  "Namespace": "amazon-cloudwatch",
  "NodeName": "ip-192-0-2-0.us-west-2.compute.internal",
  "PodName": "cloudwatch-agent-statsd",
  "Service": "cloudwatch-agent-statsd",
  "Sources": [
    "cadvisor",
    "calculated"
  ],
  "Timestamp": "1567097399912",
  "Type": "ContainerFS",
  "Version": "0",

  "device": "/dev/nvme0n1p1",
  "fstype": "vfs",
  "kubernetes": {
    "container_name": "cloudwatch-agent",
    "docker": {
      "container_id": "8967b6b37da239dfad197c9fdea3e5dfd35a8a759ec86e2e4c3f7b401e232706"
    },
    "host": "ip-192-168-75-26.us-west-2.compute.internal",
    "labels": {
      "app": "cloudwatch-agent-statsd",
      "pod-template-hash": "df44f855f"
    },
    "namespace_name": "amazon-cloudwatch",
    "pod_id": "2f4ff5ac-c813-11e9-a31d-06e9dde32928",
    "pod_name": "cloudwatch-agent-statsd-df44f855f-ts4q2",
    "pod_owners": [
      {
        "owner_kind": "Deployment",
        "owner_name": "cloudwatch-agent-statsd"
      }
    ],
    "service_name": "cloudwatch-agent-statsd"
  }
}
```

**类型：集群**

```
{
  "CloudWatchMetrics": [
    {
      "Metrics": [
        {
          "Unit": "Count",
          "Name": "cluster_node_count"
        },
        {
          "Unit": "Count",
          "Name": "cluster_failed_node_count"
        }
      ],
      "Dimensions": [
        [
          "ClusterName"
        ]
      ],
      "Namespace": "ContainerInsights"
    }
  ],
  "ClusterName": "myCICluster",
  "Sources": [
    "apiserver"
  ],
  "Timestamp": "1567097534160",
  "Type": "Cluster",
  "Version": "0",
  "cluster_failed_node_count": 0,
  "cluster_node_count": 3
}
```

**类型：“ClusterService”**

```
{
  "CloudWatchMetrics": [
    {
      "Metrics": [
        {
          "Unit": "Count",
          "Name": "service_number_of_running_pods"
        }
      ],
      "Dimensions": [
        [
          "Service",
          "Namespace",
          "ClusterName"
        ],
        [
          "ClusterName"
        ]
      ],
      "Namespace": "ContainerInsights"
    }
  ],
  "ClusterName": "myCICluster",
  "Namespace": "amazon-cloudwatch",
  "Service": "cloudwatch-agent-statsd",
  "Sources": [
    "apiserver"
  ],
  "Timestamp": "1567097534160",
  "Type": "ClusterService",
  "Version": "0",
  "kubernetes": {
    "namespace_name": "amazon-cloudwatch",
    "service_name": "cloudwatch-agent-statsd"
  },
  "service_number_of_running_pods": 1
}
```

**类型：ClusterNamespace**

```
{
  "CloudWatchMetrics": [
    {
      "Metrics": [
        {
          "Unit": "Count",
          "Name": "namespace_number_of_running_pods"
        }
      ],
      "Dimensions": [
        [
          "Namespace",
          "ClusterName"
        ],
        [
          "ClusterName"
        ]
      ],
      "Namespace": "ContainerInsights"
    }
  ],
  "ClusterName": "myCICluster",
  "Namespace": "amazon-cloudwatch",
  "Sources": [
    "apiserver"
  ],
  "Timestamp": "1567097594160",
  "Type": "ClusterNamespace",
  "Version": "0",
  "kubernetes": {
    "namespace_name": "amazon-cloudwatch"
  },
  "namespace_number_of_running_pods": 7
}
```

# Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段
<a name="Container-Insights-reference-performance-entries-EKS"></a>

对于 Amazon EKS 和 Kubernetes，容器化的 CloudWatch 代理将数据作为性能日志事件发出。这使 CloudWatch 能够摄取和存储高基数数据。CloudWatch 使用性能日志事件中的数据在集群、节点和 pod 级别创建聚合的 CloudWatch 指标，而不会丢失详细信息。

下表列出了这些性能日志事件中与 Container Insights 指标数据收集相关的字段。您可以使用 CloudWatch Logs Insights 查询其中的任何字段以收集数据或调查问题。有关更多信息，请参阅[使用 CloudWatch Logs Insights 分析日志数据](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AnalyzingLogData.html)。


| Type | 日志字段 | 来源 | 公式或备注 | 
| --- | --- | --- | --- | 
|  Pod |  `pod_cpu_utilization`  |  计算  |  公式：`pod_cpu_usage_total / node_cpu_limit`  | 
|  Pod |  `pod_cpu_usage_total` `pod_cpu_usage_total` 以千分之一核心为单位报道。  |  cadvisor  |   | 
|  Pod |  `pod_cpu_limit`  |  计算  |  公式：`sum(container_cpu_limit)` `sum(container_cpu_limit)` 包括已经完成的容器组（pod）。 如果 pod 中的任何容器未定义 CPU 限制，则该字段不会显示在日志事件中。这包括 [init 容器](https://kubernetes.io/docs/concepts/workloads/pods/init-containers/#resources)。  | 
|  Pod |  `pod_cpu_request`  |  计算  |  公式：`sum(container_cpu_request)` 不保证设置 `container_cpu_request`。仅在总和中包括设置的字段。  | 
|  Pod |  `pod_cpu_utilization_over_pod_limit`  |  计算  |  公式：`pod_cpu_usage_total / pod_cpu_limit`  | 
|  Pod |  `pod_cpu_reserved_capacity`  |  计算  |  公式：`pod_cpu_request / node_cpu_limit`  | 
|  Pod |  `pod_memory_utilization`  |  计算  |  公式：`pod_memory_working_set / node_memory_limit` 它是 pod 内存使用量相比节点内存限制的百分比。  | 
|  Pod |  `pod_memory_working_set`  |  cadvisor  |   | 
|  Pod |  `pod_memory_limit`  |  计算  |  公式：`sum(container_memory_limit)` 如果 pod 中的任何容器没有定义内存限制，则该字段不会显示在日志事件中。这包括 [init 容器](https://kubernetes.io/docs/concepts/workloads/pods/init-containers/#resources)。  | 
|  Pod |  `pod_memory_request`  |  计算  |  公式：`sum(container_memory_request)` 不保证设置 `container_memory_request`。仅在总和中包括设置的字段。  | 
|  Pod |  `pod_memory_utilization_over_pod_limit`  |  计算  |  公式：`pod_memory_working_set / pod_memory_limit` 如果 pod 中的任何容器没有定义内存限制，则该字段不会显示在日志事件中。这包括 [init 容器](https://kubernetes.io/docs/concepts/workloads/pods/init-containers/#resources)。  | 
|  Pod |  `pod_memory_reserved_capacity`  |  计算  |  公式：`pod_memory_request / node_memory_limit`  | 
|  Pod |  `pod_network_tx_bytes`  |  计算  |  公式：`sum(pod_interface_network_tx_bytes)` 该数据适用于每个 pod 的所有网络接口。CloudWatch 代理计算总数并添加指标提取规则。  | 
|  Pod |  `pod_network_rx_bytes`  |  计算  |  公式：`sum(pod_interface_network_rx_bytes)`  | 
|  Pod |  `pod_network_total_bytes`  |  计算  |  公式：`pod_network_rx_bytes + pod_network_tx_bytes`  | 
|  PodNet |  `pod_interface_network_rx_bytes`  |  cadvisor  | 该数据是 pod 网络接口每秒接收的网络字节数。  | 
|  PodNet |  `pod_interface_network_tx_bytes`  |  cadvisor  | 该数据是 pod 网络接口每秒发送的网络字节数。 | 
|  容器 |  `container_cpu_usage_total`  |  cadvisor  |   | 
|  容器 |  `container_cpu_limit`  |  cadvisor  |  不保证设置该字段。如果未设置，则不会发出该指标。 | 
|  容器 |  `container_cpu_request`  |  cadvisor  |  不保证设置该字段。如果未设置，则不会发出该指标。 | 
|  容器 |  `container_memory_working_set`  |  cadvisor  |   | 
|  容器 |  `container_memory_limit`  |  容器组（pod）  |  不保证设置该字段。如果未设置，则不会发出该指标。 | 
|  容器 |  `container_memory_request`  |  容器组（pod）  |  不保证设置该字段。如果未设置，则不会发出该指标。 | 
|  节点 |  `node_cpu_utilization`  |  计算  |  公式：`node_cpu_usage_total / node_cpu_limit`  | 
|  节点 |  `node_cpu_usage_total`  |  cadvisor  |   | 
|  节点 |  `node_cpu_limit`  |  /proc  |   | 
|  节点 |  `node_cpu_request`  |  计算  | 公式：`sum(pod_cpu_request)` 对于 cronjobs，`node_cpu_request` 还包括来自已完成的容器组（pod）的请求。这可能会导致 `node_cpu_reserved_capacity` 的值很高。  | 
|  节点 |  `node_cpu_reserved_capacity`  |  计算  | 公式：`node_cpu_request / node_cpu_limit`  | 
|  节点 |  `node_memory_utilization`  |  计算  | 公式：`node_memory_working_set / node_memory_limit`  | 
|  节点 |  `node_memory_working_set`  |  cadvisor  |   | 
|  节点 |  `node_memory_limit`  |  /proc  |   | 
|  节点 |  `node_memory_request`  |  计算  |  公式：`sum(pod_memory_request)`  | 
|  节点 |  `node_memory_reserved_capacity`  |  计算  | 公式：`node_memory_request / node_memory_limit`  | 
|  节点 |  `node_network_rx_bytes`  |  计算  | 公式：`sum(node_interface_network_rx_bytes)`  | 
|  节点 |  `node_network_tx_bytes`  |  计算  | 公式：`sum(node_interface_network_tx_bytes)`  | 
|  节点 |  `node_network_total_bytes`  |  计算  | 公式：`node_network_rx_bytes + node_network_tx_bytes`  | 
|  节点 |  `node_number_of_running_pods`  |  Pod 列表  |   | 
|  节点 |  `node_number_of_running_containers`  |  Pod 列表  |   | 
|  NodeNet |  `node_interface_network_rx_bytes`  |  cadvisor  |  该数据是工作线程节点网络接口每秒接收的网络字节数。  | 
|  NodeNet |  `node_interface_network_tx_bytes`  |  cadvisor  |  该数据是工作线程节点网络接口每秒发送的网络字节数。  | 
|  NodeFS |  `node_filesystem_capacity`  |  cadvisor  |   | 
|  NodeFS |  `node_filesystem_usage`  |  cadvisor  |   | 
|  NodeFS |  `node_filesystem_utilization`  |  计算  |  公式：`node_filesystem_usage / node_filesystem_capacity` 该数据适用于每个设备名称。  | 
|  集群 |  `cluster_failed_node_count`  |  API 服务器  |   | 
|  集群 |  `cluster_node_count`  |  API 服务器  |   | 
|  服务 |  `service_number_of_running_pods`  |  API 服务器  |   | 
|  `Namespace` |  `namespace_number_of_running_pods`  |  API 服务器  |   | 

## 指标计算示例
<a name="Container-Insights-calculation-examples"></a>

本节包含的示例说明了如何计算上表中的某些值。

假设您具有一个处于以下状态的集群。

```
Node1
   node_cpu_limit = 4
   node_cpu_usage_total = 3
   
   Pod1
     pod_cpu_usage_total = 2
     
     Container1
        container_cpu_limit = 1
        container_cpu_request = 1
        container_cpu_usage_total = 0.8
        
     Container2
        container_cpu_limit = null
        container_cpu_request = null
        container_cpu_usage_total = 1.2
        
   Pod2
     pod_cpu_usage_total = 0.4
     
     Container3
        container_cpu_limit = 1
        container_cpu_request = 0.5
        container_cpu_usage_total = 0.4
        
Node2
   node_cpu_limit = 8
   node_cpu_usage_total = 1.5
   
   Pod3
     pod_cpu_usage_total = 1
     
     Container4
        container_cpu_limit = 2
        container_cpu_request = 2
        container_cpu_usage_total = 1
```

下表说明了如何使用该数据计算 pod CPU 指标。


| 指标 | Formula | Pod1 | Pod2 | Pod3 | 
| --- | --- | --- | --- | --- | 
|  `pod_cpu_utilization` |  `pod_cpu_usage_total / node_cpu_limit`  |  2 / 4 = 50%  |  0.4 / 4 = 10%  |  1 / 8 = 12.5%  | 
|  `pod_cpu_utilization_over_pod_limit` |  `pod_cpu_usage_total / sum(container_cpu_limit)`  |  不适用，因为没有定义 `Container2` 的 CPU 限制  |  0.4 / 1 = 40%  |  1 / 2 = 50%  | 
|  `pod_cpu_reserved_capacity` |  `sum(container_cpu_request) / node_cpu_limit`  |  (1 \$1 0) / 4 = 25%  |  0.5 / 4 = 12.5%  |  2 / 8 = 25%  | 

下表说明了如何使用该数据计算节点 CPU 指标。


| 指标 | Formula | Node1 | Node2 | 
| --- | --- | --- | --- | 
|  `node_cpu_utilization` |  `node_cpu_usage_total / node_cpu_limit`  |  3 / 4 = 75%  |  1.5 / 8 = 18.75%  | 
|  `node_cpu_reserved_capacity` |  `sum(pod_cpu_request) / node_cpu_limit`  |  1.5 / 4 = 37.5%  |  2 / 8 = 25%  | 

# Container Insights Prometheus 指标监控
<a name="ContainerInsights-Prometheus"></a>

适用于 Prometheus 的 CloudWatch Container Insights 监控可以自动发现来自容器化系统和工作负载的 Prometheus 指标。Prometheus 是一个开源系统监控和警报工具包。有关更多信息，请参阅 Prometheus 文档中的[什么是 Prometheus？](https://prometheus.io/docs/introduction/overview/)

[Amazon Elastic Container Service](https://aws.amazon.com/ecs/)、[Amazon Elastic Kubernetes Service](https://aws.amazon.com/eks/) 和在 Amazon EC2 实例上运行的 [Kubernetes](https://aws.amazon.com/kubernetes/) 集群支持发现 Prometheus 指标。收集了 Prometheus 计数器、计量表和汇总指标类型。

对于 Amazon ECS 和 Amazon EKS 集群，EC2 和 Fargate 启动类型均受支持。Container Insights 会自动从多个工作负载收集指标，您可以将其配置为从任何工作负载收集指标。

您可以采用 Prometheus 作为开源和开放标准方法，在 CloudWatch 中摄取自定义指标。具有 Prometheus 支持的 CloudWatch 代理可以发现并收集 Prometheus 指标，以便监控应用程序性能下降和故障，并更快地进行故障排除和发出告警。这也减少了改进可观测性所需的监控工具数量。

Container Insights Prometheus 支持涉及按用量付费的指标和日志，包括收集、存储和分析。有关更多信息，请参阅 [Amazon CloudWatch 定价](https://aws.amazon.com/cloudwatch/pricing/)。

**某些工作负载的预构建控制面板**

Container Insights Prometheus 解决方案包括针对本节中列出的常见工作负载的预构建控制面板。有关这些工作负载的示例配置，请参阅 [（可选）为 Prometheus 指标测试设置示例容器化 Amazon ECS 工作负载](ContainerInsights-Prometheus-Sample-Workloads-ECS.md) 和 [（可选）为 Prometheus 指标测试设置示例容器化 Amazon EKS 工作负载](ContainerInsights-Prometheus-Sample-Workloads.md)。

您还可以配置 Container Insights 以通过编辑代理配置文件从其他容器化服务和应用程序收集 Prometheus 指标。

带有适用于在 Amazon EC2 实例上运行的 Amazon EKS 集群和 Kubernetes 集群的预构建控制面板的工作负载：
+ AWS App Mesh
+ NGINX
+ Memcached
+ Java/JMX
+ HAProxy

带有适用于 Amazon ECS 集群的预构建控制面板的工作负载：
+ AWS App Mesh
+ Java/JMX
+ NGINX
+ NGINX Plus

# 在亚马逊云服务器集群上设置和配置 Prometheus 指标收集 在 Amazon ECS 集群上设置和配置 Prometheus 指标收集
<a name="ContainerInsights-Prometheus-Setup-ECS"></a>

要从 Amazon ECS 集群收集 Prometheus 指标，您可以使用 CloudWatch 代理作为收集器或使用 AWS Distro for OpenTelemetry 收集器。有关使用 AWS Distro for OpenTelemetry 收集器的信息，请参阅 [https://aws-otel.github.io/docs/getting-started/container-insights/ecs-prometheus](https://aws-otel.github.io/docs/getting-started/container-insights/ecs-prometheus)。

下面几节介绍如何使用 CloudWatch 代理作为收集器来检索 Prometheus 指标。您可以在运行 Amazon ECS 的集群上安装带有 Prometheus 监控功能的 CloudWatch 代理，还可以选择配置该代理以抓取其他目标。这些部分还提供用于设置示例工作负载的可选教程，以使用 Prometheus 监控进行测试。

Amazon ECS 上的 Container Insights 支持 Prometheus 指标的以下启动类型和网络模式组合：


| Amazon ECS 启动类型 | 支持的网络模式 | 
| --- | --- | 
|  EC2 (Linux)  |  网桥、主机和 awsvpc  | 
|  Fargate  |  awsvpc  | 

**VPC 安全组要求**

Prometheus 工作负载的安全组的入口规则必须向 CloudWatch 代理打开 Prometheus 端口，以便通过私有 IP 抓取 Prometheus 指标。

CloudWatch 代理的安全组的出口规则必须允许 CloudWatch 代理通过私有 IP 连接到 Prometheus 工作负载的端口。

**Topics**
+ [在 Amazon ECS 集群上安装带有 Prometheus 指标收集功能的 CloudWatch 代理](ContainerInsights-Prometheus-install-ECS.md)
+ [抓取其他 Prometheus 源并导入这些指标](ContainerInsights-Prometheus-Setup-configure-ECS.md)
+ [（可选）为 Prometheus 指标测试设置示例容器化 Amazon ECS 工作负载](ContainerInsights-Prometheus-Sample-Workloads-ECS.md)

# 在 Amazon ECS 集群上安装带有 Prometheus 指标收集功能的 CloudWatch 代理
<a name="ContainerInsights-Prometheus-install-ECS"></a>

本节介绍如何在运行 Amazon ECS 的集群中设置带有 Prometheus 监控功能的 CloudWatch 代理。执行此操作后，代理会自动抓取并导入该集群中运行的以下工作负载的指标。
+ AWS App Mesh
+ Java/JMX

您还可以将代理配置为从其他 Prometheus 工作负载和源抓取及导入指标。

## 设置 IAM 角色
<a name="ContainerInsights-Prometheus-Setup-ECS-IAM"></a>

您需要两个 IAM 角色来执行 CloudWatch 代理任务定义。如果您指定 CloudFormation 堆栈中的 **CreateIAMRoles=True** 让 Container Insights 为您创建这些角色，则将使用正确的权限创建这些角色。如果要自己创建或使用现有角色，则需要以下角色和权限。
+ **CloudWatch 代理 ECS 任务角色** – CloudWatch 代理容器使用此角色。它必须包括 **CloudWatchAgentServerPolicy** 策略以及包含以下只读权限的客户管理策略：
  + `ec2:DescribeInstances`
  + `ecs:ListTasks`
  + `ecs:ListServices`
  + `ecs:DescribeContainerInstances`
  + `ecs:DescribeServices`
  + `ecs:DescribeTasks`
  + `ecs:DescribeTaskDefinition`
+ **CloudWatch 代理 ECS 任务执行角色** – 这是 Amazon ECS 启动和执行容器所需的角色。确保您的任务执行角色附加了 **AmazonSSMReadOnlyAccess**、**AmazonECSTaskExecutionRolePolicy** 和 **CloudWatchAgentServerPolicy** 策略。如果您需要存储更敏感的数据以供 Amazon ECS 使用，请参阅[指定敏感数据](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/specifying-sensitive-data.html)以了解更多信息。

## 使用 CloudFormation 安装带有 Prometheus 监控功能的 CloudWatch 代理
<a name="ContainerInsights-Prometheus-Setup-ECS-CFN"></a>

您使用 AWS CloudFormation 为 Amazon ECS 集群安装带有 Prometheus 监控功能的 CloudWatch 代理。以下列表显示了您将在 CloudFormation 模板中使用的参数。
+ **ECSClusterName** – 指定目标 Amazon ECS 集群。
+ **CreateIAMRoles** – 指定 **True** 为 Amazon ECS 任务角色和 Amazon ECS 任务执行角色创建新角色。指定 **False** 重新使用现有角色。
+ **TaskRoleName** – 如果您为 **CreateIAMRoles** 指定 **True**，这会指定用于新 Amazon ECS 任务角色的名称。如果您为 **CreateIAMRoles** 指定 **False**，这会指定要用作 Amazon ECS 任务角色的现有角色。
+ **ExecutionRoleName** – 如果您为 **CreateIAMRoles** 指定 **True**，这会指定用于新 Amazon ECS 任务执行角色的名称。如果您为 **CreateIAMRoles** 指定 **False**，这会指定要用作 Amazon ECS 任务执行角色的现有角色。
+ **ECSNetworkMode** – 如果您使用 EC2 启动类型，请在此处指定网络模式。必须是 **bridge** 或 **host**。
+ **ECSLaunchType** – 指定 **fargate** 或 **EC2**。
+ **SecurityGroupID** – 如果 **ECSNetworkMode** 是 **awsvpc**，请在此处指定安全组 ID。
+ **SubnetID** – 如果 **ECSNetworkMode** 是 **awsvpc**，请在此处指定子网 ID。

### 命令示例
<a name="ContainerInsights-Prometheus-Setup-ECS-CFNcommands"></a>

本节包含在各种情况下安装带有 Prometheus 监控功能的 Container Insights 的 CloudFormation 示例命令。

**在桥式网络模式下为 Amazon ECS 集群创建 CloudFormation 堆栈**

```
export AWS_PROFILE=your_aws_config_profile_eg_default
export AWS_DEFAULT_REGION=your_aws_region_eg_ap-southeast-1
export ECS_CLUSTER_NAME=your_ec2_ecs_cluster_name
export ECS_NETWORK_MODE=bridge
export CREATE_IAM_ROLES=True
export ECS_TASK_ROLE_NAME=your_selected_ecs_task_role_name
export ECS_EXECUTION_ROLE_NAME=your_selected_ecs_execution_role_name

curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/ecs-task-definition-templates/deployment-mode/replica-service/cwagent-prometheus/cloudformation-quickstart/cwagent-ecs-prometheus-metric-for-bridge-host.yaml

aws cloudformation create-stack --stack-name CWAgent-Prometheus-ECS-${ECS_CLUSTER_NAME}-EC2-${ECS_NETWORK_MODE} \
    --template-body file://cwagent-ecs-prometheus-metric-for-bridge-host.yaml \
    --parameters ParameterKey=ECSClusterName,ParameterValue=${ECS_CLUSTER_NAME} \
                 ParameterKey=CreateIAMRoles,ParameterValue=${CREATE_IAM_ROLES} \
                 ParameterKey=ECSNetworkMode,ParameterValue=${ECS_NETWORK_MODE} \
                 ParameterKey=TaskRoleName,ParameterValue=${ECS_TASK_ROLE_NAME} \
                 ParameterKey=ExecutionRoleName,ParameterValue=${ECS_EXECUTION_ROLE_NAME} \
    --capabilities CAPABILITY_NAMED_IAM \
    --region ${AWS_DEFAULT_REGION} \
    --profile ${AWS_PROFILE}
```

**在主机网络模式下为 Amazon ECS 集群创建 CloudFormation 堆栈**

```
export AWS_PROFILE=your_aws_config_profile_eg_default
export AWS_DEFAULT_REGION=your_aws_region_eg_ap-southeast-1
export ECS_CLUSTER_NAME=your_ec2_ecs_cluster_name
export ECS_NETWORK_MODE=host
export CREATE_IAM_ROLES=True
export ECS_TASK_ROLE_NAME=your_selected_ecs_task_role_name
export ECS_EXECUTION_ROLE_NAME=your_selected_ecs_execution_role_name


curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/ecs-task-definition-templates/deployment-mode/replica-service/cwagent-prometheus/cloudformation-quickstart/cwagent-ecs-prometheus-metric-for-bridge-host.yaml

aws cloudformation create-stack --stack-name CWAgent-Prometheus-ECS-${ECS_CLUSTER_NAME}-EC2-${ECS_NETWORK_MODE} \
    --template-body file://cwagent-ecs-prometheus-metric-for-bridge-host.yaml \
    --parameters ParameterKey=ECSClusterName,ParameterValue=${ECS_CLUSTER_NAME} \
                 ParameterKey=CreateIAMRoles,ParameterValue=${CREATE_IAM_ROLES} \
                 ParameterKey=ECSNetworkMode,ParameterValue=${ECS_NETWORK_MODE} \
                 ParameterKey=TaskRoleName,ParameterValue=${ECS_TASK_ROLE_NAME} \
                 ParameterKey=ExecutionRoleName,ParameterValue=${ECS_EXECUTION_ROLE_NAME} \ 
    --capabilities CAPABILITY_NAMED_IAM \
    --region ${AWS_DEFAULT_REGION} \
    --profile ${AWS_PROFILE}
```

**在 awsvpc 网络模式下为 Amazon ECS 集群创建 CloudFormation 堆栈**

```
export AWS_PROFILE=your_aws_config_profile_eg_default
export AWS_DEFAULT_REGION=your_aws_region_eg_ap-southeast-1
export ECS_CLUSTER_NAME=your_ec2_ecs_cluster_name
export ECS_LAUNCH_TYPE=EC2
export CREATE_IAM_ROLES=True
export ECS_CLUSTER_SECURITY_GROUP=your_security_group_eg_sg-xxxxxxxxxx
export ECS_CLUSTER_SUBNET=your_subnet_eg_subnet-xxxxxxxxxx
export ECS_TASK_ROLE_NAME=your_selected_ecs_task_role_name
export ECS_EXECUTION_ROLE_NAME=your_selected_ecs_execution_role_name

curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/ecs-task-definition-templates/deployment-mode/replica-service/cwagent-prometheus/cloudformation-quickstart/cwagent-ecs-prometheus-metric-for-awsvpc.yaml

aws cloudformation create-stack --stack-name CWAgent-Prometheus-ECS-${ECS_CLUSTER_NAME}-${ECS_LAUNCH_TYPE}-awsvpc \
    --template-body file://cwagent-ecs-prometheus-metric-for-awsvpc.yaml \
    --parameters ParameterKey=ECSClusterName,ParameterValue=${ECS_CLUSTER_NAME} \
                 ParameterKey=CreateIAMRoles,ParameterValue=${CREATE_IAM_ROLES} \
                 ParameterKey=ECSLaunchType,ParameterValue=${ECS_LAUNCH_TYPE} \
                 ParameterKey=SecurityGroupID,ParameterValue=${ECS_CLUSTER_SECURITY_GROUP} \
                 ParameterKey=SubnetID,ParameterValue=${ECS_CLUSTER_SUBNET} \
                 ParameterKey=TaskRoleName,ParameterValue=${ECS_TASK_ROLE_NAME} \
                 ParameterKey=ExecutionRoleName,ParameterValue=${ECS_EXECUTION_ROLE_NAME} \
    --capabilities CAPABILITY_NAMED_IAM \
    --region ${AWS_DEFAULT_REGION} \
    --profile ${AWS_PROFILE}
```

**在 awsvpc 网络模式下为 Fargate 集群创建 CloudFormation 堆栈**

```
export AWS_PROFILE=your_aws_config_profile_eg_default
export AWS_DEFAULT_REGION=your_aws_region_eg_ap-southeast-1
export ECS_CLUSTER_NAME=your_ec2_ecs_cluster_name
export ECS_LAUNCH_TYPE=FARGATE
export CREATE_IAM_ROLES=True
export ECS_CLUSTER_SECURITY_GROUP=your_security_group_eg_sg-xxxxxxxxxx
export ECS_CLUSTER_SUBNET=your_subnet_eg_subnet-xxxxxxxxxx
export ECS_TASK_ROLE_NAME=your_selected_ecs_task_role_name
export ECS_EXECUTION_ROLE_NAME=your_selected_ecs_execution_role_name            

curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/ecs-task-definition-templates/deployment-mode/replica-service/cwagent-prometheus/cloudformation-quickstart/cwagent-ecs-prometheus-metric-for-awsvpc.yaml

aws cloudformation create-stack --stack-name CWAgent-Prometheus-ECS-${ECS_CLUSTER_NAME}-${ECS_LAUNCH_TYPE}-awsvpc \
    --template-body file://cwagent-ecs-prometheus-metric-for-awsvpc.yaml \
    --parameters ParameterKey=ECSClusterName,ParameterValue=${ECS_CLUSTER_NAME} \
                 ParameterKey=CreateIAMRoles,ParameterValue=${CREATE_IAM_ROLES} \
                 ParameterKey=ECSLaunchType,ParameterValue=${ECS_LAUNCH_TYPE} \
                 ParameterKey=SecurityGroupID,ParameterValue=${ECS_CLUSTER_SECURITY_GROUP} \
                 ParameterKey=SubnetID,ParameterValue=${ECS_CLUSTER_SUBNET} \
                 ParameterKey=TaskRoleName,ParameterValue=${ECS_TASK_ROLE_NAME} \
                 ParameterKey=ExecutionRoleName,ParameterValue=${ECS_EXECUTION_ROLE_NAME} \
    --capabilities CAPABILITY_NAMED_IAM \
    --region ${AWS_DEFAULT_REGION} \
    --profile ${AWS_PROFILE}
```

### CloudFormation 堆栈创建的 AWS 资源
<a name="ContainerInsights-Prometheus-Setup-ECS-resources"></a>

下表列出了 AWS 资源，该资源在 Amazon ECS 集群上使用 CloudFormation 设置 带有 Prometheus 监控功能的 Container Insights 时创建。


| 资源类型 | 资源名称 | 评论 | 
| --- | --- | --- | 
|  AWS::SSM::Parameter  |  AmazonCloudWatch-CWAgentConfig-\$1*ECS\$1CLUSTER\$1NAME*-\$1*ECS\$1LAUNCH\$1TYPE*-\$1*ECS\$1NETWORK\$1MODE*  |  这是具有默认 App Mesh 和 Java/JMX 嵌入式指标格式定义的 CloudWatch 代理。  | 
|  AWS::SSM::Parameter  |  AmazonCloudWatch-PrometheusConfigName-\$1*ECS\$1CLUSTER\$1NAME*-\$1*ECS\$1LAUNCH\$1TYPE*-\$1*ECS\$1NETWORK\$1MODE*  |  这是 Prometheus 抓取配置。  | 
|  AWS::IAM::Role  |  **\$1ECS\$1TASK\$1ROLE\$1NAME**。  |  Amazon ECS 任务角色。这仅在您为 `CREATE_IAM_ROLES` 指定 **True** 时创建。  | 
|  AWS::IAM::Role  |  **\$1\$1ECS\$1EXECUTION\$1ROLE\$1NAME\$1**   |  Amazon ECS 任务执行角色。这仅在您为 `CREATE_IAM_ROLES` 指定 **True** 时创建。  | 
|  AWS::ECS::TaskDefinition  |  cwagent-prometheus-\$1*ECS\$1CLUSTER\$1NAME*-\$1*ECS\$1LAUNCH\$1TYPE*-\$1*ECS\$1NETWORK\$1MODE*   |   | 
|  AWS::ECS::Service  |  cwagent-prometheus-replica-service-\$1*ECS\$1LAUNCH\$1TYPE*-\$1*ECS\$1NETWORK\$1MODE*  |   | 

### 使用 Prometheus 监控功能删除 CloudWatch 代理的 CloudFormation 堆栈
<a name="ContainerInsights-Prometheus-ECS-delete"></a>

要从 Amazon ECS 集群中删除 CloudWatch 代理，请输入以下命令。

```
export AWS_PROFILE=your_aws_config_profile_eg_default
export AWS_DEFAULT_REGION=your_aws_region_eg_ap-southeast-1
export CLOUDFORMATION_STACK_NAME=your_cloudformation_stack_name

aws cloudformation delete-stack \
--stack-name ${CLOUDFORMATION_STACK_NAME} \
--region ${AWS_DEFAULT_REGION} \
--profile ${AWS_PROFILE}
```

# 抓取其他 Prometheus 源并导入这些指标
<a name="ContainerInsights-Prometheus-Setup-configure-ECS"></a>

具有 Prometheus 监控功能的 CloudWatch 代理需要两种配置来抓取 Prometheus 指标。一个用于 Prometheus 文档中 [<scrape\$1config>](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#scrape_config) 记录的标准 Prometheus 配置。另一种配置是 CloudWatch 代理配置文件。

对于 Amazon ECS 集群，配置通过 Amazon ECS 任务定义中的密钥与 AWS Systems Manager 的 Parameter Store 集成：
+ 密钥 `PROMETHEUS_CONFIG_CONTENT` 用于 Prometheus 抓取配置。
+ 密钥 `CW_CONFIG_CONTENT` 用于 CloudWatch 代理配置。

要抓取其他 Prometheus 指标源并将这些指标导入 CloudWatch，您需要修改 Prometheus 抓取配置和 CloudWatch 代理配置，然后使用更新的配置重新部署代理。

**VPC 安全组要求**

Prometheus 工作负载的安全组的入口规则必须向 CloudWatch 代理打开 Prometheus 端口，以便通过私有 IP 抓取 Prometheus 指标。

CloudWatch 代理的安全组的出口规则必须允许 CloudWatch 代理通过私有 IP 连接到 Prometheus 工作负载的端口。

## Prometheus 抓取配置
<a name="ContainerInsights-Prometheus-Setup-config-global"></a>

CloudWatch 代理支持标准的 Prometheus 抓取配置，如 Prometheus 文档中的 [<scrape\$1config>](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#scrape_config) 所述。您可以编辑此部分以更新此文件中已有的配置，并添加其他 Prometheus 抓取目标。默认情况下，示例配置文件包含以下全局配置行：

```
global:
  scrape_interval: 1m
  scrape_timeout: 10s
```
+ **scrape\$1interval** – 定义抓取目标的频率。
+ **scrape\$1timeout** – 定义抓取请求超时之前的等待时间。

您还可以在作业级别为这些设置定义不同的值，以覆盖全局配置。

### Prometheus 抓取任务
<a name="ContainerInsights-Prometheus-Setup-config-scrape"></a>

CloudWatch 代理 YAML 文件已配置了一些默认的抓取任务。例如，在 Amazon ECS 的 YAML 文件（例如 `cwagent-ecs-prometheus-metric-for-bridge-host.yaml`）中，默认抓取任务在 `ecs_service_discovery` 部分中配置。

```
"ecs_service_discovery": {
                  "sd_frequency": "1m",
                  "sd_result_file": "/tmp/cwagent_ecs_auto_sd.yaml",
                  "docker_label": {
                  },
                  "task_definition_list": [
                    {
                      "sd_job_name": "ecs-appmesh-colors",
                      "sd_metrics_ports": "9901",
                      "sd_task_definition_arn_pattern": ".*:task-definition\/.*-ColorTeller-(white):[0-9]+",
                      "sd_metrics_path": "/stats/prometheus"
                    },
                    {
                      "sd_job_name": "ecs-appmesh-gateway",
                      "sd_metrics_ports": "9901",
                      "sd_task_definition_arn_pattern": ".*:task-definition/.*-ColorGateway:[0-9]+",
                      "sd_metrics_path": "/stats/prometheus"
                    }
                  ]
                }
```

这些默认目标中的每个目标都会被抓取，并使用嵌入式指标格式在日志事件中将指标发送到 CloudWatch。有关更多信息，请参阅 [在日志中嵌入指标](CloudWatch_Embedded_Metric_Format.md)。

来自 Amazon ECS 集群的日志事件存储在 **/aws/ecs/containerinsights/*cluster\$1name*/prometheus** 日志组中。

每个抓取作业都包含在此日志组中的不同日志流中。

要添加新的抓取目标，请在 YAML 文件 `ecs_service_discovery` 部分下的 `task_definition_list` 部分中添加一个新条目，然后重新启动代理。有关此过程的示例，请参阅 [添加新 Prometheus 抓取目标的教程：Prometheus API 服务器指标](ContainerInsights-Prometheus-Setup-configure.md#ContainerInsights-Prometheus-Setup-new-exporters)。

## Prometheus 的 CloudWatch 代理配置
<a name="ContainerInsights-Prometheus-Setup-cw-agent-config"></a>

CloudWatch 代理配置文件在 `metrics_collected` 下面有一个 `prometheus` 部分用于 Prometheus 抓取配置。它包含以下配置选项：
+ **cluster\$1name** – 指定要在日志事件中添加为标签的集群名称。该字段是可选的。如果省略此项，代理可以检测 Amazon ECS 集群名称。
+ **log\$1group\$1name** – 指定已抓取 Prometheus 指标的日志组名称。该字段是可选的。如果省略此项，CloudWatch 会将 **/aws/ecs/containerinsights/*cluster\$1name*/prometheus** 用于来自 Amazon ECS 集群的日志。
+ **prometheus\$1config\$1path** – 指定 Prometheus 抓取配置文件路径。如果此字段的值以 `env:` 开头，Prometheus 抓取配置文件内容将从容器的环境变量中检索。请勿更改此字段。
+ **ecs\$1service\$1discovery** – 是指定 Amazon ECS Prometheus 目标自动发现功能配置的部分。支持两种模式来发现 Prometheus 目标：根据容器的 docker 标签的发现或根据 Amazon ECS 任务定义 ARN 正则表达式的发现。您可以同时使用这两种模式，CloudWatch 代理将根据 *\$1private\$1ip\$1:\$1port\$1/\$1metrics\$1path\$1* 对发现的目标进行重复去除。

  `ecs_service_discovery` 部分包含以下字段：
  + `sd_frequency` 是发现 Prometheus 导出器的频率。指定数字和单位后缀。例如，`1m` 表示每分钟一次或 `30s` 表示每 30 秒一次。有效的单位后缀为 `ns`、`us`、`ms`、`s`、`m` 和 `h`。

    该字段是可选的。默认值为 60 秒（1 分钟）。
  + `sd_target_cluster` 是用于自动发现的目标 Amazon ECS 集群名称。该字段是可选的。默认名称为安装 CloudWatch 代理的 Amazon ECS 集群的名称。
  + `sd_cluster_region` 是目标 Amazon ECS 集群的区域。该字段是可选的。默认区域为安装 CloudWatch 代理的 Amazon ECS 集群的区域。
  + `sd_result_file` 是 Prometheus 目标结果的 YAML 文件的路径。Prometheus 抓取配置将引用此文件。
  + `docker_label` 是可选部分，您可以使用它来指定基于 docker 标签的服务发现的配置。如果省略此部分，则不会使用基于 docker 标签的发现。此部分包含以下字段：
    + `sd_port_label` 是容器的 docker 标签名称，用于指定 Prometheus 指标的容器端口。默认值为 `ECS_PROMETHEUS_EXPORTER_PORT`。如果容器没有此 docker 标签，CloudWatch 代理将跳过它。
    + `sd_metrics_path_label` 是容器的 docker 标签名称，用于指定 Prometheus 指标路径。默认值为 `ECS_PROMETHEUS_METRICS_PATH`。如果容器没有此 docker 标签，则代理会采用默认路径 `/metrics`。
    + `sd_job_name_label` 是容器的 docker 标签名称，用于指定 Prometheus 抓取任务名称。默认值为 `job`。如果容器没有此 docker 标签，CloudWatch 代理会使用 Prometheus 抓取配置中的任务名称。
  + `task_definition_list` 是可选部分，可用于指定基于任务定义的服务发现的配置。如果省略此部分，则不会使用基于任务定义的发现。此部分包含以下字段：
    + `sd_task_definition_arn_pattern` 是用于指定要发现的 Amazon ECS 任务定义的模式。这是正则表达式。
    + `sd_metrics_ports` 列出 Prometheus 指标的 containerPort。用分号分隔 containerPorts。
    + `sd_container_name_pattern` 指定 Amazon ECS 任务容器名称。这是正则表达式。
    + `sd_metrics_path` 指定 Prometheus 指标路径。如果省略此项，代理会采用默认路径 `/metrics`
    + `sd_job_name` 指定 Prometheus 抓取任务名称。如果省略此字段，CloudWatch 代理会使用 Prometheus 抓取配置中的任务名称。
  + `service_name_list_for_tasks` 是可选部分，可用于指定基于服务名称的发现的配置。如果省略此部分，则不会使用基于服务名称的发现。此部分包含以下字段：
    + `sd_service_name_pattern` 是用于指定要在其中发现任务的 Amazon ECS 服务的模式。这是正则表达式。
    + `sd_metrics_ports` 列出 Prometheus 指标的 `containerPort`。用分号分隔多个 `containerPorts`。
    + `sd_container_name_pattern` 指定 Amazon ECS 任务容器名称。这是正则表达式。
    + `sd_metrics_path` 指定 Prometheus 指标路径。如果省略此项，代理会采用默认路径 `/metrics`。
    + `sd_job_name` 指定 Prometheus 抓取任务名称。如果省略此字段，CloudWatch 代理会使用 Prometheus 抓取配置中的任务名称。
+ **metric\$1declaration** – 是指定要生成的采用嵌入式指标格式的日志数组的部分。默认情况下，CloudWatch 代理从中进行导入的每个 Prometheus 源都有 `metric_declaration` 部分。这些部分各包括以下字段：
  + `label_matcher` 是一个正则表达式，用于检查 `source_labels` 中列出的标签的值。匹配的指标将启用，以包含在发送到 CloudWatch 的嵌入式指标格式中。

    如果您在 `source_labels` 中指定了多个标签，我们建议您不要在 `label_matcher` 的正则表达式中使用 `^` 或 `$` 字符。
  + `source_labels` 指定由 `label_matcher` 行检查的标签的值。
  + `label_separator` 指定要在 ` label_matcher` 行中使用的分隔符（如果指定了多个 `source_labels`）。默认值为 `;`。您可以在以下示例中看到 `label_matcher` 行中使用的此默认值。
  + `metric_selectors` 是一个正则表达式，用于指定要收集并发送到 CloudWatch 的指标。
  + `dimensions` 是要用作每个选定指标的 CloudWatch 维度的标签列表。

请参阅以下 `metric_declaration` 示例。

```
"metric_declaration": [
  {
     "source_labels":[ "Service", "Namespace"],
     "label_matcher":"(.*node-exporter.*|.*kube-dns.*);kube-system$",
     "dimensions":[
        ["Service", "Namespace"]
     ],
     "metric_selectors":[
        "^coredns_dns_request_type_count_total$"
     ]
  }
]
```

此示例配置嵌入式指标格式部分，以便在满足以下条件时作为日志事件发送：
+ `Service` 的值包含 `node-exporter` 或 `kube-dns`。
+ `Namespace` 的值为 `kube-system`。
+ Prometheus 指标 `coredns_dns_request_type_count_total` 同时包含 `Service` 和 `Namespace` 标签。

发送的日志事件包括以下突出显示的部分：

```
{
   "CloudWatchMetrics":[
      {
         "Metrics":[
            {
               "Name":"coredns_dns_request_type_count_total"
            }
         ],
         "Dimensions":[
            [
               "Namespace",
               "Service"
            ]
         ],
         "Namespace":"ContainerInsights/Prometheus"
      }
   ],
   "Namespace":"kube-system",
   "Service":"kube-dns",
   "coredns_dns_request_type_count_total":2562,
   "eks_amazonaws_com_component":"kube-dns",
   "instance":"192.168.61.254:9153",
   "job":"kubernetes-service-endpoints",
   ...
}
```

# Amazon ECS 集群上自动发现的详细指南
<a name="ContainerInsights-Prometheus-Setup-autodiscovery-ecs"></a>

Prometheus 提供了数十种动态服务发现机制，如 [<scrape\$1config>](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#scrape_config) 中所述。但是，Amazon ECS 没有内置服务发现。CloudWatch 代理添加了此机制。

启用 Amazon ECS Prometheus 服务发现后，CloudWatch 代理会定期对 Amazon ECS 和 Amazon EC2 前端进行以下 API 调用，以检索目标 ECS 集群中正在运行的 ECS 任务的元数据。

```
EC2:DescribeInstances
ECS:ListTasks
ECS:ListServices
ECS:DescribeContainerInstances
ECS:DescribeServices
ECS:DescribeTasks
ECS:DescribeTaskDefinition
```

CloudWatch 代理使用元数据来扫描 ECS 集群内的 Prometheus 目标。CloudWatch 代理支持三种服务发现模式：
+ 基于容器 docker 标签的服务发现
+ 基于 ECS 任务定义 ARN 正则表达式的服务发现
+ 基于 ECS 服务名称正则表达式的服务发现

所有模式均可同时使用。CloudWatch 代理会根据 `{private_ip}:{port}/{metrics_path}` 对发现的目标进行重复去除。

所有发现的目标均写入由 CloudWatch 代理容器内的 `sd_result_file` 配置字段指定的结果文件。以下为示例结果文件：

```
- targets:
  - 10.6.1.95:32785
  labels:
    __metrics_path__: /metrics
    ECS_PROMETHEUS_EXPORTER_PORT: "9406"
    ECS_PROMETHEUS_JOB_NAME: demo-jar-ec2-bridge-dynamic
    ECS_PROMETHEUS_METRICS_PATH: /metrics
    InstanceType: t3.medium
    LaunchType: EC2
    SubnetId: subnet-123456789012
    TaskDefinitionFamily: demo-jar-ec2-bridge-dynamic-port
    TaskGroup: family:demo-jar-ec2-bridge-dynamic-port
    TaskRevision: "7"
    VpcId: vpc-01234567890
    container_name: demo-jar-ec2-bridge-dynamic-port
    job: demo-jar-ec2-bridge-dynamic
- targets:
  - 10.6.3.193:9404
  labels:
    __metrics_path__: /metrics
    ECS_PROMETHEUS_EXPORTER_PORT_SUBSET_B: "9404"
    ECS_PROMETHEUS_JOB_NAME: demo-tomcat-ec2-bridge-mapped-port
    ECS_PROMETHEUS_METRICS_PATH: /metrics
    InstanceType: t3.medium
    LaunchType: EC2
    SubnetId: subnet-123456789012
    TaskDefinitionFamily: demo-tomcat-ec2-bridge-mapped-port
    TaskGroup: family:demo-jar-tomcat-bridge-mapped-port
    TaskRevision: "12"
    VpcId: vpc-01234567890
    container_name: demo-tomcat-ec2-bridge-mapped-port
    job: demo-tomcat-ec2-bridge-mapped-port
```

您可以直接将此结果文件与基于 Prometheus 文件的服务发现集成。有关基于 Prometheus 文件的服务发现的更多信息，请参阅 [<file\$1sd\$1config>](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#file_sd_config)。

 假设将结果文件写入 `/tmp/cwagent_ecs_auto_sd.yaml`。以下 Prometheus 抓取配置将使用它。

```
global:
  scrape_interval: 1m
  scrape_timeout: 10s
scrape_configs:
  - job_name: cwagent-ecs-file-sd-config
    sample_limit: 10000
    file_sd_configs:
      - files: [ "/tmp/cwagent_ecs_auto_sd.yaml" ]
```

CloudWatch 代理还会为发现的目标添加以下附加标签。
+ `container_name`
+ `TaskDefinitionFamily`
+ `TaskRevision`
+ `TaskGroup`
+ `StartedBy`
+ `LaunchType`
+ `job`
+ `__metrics_path__`
+ Docker 标签

当集群具有 EC2 启动类型时，会添加以下三个标签。
+ `InstanceType`
+ `VpcId`
+ `SubnetId`

**注意**  
与正则表达式 `[a-zA-Z_][a-zA-Z0-9_]*` 不匹配的 Docker 标签将被筛选掉。这与 Prometheus 文档中[配置文件](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#labelname)的 `label_name` 中列出的 Prometheus 惯例相匹配。

## ECS 服务发现配置示例
<a name="ContainerInsights-Prometheus-Setup-autodiscovery-ecs-examples"></a>

本节包括演示 ECS 服务发现的示例。

**示例 1**

```
"ecs_service_discovery": {
  "sd_frequency": "1m",
  "sd_result_file": "/tmp/cwagent_ecs_auto_sd.yaml",
  "docker_label": {
  }
}
```

此示例启用基于 docker 标签的服务发现。CloudWatch 代理将每分钟查询一次 ECS 任务的元数据，并将发现的目标写入 CloudWatch 代理容器内的 `/tmp/cwagent_ecs_auto_sd.yaml` 文件中。

`docker_label` 部分中 `sd_port_label` 的默认值为 `ECS_PROMETHEUS_EXPORTER_PORT`。如果 ECS 任务中任何正在运行的容器具有 `ECS_PROMETHEUS_EXPORTER_PORT` docker 标签，CloudWatch 代理将其值作为 `container port` 来扫描容器的所有公开端口。如果匹配，则使用映射的主机端口和容器的私有 IP，以 `private_ip:host_port` 格式来构建 Prometheus 导出器目标。

`docker_label` 部分中 `sd_metrics_path_label` 的默认值为 `ECS_PROMETHEUS_METRICS_PATH`。如果容器具有此 docker 标签，则其值将用作 `__metrics_path__`。如果容器没有此标签，则使用默认值 `/metrics`。

`docker_label` 部分中 `sd_job_name_label` 的默认值为 `job`。如果容器具有此 docker 标签，则其值将作为一个目标标签附加，以替换 Prometheus 配置中指定的默认任务名称。此 docker 标签的值用作 CloudWatch Logs 日志组中的日志流名称。

**示例 2**

```
"ecs_service_discovery": {
  "sd_frequency": "15s",
  "sd_result_file": "/tmp/cwagent_ecs_auto_sd.yaml",
  "docker_label": {
    "sd_port_label": "ECS_PROMETHEUS_EXPORTER_PORT_SUBSET_A",
    "sd_job_name_label": "ECS_PROMETHEUS_JOB_NAME"  
  }
}
```

此示例启用基于 docker 标签的服务发现。CloudWatch 代理将每 15 秒查询一次 ECS 任务的元数据，并将发现的目标写入 CloudWatch 代理容器内的 `/tmp/cwagent_ecs_auto_sd.yaml` 文件中。带有 `ECS_PROMETHEUS_EXPORTER_PORT_SUBSET_A` 的 docker 标签的容器将被扫描。docker 标签 `ECS_PROMETHEUS_JOB_NAME` 的值用作任务名称。

**示例 3**

```
"ecs_service_discovery": {
  "sd_frequency": "5m",
  "sd_result_file": "/tmp/cwagent_ecs_auto_sd.yaml",
  "task_definition_list": [
    {
      "sd_job_name": "java-prometheus",
      "sd_metrics_path": "/metrics",
      "sd_metrics_ports": "9404; 9406",
      "sd_task_definition_arn_pattern": ".*:task-definition/.*javajmx.*:[0-9]+"
    },
    {
      "sd_job_name": "envoy-prometheus",
      "sd_metrics_path": "/stats/prometheus",
      "sd_container_name_pattern": "^envoy$", 
      "sd_metrics_ports": "9901",
      "sd_task_definition_arn_pattern": ".*:task-definition/.*appmesh.*:23"
    }
  ]
}
```

此示例启用基于 ECS 任务定义 ARN 正则表达式的服务发现。CloudWatch 代理将每五分钟查询一次 ECS 任务的元数据，并将发现的目标写入 CloudWatch 代理容器内的 `/tmp/cwagent_ecs_auto_sd.yaml` 文件中。

定义了两个任务定义 ARN 正则表达式部分：
+  对于第一部分，过滤 ECS 任务定义 ARN 中的 ECS 任务以及 `javajmx`，以进行容器端口扫描。如果这些 ECS 任务中的容器在 9404 或 9406 上公开容器端口，则映射的主机端口和容器的私有 IP 会用于创建 Prometheus 导出器目标。`sd_metrics_path` 的值将 `__metrics_path__` 设置为 `/metrics`。因此 CloudWatch 代理将从 `private_ip:host_port/metrics` 中抓取 Prometheus 指标，抓取的指标发送到日志组 `/aws/ecs/containerinsights/cluster_name/prometheus` 中 CloudWatch Logs 中的 `java-prometheus` 日志流。
+  对于第二部分，过滤 ECS 任务定义 ARN 中带有 `appmesh` 的 ECS 任务以及 `:23` 的 `version`，以进行容器端口扫描。对于在 `9901` 上公开容器端口的、名称为 `envoy` 的容器，映射的主机端口以及容器的私有 IP 用于创建 Prometheus 导出器目标。这些 ECS 任务中的值会公开 9404 或 9406 上的容器端口，映射的主机端口以及容器的私有 IP 用于创建 Prometheus 导出器目标。`sd_metrics_path` 的值将 `__metrics_path__` 设置为 `/stats/prometheus`。因此，CloudWatch 代理将从 `private_ip:host_port/stats/prometheus` 中抓取 Prometheus 指标，并将抓取的指标发送到日志组 `/aws/ecs/containerinsights/cluster_name/prometheus` 中的 CloudWatch Logs 中的 `envoy-prometheus` 日志流。

**示例 4**。

```
"ecs_service_discovery": {
  "sd_frequency": "5m",
  "sd_result_file": "/tmp/cwagent_ecs_auto_sd.yaml",
  "service_name_list_for_tasks": [
    {
      "sd_job_name": "nginx-prometheus",
      "sd_metrics_path": "/metrics",
      "sd_metrics_ports": "9113",
      "sd_service_name_pattern": "^nginx-.*"
    },
    {
      "sd_job_name": "haproxy-prometheus",
      "sd_metrics_path": "/stats/metrics",
      "sd_container_name_pattern": "^haproxy$",
      "sd_metrics_ports": "8404",
      "sd_service_name_pattern": ".*haproxy-service.*"
    }
  ]
}
```

本示例启用基于 ECS 服务名称正则表达式的服务发现。CloudWatch 代理将每五分钟查询一次 ECS 服务的元数据，并将发现的目标写入 CloudWatch 代理容器内的 `/tmp/cwagent_ecs_auto_sd.yaml` 文件中。

定义了两个服务名称正则表达式部分：
+  对于第一部分，过滤与 ECS 服务关联的 ECS 任务（名称与正则表达式 `^nginx-.*` 相匹配），以进行容器端口扫描。如果这些 ECS 任务中的容器在 9113 上公开容器端口，则映射的主机端口和容器的私有 IP 将用于创建 Prometheus 导出器目标。`sd_metrics_path` 的值将 `__metrics_path__` 设置为 `/metrics`。因此，CloudWatch 代理将从 `private_ip:host_port/metrics` 中抓取 Prometheus 指标，并将抓取的指标发送到日志组 `/aws/ecs/containerinsights/cluster_name/prometheus` 中 CloudWatch Logs 中的 `nginx-prometheus` 日志流。
+  或第二部分，过滤与 ECS 服务关联的 ECS 任务（名称与正则表达式 `.*haproxy-service.*` 匹配），以进行容器端口扫描。对于在 8404 上公开容器端口、名称为 `haproxy` 的容器，映射的主机端口以及容器的私有 IP 用于创建 Prometheus 导出器目标。`sd_metrics_path` 的值将 `__metrics_path__` 设置为 `/stats/metrics`。因此，CloudWatch 代理将从 `private_ip:host_port/stats/metrics` 中抓取 Prometheus 指标，并将抓取的指标发送到日志组 `/aws/ecs/containerinsights/cluster_name/prometheus` 中 CloudWatch Logs 中的 `haproxy-prometheus` 日志流。

**示例 5**

```
"ecs_service_discovery": {
  "sd_frequency": "1m30s",
  "sd_result_file": "/tmp/cwagent_ecs_auto_sd.yaml",
  "docker_label": {
    "sd_port_label": "MY_PROMETHEUS_EXPORTER_PORT_LABEL",
    "sd_metrics_path_label": "MY_PROMETHEUS_METRICS_PATH_LABEL",
    "sd_job_name_label": "MY_PROMETHEUS_METRICS_NAME_LABEL"  
  }
  "task_definition_list": [
    {
      "sd_metrics_ports": "9150",
      "sd_task_definition_arn_pattern": "*memcached.*"
    }
  ]
}
```

本示例启用了两种 ECS 服务发现模式。CloudWatch 代理将每 90 秒查询一次 ECS 任务的元数据，并将发现的目标写入 CloudWatch 代理容器内的 `/tmp/cwagent_ecs_auto_sd.yaml` 文件中。

对于基于 docker 的服务发现配置：
+ 过滤带有 docker 标签 `MY_PROMETHEUS_EXPORTER_PORT_LABEL` 的 ECS 任务，以进行 Prometheus 端口扫描。目标 Prometheus 容器端口由 label `MY_PROMETHEUS_EXPORTER_PORT_LABEL` 的值指定。
+ docker 标签 `MY_PROMETHEUS_EXPORTER_PORT_LABEL` 的值用于 `__metrics_path__`。如果容器没有此 docker 标签，则使用默认值 `/metrics`。
+ docker 标签 `MY_PROMETHEUS_EXPORTER_PORT_LABEL` 的值用作任务标签。如果容器没有此 docker 标签，则使用 Prometheus 配置中定义的任务名称。

对于基于 ECS 任务定义 ARN 正则表达式的服务发现配置：
+ 过滤 ECS 任务定义 ARN 中带 `memcached` 的 ECS 任务，以进行容器端口扫描。根据 `sd_metrics_ports` 定义，目标 Prometheus 容器端口是 9150。使用默认指标路径 `/metrics`。使用 Prometheus 配置中定义的任务名称。

# （可选）为 Prometheus 指标测试设置示例容器化 Amazon ECS 工作负载
<a name="ContainerInsights-Prometheus-Sample-Workloads-ECS"></a>

要测试 CloudWatch Container Insights 中的 Prometheus 指标支持，您可设置以下一个或多个容器化工作负载。具有 Prometheus 支持的 CloudWatch 代理会自动从这些工作负载中的每一个收集指标。要查看默认情况下收集的指标，请参阅 [CloudWatch 代理收集的 Prometheus 指标](ContainerInsights-Prometheus-metrics.md)。

**Topics**
+ [Amazon ECS 集群的示例 App Mesh 工作负载](ContainerInsights-Prometheus-Sample-Workloads-ECS-appmesh.md)
+ [Amazon ECS 集群的示例 Java/JMX 工作负载](ContainerInsights-Prometheus-Sample-Workloads-ECS-javajmx.md)
+ [Amazon ECS 集群的示例 NGINX 工作负载](ContainerInsights-Prometheus-Setup-nginx-ecs.md)
+ [Amazon ECS 集群的示例 NGINX Plus 工作负载](ContainerInsights-Prometheus-Setup-nginx-plus-ecs.md)
+ [添加新 Prometheus 抓取目标的教程：Amazon ECS 上的 Memcached](ContainerInsights-Prometheus-Setup-memcached-ecs.md)
+ [在 Amazon ECS Fargate 上抓取 Redis OSS Prometheus 指标的教程](ContainerInsights-Prometheus-Setup-redis-ecs.md)

# Amazon ECS 集群的示例 App Mesh 工作负载
<a name="ContainerInsights-Prometheus-Sample-Workloads-ECS-appmesh"></a>

要从 Amazon ECS 的示例 Prometheus 工作负载收集指标，您必须在集群中运行 Container Insights。有关安装 Container Insights 的信息，请参阅 [在 Amazon ECS 上设置 Container Insights](deploy-container-insights-ECS.md)。

首先，按照本[演练](https://github.com/aws/aws-app-mesh-examples/tree/main/examples/apps/colorapp#app-mesh-walkthrough-deploy-the-color-app-on-ecs)在 Amazon ECS 集群上部署示例颜色应用程序。完成后，您将在端口 9901 上公开 App Mesh Prometheus 指标。

接下来，按照以下步骤在安装颜色应用程序的同一 Amazon ECS 集群上，安装带有 Prometheus 监控功能的 CloudWatch 代理。本节中的步骤以桥式网络模式安装 CloudWatch 代理。

您在演练中设置的环境变量 `ENVIRONMENT_NAME`、`AWS_PROFILE` 和 `AWS_DEFAULT_REGION`也将在以下步骤中使用。

**安装带有 Prometheus 监控功能的 CloudWatch 代理以进行测试**

1. 通过输入以下命令，下载 CloudFormation 模板。

   ```
   curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/ecs-task-definition-templates/deployment-mode/replica-service/cwagent-prometheus/cloudformation-quickstart/cwagent-ecs-prometheus-metric-for-bridge-host.yaml
   ```

1. 通过输入以下命令，设置网络模式。

   ```
   export ECS_CLUSTER_NAME=${ENVIRONMENT_NAME}
   export ECS_NETWORK_MODE=bridge
   ```

1. 输入以下命令以创建 CloudFormation 堆栈。

   ```
   aws cloudformation create-stack --stack-name CWAgent-Prometheus-ECS-${ECS_CLUSTER_NAME}-EC2-${ECS_NETWORK_MODE} \
       --template-body file://cwagent-ecs-prometheus-metric-for-bridge-host.yaml \
       --parameters ParameterKey=ECSClusterName,ParameterValue=${ECS_CLUSTER_NAME} \
                    ParameterKey=CreateIAMRoles,ParameterValue=True \
                    ParameterKey=ECSNetworkMode,ParameterValue=${ECS_NETWORK_MODE} \
                    ParameterKey=TaskRoleName,ParameterValue=CWAgent-Prometheus-TaskRole-${ECS_CLUSTER_NAME} \
                    ParameterKey=ExecutionRoleName,ParameterValue=CWAgent-Prometheus-ExecutionRole-${ECS_CLUSTER_NAME} \
       --capabilities CAPABILITY_NAMED_IAM \
       --region ${AWS_DEFAULT_REGION} \
       --profile ${AWS_PROFILE}
   ```

1. （可选）创建 CloudFormation 堆栈后，您会看到 `CREATE_COMPLETE` 消息。如果要在看到该消息之前检查状态，请输入以下命令。

   ```
   aws cloudformation describe-stacks \
   --stack-name CWAgent-Prometheus-ECS-${ECS_CLUSTER_NAME}-EC2-${ECS_NETWORK_MODE} \
   --query 'Stacks[0].StackStatus' \
   --region ${AWS_DEFAULT_REGION} \
   --profile ${AWS_PROFILE}
   ```

**故障排查**

演练中的步骤使用 jq 来分析 AWS CLI 的输出结果。有关安装 jq 代理的更多信息，请参阅 [ jq](https://stedolan.github.io/jq/)。使用以下命令将 AWS CLI 的默认输出格式设置为 JSON，以便 jq 可以对其进行正确分析。

```
$ aws configure
```

当响应变为 `Default output format` 时，输入 **json**。

## 使用 Prometheus 监控功能卸载 CloudWatch 代理
<a name="ContainerInsights-Prometheus-Sample-Workloads-ECS-appmesh-uninstall"></a>

完成测试后，输入以下命令以通过 CloudFormation 删除堆栈来卸载 CloudWatch 代理。

```
aws cloudformation delete-stack \
--stack-name CWAgent-Prometheus-ECS-${ECS_CLUSTER_NAME}-EC2-${ECS_NETWORK_MODE} \
--region ${AWS_DEFAULT_REGION} \
--profile ${AWS_PROFILE}
```

# Amazon ECS 集群的示例 Java/JMX 工作负载
<a name="ContainerInsights-Prometheus-Sample-Workloads-ECS-javajmx"></a>

JMX Exporter 是 Prometheus 的官方导出程序，可以将 JMX MBeans 作为 Prometheus 指标进行抓取和公开。有关详细信息，请参阅 [prometheus/jmx\$1exporter](https://github.com/prometheus/jmx_exporter)。

支持 Prometheus 的 CloudWatch 代理根据 Amazon ECS 集群中的服务发现配置抓取 Java/JMX Prometheus 指标。您可以将 JMX Exporter 配置为在不同端口或 metrics\$1path 上公开指标。如果您更改了端口或路径，请更新 CloudWatch 代理配置中的默认 `ecs_service_discovery` 部分。

要从 Amazon ECS 的示例 Prometheus 工作负载收集指标，您必须在集群中运行 Container Insights。有关安装 Container Insights 的信息，请参阅 [在 Amazon ECS 上设置 Container Insights](deploy-container-insights-ECS.md)。

**为 Amazon ECS 集群安装 Java/JMX 示例工作负载**

1. 按照这些部分中的步骤创建 Docker 镜像。
   + [示例：具有 Prometheus 指标的 Java Jar 应用程序 Docker 镜像](ContainerInsights-Prometheus-Sample-Workloads-javajmx.md#ContainerInsights-Prometheus-Sample-Workloads-javajmx-jar)
   + [示例：具有 Prometheus 指标的 Apache Tomcat Docker 镜像](ContainerInsights-Prometheus-Sample-Workloads-javajmx.md#ContainerInsights-Prometheus-Sample-Workloads-javajmx-tomcat)

1. 在 Amazon ECS 任务定义文件中指定以下两个 docker 标签。然后，您可以将任务定义作为集群中的 Amazon ECS 服务或 Amazon ECS 任务运行。
   + 将 `ECS_PROMETHEUS_EXPORTER_PORT` 设置为指向公开 Prometheus 指标的 containerPort。
   + 将 `Java_EMF_Metrics` 设置为 `true`。CloudWatch 代理使用此标志在日志事件中生成嵌入的指标格式。

   以下是示例：

   ```
   {
     "family": "workload-java-ec2-bridge",
     "taskRoleArn": "{{task-role-arn}}",
     "executionRoleArn": "{{execution-role-arn}}",
     "networkMode": "bridge",
     "containerDefinitions": [
       {
         "name": "tomcat-prometheus-workload-java-ec2-bridge-dynamic-port",
         "image": "your_docker_image_tag_for_tomcat_with_prometheus_metrics",
         "portMappings": [
           {
             "hostPort": 0,
             "protocol": "tcp",
             "containerPort": 9404
           }
         ],
         "dockerLabels": {
           "ECS_PROMETHEUS_EXPORTER_PORT": "9404",
           "Java_EMF_Metrics": "true"
         }
       }
     ],
     "requiresCompatibilities": [
       "EC2"  ],
     "cpu": "256",
     "memory": "512"
     }
   ```

CloudFormation 模板中 CloudWatch 代理的默认设置同时启用基于 docker 标签的服务发现和基于任务定义 ARN 的服务发现。要查看这些默认设置，请参阅 [CloudWatch 代理 YAML 配置文件](https://github.com/aws-samples/amazon-cloudwatch-container-insights/blob/latest/ecs-task-definition-templates/deployment-mode/replica-service/cwagent-prometheus/cloudformation-quickstart/cwagent-ecs-prometheus-metric-for-bridge-host.yaml#L65)的第 65 行。带有 `ECS_PROMETHEUS_EXPORTER_PORT` 标签的容器将根据 Prometheus 抓取的指定容器端口自动发现。

CloudWatch 代理的默认设置在同一文件的第 112 行也有 Java/JMX `metric_declaration` 设置。目标容器的所有 docker 标签将作为附加标签添加到 Prometheus 指标中并发送到 CloudWatch Logs。对于带有 docker 标签 `Java_EMF_Metrics=“true”` 的 Java/JMX 容器，将生成嵌入式指标格式。

# Amazon ECS 集群的示例 NGINX 工作负载
<a name="ContainerInsights-Prometheus-Setup-nginx-ecs"></a>

NGINX Prometheus 导出器可以抓取和公开 NGINX 数据作为 Prometheus 指标。此示例将导出器与适用于 Amazon ECS 的 NGINX 反向代理服务结合使用。

有关 NGINX Prometheus 导出器的更多信息，请参阅 Github 上的 [nginx-prometheus-exporter](https://github.com/nginxinc/nginx-prometheus-exporter)。有关 NGINX 反向代理的更多信息，请参阅 Github 上的 [ecs-nginx-reverse-proxy](https://github.com/awslabs/ecs-nginx-reverse-proxy)。

支持 Prometheus 的 CloudWatch 代理根据 Amazon ECS 集群中的服务发现配置抓取 NGINX Prometheus 指标。您可以将 NGINX Prometheus Exporter 配置为在不同端口或路径上公开指标。如果您更改端口或路径，请更新 CloudWatch 代理配置文件中的 `ecs_service_discovery` 部分。

## 为 Amazon ECS 集群安装 NGINX 反向代理示例工作负载
<a name="ContainerInsights-Prometheus-nginx-ecs-setup"></a>

按照以下步骤安装 NGINX 反向代理示例工作负载。

### 创建 Docker 镜像
<a name="ContainerInsights-Prometheus-nginx-ecs-setup-docker"></a>

**为 NGINX 反向代理示例工作负载创建 Docker 镜像**

1. 从 NGINX 反向代理存储库下载以下文件夹：[https://github.com/awslabs/ecs-nginx-reverse-proxy/tree/master/reverse-proxy/](https://github.com/awslabs/ecs-nginx-reverse-proxy/tree/master/reverse-proxy/)。

1. 查找 `app` 目录并从该目录构建镜像：

   ```
   docker build -t web-server-app ./path-to-app-directory
   ```

1. 为 NGINX 构建自定义镜像。首先，创建一个包含以下两个文件的目录：
   + 示例 Dockerfile：

     ```
     FROM nginx
     COPY nginx.conf /etc/nginx/nginx.conf
     ```
   + 一个 `nginx.conf` 文件，修改自 [https://github.com/awslabs/ecs-nginx-reverse-proxy/tree/master/reverse-proxy/](https://github.com/awslabs/ecs-nginx-reverse-proxy/tree/master/reverse-proxy/)：

     ```
     events {
       worker_connections 768;
     }
     
     http {
       # Nginx will handle gzip compression of responses from the app server
       gzip on;
       gzip_proxied any;
       gzip_types text/plain application/json;
       gzip_min_length 1000;
     
       server{
         listen 8080;
         location /stub_status {
             stub_status   on;
         }
       }
     
       server {
         listen 80;
     
         # Nginx will reject anything not matching /api
         location /api {
           # Reject requests with unsupported HTTP method
           if ($request_method !~ ^(GET|POST|HEAD|OPTIONS|PUT|DELETE)$) {
             return 405;
           }
     
           # Only requests matching the whitelist expectations will
           # get sent to the application server
           proxy_pass http://app:3000;
           proxy_http_version 1.1;
           proxy_set_header Upgrade $http_upgrade;
           proxy_set_header Connection 'upgrade';
           proxy_set_header Host $host;
           proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
           proxy_cache_bypass $http_upgrade;
         }
       }
     }
     ```
**注意**  
`stub_status` 必须在将 `nginx-prometheus-exporter` 配置为从中抓取指标的同一端口上启用。在我们的示例任务定义中，将 `nginx-prometheus-exporter` 配置为从端口 8080 抓取指标。

1. 从新目录中的文件构建镜像：

   ```
   docker build -t nginx-reverse-proxy ./path-to-your-directory
   ```

1. 将新镜像上传到镜像存储库以供日后使用。

### 创建任务定义以在 Amazon ECS 中运行 NGINX 和 web 服务器应用程序
<a name="ContainerInsights-Prometheus-nginx-ecs-setup-task"></a>

接下来，设置任务定义。

此任务定义启用 NGINX Prometheus 指标的收集和导出。NGINX 容器跟踪来自应用程序的输入，并将该数据公开到端口 8080，如 `nginx.conf` 中所设置。NGINX prometheus 导出器容器抓取这些指标，并将其发布到端口 9113，以在 CloudWatch 中使用。

**为 NGINX 示例 Amazon ECS 工作负载设置任务定义**

1. 使用以下内容创建任务定义 JSON 文件。将 *your-customized-nginx-iamge* 替换为您自定义的 NGINX 镜像的镜像 URI，并将 *your-web-server-app-image* 替换为您 web 服务器应用程序镜像的镜像 URI。

   ```
   {
     "containerDefinitions": [
       {
         "name": "nginx",
         "image": "your-customized-nginx-image",
         "memory": 256,
         "cpu": 256,
         "essential": true,
         "portMappings": [
           {
             "containerPort": 80,
             "protocol": "tcp"
           }
         ],
         "links": [
           "app"
         ]
       },
       {
         "name": "app",
         "image": "your-web-server-app-image",
         "memory": 256,
         "cpu": 256,
         "essential": true
       },
       {
         "name": "nginx-prometheus-exporter",
         "image": "docker.io/nginx/nginx-prometheus-exporter:0.8.0",
         "memory": 256,
         "cpu": 256,
         "essential": true,
         "command": [
           "-nginx.scrape-uri",
           "http://nginx:8080/stub_status"
       ],
       "links":[
         "nginx"
       ],
         "portMappings":[
           {
             "containerPort": 9113,
             "protocol": "tcp"
           }
         ]
       }
     ],
     "networkMode": "bridge",
     "placementConstraints": [],
     "family": "nginx-sample-stack"
   }
   ```

1. 使用以下命令注册任务定义。

   ```
   aws ecs register-task-definition --cli-input-json file://path-to-your-task-definition-json
   ```

1. 通过输入以下命令创建服务以运行任务：

   确保不要更改服务名称。我们将使用配置来运行 CloudWatch 代理服务，该配置使用启动它们的服务的名称模式来搜索任务。例如，要让 CloudWatch 代理查找此命令启动的任务，您可以将 `sd_service_name_pattern` 的值指定为 `^nginx-service$`。下一部分将提供更多详细信息。

   ```
   aws ecs create-service \
    --cluster your-cluster-name \
    --service-name nginx-service \
    --task-definition nginx-sample-stack:1 \
    --desired-count 1
   ```

### 配置 CloudWatch 代理以抓取 NGINX Prometheus 指标
<a name="ContainerInsights-Prometheus-nginx-ecs-setup-agent"></a>

最后一步是配置 CloudWatch 代理以抓取 NGINX 指标。在此示例中，CloudWatch 代理通过服务名称模式和端口 9113 发现任务，导出器在该端口公开 NGINX 的 prometheus 指标。发现任务且指标可用后，CloudWatch 代理开始将收集的指标发布到日志流 **nginx-prometheus-exporter**。

**配置 CloudWatch 代理以抓取 NGINX 指标**

1. 通过输入以下命令，下载必要 YAML 文件的最新版本。

   ```
   curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/ecs-task-definition-templates/deployment-mode/replica-service/cwagent-prometheus/cloudformation-quickstart/cwagent-ecs-prometheus-metric-for-bridge-host.yaml
   ```

1. 使用文本编辑器打开文件，然后在 `resource:CWAgentConfigSSMParameter` 部分的 `value` 密钥中查找完整的 CloudWatch 代理配置。然后，在 `ecs_service_discovery` 部分中，添加以下 `service_name_list_for_tasks` 部分。

   ```
   "service_name_list_for_tasks": [
     {
       "sd_job_name": "nginx-prometheus-exporter",
       "sd_metrics_path": "/metrics",
       "sd_metrics_ports": "9113",
       "sd_service_name_pattern": "^nginx-service$"
      }
   ],
   ```

1. 在同一文件中，在 `metric_declaration` 部分中添加以下部分以允许 NGINX 指标。请务必遵循现有的缩进模式。

   ```
   {
     "source_labels": ["job"],
     "label_matcher": ".*nginx.*",
     "dimensions": [["ClusterName", "TaskDefinitionFamily", "ServiceName"]],
     "metric_selectors": [
       "^nginx_.*$"
     ]
   },
   ```

1. 如果您尚未在此集群中部署 CloudWatch 代理，请跳至步骤 8。

   如果您已经使用 AWS CloudFormation 将 CloudWatch 代理部署在 Amazon ECS 集群中，您可以通过输入以下命令来创建更改集：

   ```
   ECS_CLUSTER_NAME=your_cluster_name
   AWS_REGION=your_aws_region
   ECS_NETWORK_MODE=bridge
   CREATE_IAM_ROLES=True
   ECS_TASK_ROLE_NAME=your_selected_ecs_task_role_name
   ECS_EXECUTION_ROLE_NAME=your_selected_ecs_execution_role_name
   
   aws cloudformation create-change-set --stack-name CWAgent-Prometheus-ECS-${ECS_CLUSTER_NAME}-EC2-${ECS_NETWORK_MODE} \
       --template-body file://cwagent-ecs-prometheus-metric-for-bridge-host.yaml \
       --parameters ParameterKey=ECSClusterName,ParameterValue=$ECS_CLUSTER_NAME \
                    ParameterKey=CreateIAMRoles,ParameterValue=$CREATE_IAM_ROLES \
                    ParameterKey=ECSNetworkMode,ParameterValue=$ECS_NETWORK_MODE \
                    ParameterKey=TaskRoleName,ParameterValue=$ECS_TASK_ROLE_NAME \
                    ParameterKey=ExecutionRoleName,ParameterValue=$ECS_EXECUTION_ROLE_NAME \
       --capabilities CAPABILITY_NAMED_IAM \
       --region $AWS_REGION \
       --change-set-name nginx-scraping-support
   ```

1. 通过以下网址打开 CloudFormation 控制台：[https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/)。

1. 查看新创建的变更集 **nginx-scraping-support**。您会看到一项应用于 **CWAgentConfigSSMParameter** 资源的更改。通过输入以下命令，运行变更集并重新启动 CloudWatch 代理任务：

   ```
   aws ecs update-service --cluster $ECS_CLUSTER_NAME \
   --desired-count 0 \
   --service cwagent-prometheus-replica-service-EC2-$ECS_NETWORK_MODE \
   --region $AWS_REGION
   ```

1. 等待大约 10 秒，然后输入以下命令。

   ```
   aws ecs update-service --cluster $ECS_CLUSTER_NAME \
   --desired-count 1 \
   --service cwagent-prometheus-replica-service-EC2-$ECS_NETWORK_MODE \
   --region $AWS_REGION
   ```

1. 如果您是首次在集群上安装带有 Prometheus 指标收集功能的 CloudWatch 代理，请输入以下命令。

   ```
   ECS_CLUSTER_NAME=your_cluster_name
   AWS_REGION=your_aws_region
   ECS_NETWORK_MODE=bridge
   CREATE_IAM_ROLES=True
   ECS_TASK_ROLE_NAME=your_selected_ecs_task_role_name
   ECS_EXECUTION_ROLE_NAME=your_selected_ecs_execution_role_name
   
   aws cloudformation create-stack --stack-name CWAgent-Prometheus-ECS-${ECS_CLUSTER_NAME}-EC2-${ECS_NETWORK_MODE} \
       --template-body file://cwagent-ecs-prometheus-metric-for-bridge-host.yaml \
       --parameters ParameterKey=ECSClusterName,ParameterValue=$ECS_CLUSTER_NAME \
                    ParameterKey=CreateIAMRoles,ParameterValue=$CREATE_IAM_ROLES \
                    ParameterKey=ECSNetworkMode,ParameterValue=$ECS_NETWORK_MODE \
                    ParameterKey=TaskRoleName,ParameterValue=$ECS_TASK_ROLE_NAME \
                    ParameterKey=ExecutionRoleName,ParameterValue=$ECS_EXECUTION_ROLE_NAME \
       --capabilities CAPABILITY_NAMED_IAM \
       --region $AWS_REGION
   ```

## 查看您的 NGINX 指标和日志
<a name="ContainerInsights-Prometheus-Setup-nginx-view"></a>

您现在可以查看正在收集的 NGINX 指标。

**查看示例 NGINX 工作负载的指标**

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 在运行集群的区域中，选择左侧导航窗格中的 **Metrics（指标）**。查找 **ContainerInsights/Prometheus** 命名空间以查看指标。

1. 要查看 CloudWatch Logs 事件，请在导航窗格中选择 **Log groups（日志组）**。这些事件位于日志流 *nginx-prometheus-exporter* 中的日志组 **/aws/containerinsights/*your\$1cluster\$1name*/prometheus** 中。

# Amazon ECS 集群的示例 NGINX Plus 工作负载
<a name="ContainerInsights-Prometheus-Setup-nginx-plus-ecs"></a>

NGINX Plus 是 NGINX 的商业版本。您必须拥有许可证方可使用它。有关更多信息，请参阅 [NGINX Plus](https://www.nginx.com/products/nginx/)

NGINX Prometheus 导出器可以抓取和公开 NGINX 数据作为 Prometheus 指标。此示例将导出器与适用于 Amazon ECS 的 NGINX Plus 反向代理服务结合使用。

有关 NGINX Prometheus 导出器的更多信息，请参阅 Github 上的 [nginx-prometheus-exporter](https://github.com/nginxinc/nginx-prometheus-exporter)。有关 NGINX 反向代理的更多信息，请参阅 Github 上的 [ecs-nginx-reverse-proxy](https://github.com/awslabs/ecs-nginx-reverse-proxy)。

支持 Prometheus 的 CloudWatch 代理根据 Amazon ECS 集群中的服务发现配置抓取 NGINX Plus Prometheus 指标。您可以将 NGINX Prometheus Exporter 配置为在不同端口或路径上公开指标。如果您更改端口或路径，请更新 CloudWatch 代理配置文件中的 `ecs_service_discovery` 部分。

## 为 Amazon ECS 集群安装 NGINX Plus 反向代理示例工作负载
<a name="ContainerInsights-Prometheus-nginx-plus-ecs-setup"></a>

按照以下步骤安装 NGINX 反向代理示例工作负载。

### 创建 Docker 镜像
<a name="ContainerInsights-Prometheus-nginx-plus-ecs-setup-docker"></a>

**为 NGINX Plus 反向代理示例工作负载创建 Docker 镜像**

1. 从 NGINX 反向代理存储库下载以下文件夹：[https://github.com/awslabs/ecs-nginx-reverse-proxy/tree/master/reverse-proxy/](https://github.com/awslabs/ecs-nginx-reverse-proxy/tree/master/reverse-proxy/)。

1. 查找 `app` 目录并从该目录构建镜像：

   ```
   docker build -t web-server-app ./path-to-app-directory
   ```

1. 为 NGINX Plus 构建自定义镜像。在为 NGINX Plus 构建镜像之前，您需要为您的 NGINX Plus 许可获取名为 `nginx-repo.key` 的密钥和 SSL 证书 `nginx-repo.crt`。创建目录并将您的 `nginx-repo.key` 和 `nginx-repo.crt` 文件存储在其中。

   在刚刚创建的目录中，创建以下两个文件：
   + 使用以下内容创建示例 Dockerfile。此 docker 文件取自 [https://docs.nginx.com/nginx/admin-guide/installing-nginx/installing-nginx-docker/\$1docker\$1plus\$1image](https://docs.nginx.com/nginx/admin-guide/installing-nginx/installing-nginx-docker/#docker_plus_image) 上提供的示例文件。我们所做的重要更改是我们加载了一个名为 `nginx.conf` 的单独文件，该文件将在下一步中创建。

     ```
     FROM debian:buster-slim
     
     LABEL maintainer="NGINX Docker Maintainers <docker-maint@nginx.com>“
     
     # Define NGINX versions for NGINX Plus and NGINX Plus modules
     # Uncomment this block and the versioned nginxPackages block in the main RUN
     # instruction to install a specific release
     # ENV NGINX_VERSION 21
     # ENV NJS_VERSION 0.3.9
     # ENV PKG_RELEASE 1~buster
     
     # Download certificate and key from the customer portal (https://cs.nginx.com (https://cs.nginx.com/))
     # and copy to the build context
     COPY nginx-repo.crt /etc/ssl/nginx/
     COPY nginx-repo.key /etc/ssl/nginx/
     # COPY nginx.conf /etc/ssl/nginx/nginx.conf
     
     RUN set -x \
     # Create nginx user/group first, to be consistent throughout Docker variants
     && addgroup --system --gid 101 nginx \
     && adduser --system --disabled-login --ingroup nginx --no-create-home --home /nonexistent --gecos "nginx user" --shell /bin/false --uid 101 nginx \
     && apt-get update \
     && apt-get install --no-install-recommends --no-install-suggests -y ca-certificates gnupg1 \
     && \
     NGINX_GPGKEY=573BFD6B3D8FBC641079A6ABABF5BD827BD9BF62; \
     found=''; \
     for server in \
     ha.pool.sks-keyservers.net (http://ha.pool.sks-keyservers.net/) \
     hkp://keyserver.ubuntu.com:80 \
     hkp://p80.pool.sks-keyservers.net:80 \
     pgp.mit.edu (http://pgp.mit.edu/) \
     ; do \
     echo "Fetching GPG key $NGINX_GPGKEY from $server"; \
     apt-key adv --keyserver "$server" --keyserver-options timeout=10 --recv-keys "$NGINX_GPGKEY" && found=yes && break; \
     done; \
     test -z "$found" && echo >&2 "error: failed to fetch GPG key $NGINX_GPGKEY" && exit 1; \
     apt-get remove --purge --auto-remove -y gnupg1 && rm -rf /var/lib/apt/lists/* \
     # Install the latest release of NGINX Plus and/or NGINX Plus modules
     # Uncomment individual modules if necessary
     # Use versioned packages over defaults to specify a release
     && nginxPackages=" \
     nginx-plus \
     # nginx-plus=${NGINX_VERSION}-${PKG_RELEASE} \
     # nginx-plus-module-xslt \
     # nginx-plus-module-xslt=${NGINX_VERSION}-${PKG_RELEASE} \
     # nginx-plus-module-geoip \
     # nginx-plus-module-geoip=${NGINX_VERSION}-${PKG_RELEASE} \
     # nginx-plus-module-image-filter \
     # nginx-plus-module-image-filter=${NGINX_VERSION}-${PKG_RELEASE} \
     # nginx-plus-module-perl \
     # nginx-plus-module-perl=${NGINX_VERSION}-${PKG_RELEASE} \
     # nginx-plus-module-njs \
     # nginx-plus-module-njs=${NGINX_VERSION}+${NJS_VERSION}-${PKG_RELEASE} \
     " \
     && echo "Acquire::https::plus-pkgs.nginx.com::Verify-Peer \"true\";" >> /etc/apt/apt.conf.d/90nginx \
     && echo "Acquire::https::plus-pkgs.nginx.com::Verify-Host \"true\";" >> /etc/apt/apt.conf.d/90nginx \
     && echo "Acquire::https::plus-pkgs.nginx.com::SslCert \"/etc/ssl/nginx/nginx-repo.crt\";" >> /etc/apt/apt.conf.d/90nginx \
     && echo "Acquire::https::plus-pkgs.nginx.com::SslKey \"/etc/ssl/nginx/nginx-repo.key\";" >> /etc/apt/apt.conf.d/90nginx \
     && printf "deb https://plus-pkgs.nginx.com/debian buster nginx-plus\n" > /etc/apt/sources.list.d/nginx-plus.list \
     && apt-get update \
     && apt-get install --no-install-recommends --no-install-suggests -y \
     $nginxPackages \
     gettext-base \
     curl \
     && apt-get remove --purge --auto-remove -y && rm -rf /var/lib/apt/lists/* /etc/apt/sources.list.d/nginx-plus.list \
     && rm -rf /etc/apt/apt.conf.d/90nginx /etc/ssl/nginx
     
     # Forward request logs to Docker log collector
     RUN ln -sf /dev/stdout /var/log/nginx/access.log \
     && ln -sf /dev/stderr /var/log/nginx/error.log
     
     COPY nginx.conf /etc/nginx/nginx.conf
     
     EXPOSE 80
     
     STOPSIGNAL SIGTERM
     
     CMD ["nginx", "-g", "daemon off;"]
     ```
   + 一个修改自 [ https://github.com/awslabs/ecs-nginx-reverse-proxy/tree/master/reverse-proxy/nginx](https://github.com/awslabs/ecs-nginx-reverse-proxy/tree/master/reverse-proxy/nginx) 的 `nginx.conf` 文件。

     ```
     events {
       worker_connections 768;
     }
     
     http {
       # Nginx will handle gzip compression of responses from the app server
       gzip on;
       gzip_proxied any;
       gzip_types text/plain application/json;
       gzip_min_length 1000;
     
       upstream backend {
         zone name 10m;
         server app:3000    weight=2;
         server app2:3000    weight=1;
       }
     
       server{
         listen 8080;
         location /api {
           api write=on;
         }
       }
     
       match server_ok {
         status 100-599;
       }
     
       server {
         listen 80;
         status_zone zone;
         # Nginx will reject anything not matching /api
         location /api {
           # Reject requests with unsupported HTTP method
           if ($request_method !~ ^(GET|POST|HEAD|OPTIONS|PUT|DELETE)$) {
             return 405;
           }
     
           # Only requests matching the whitelist expectations will
           # get sent to the application server
           proxy_pass http://backend;
           health_check uri=/lorem-ipsum match=server_ok;
           proxy_http_version 1.1;
           proxy_set_header Upgrade $http_upgrade;
           proxy_set_header Connection 'upgrade';
           proxy_set_header Host $host;
           proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
           proxy_cache_bypass $http_upgrade;
         }
       }
     }
     ```

1. 从新目录中的文件构建镜像：

   ```
   docker build -t nginx-plus-reverse-proxy ./path-to-your-directory
   ```

1. 将新镜像上传到镜像存储库以供日后使用。

### 创建任务定义以在 Amazon ECS 中运行 NGINX Plus 和 web 服务器应用程序
<a name="ContainerInsights-Prometheus-nginx-plus-ecs-setup-task"></a>

接下来，设置任务定义。

此任务定义启用 NGINX Plus Prometheus 指标的收集和导出。NGINX 容器跟踪来自应用程序的输入，并将该数据公开到端口 8080，如 `nginx.conf` 中所设置。NGINX prometheus 导出器容器抓取这些指标，并将其发布到端口 9113，以在 CloudWatch 中使用。

**为 NGINX 示例 Amazon ECS 工作负载设置任务定义**

1. 使用以下内容创建任务定义 JSON 文件。将 *your-customized-nginx-plus-image* 替换为自定义 NGINX Plus 镜像的镜像 URI，并将 *your-web-server-app-image* 替换为 Web 服务器应用程序镜像的镜像 URI。

   ```
   {
     "containerDefinitions": [
       {
         "name": "nginx",
         "image": "your-customized-nginx-plus-image",
         "memory": 256,
         "cpu": 256,
         "essential": true,
         "portMappings": [
           {
             "containerPort": 80,
             "protocol": "tcp"
           }
         ],
         "links": [
           "app",
           "app2"
         ]
       },
       {
         "name": "app",
         "image": "your-web-server-app-image",
         "memory": 256,
         "cpu": 128,
         "essential": true
       },
       {
         "name": "app2",
         "image": "your-web-server-app-image",
         "memory": 256,
         "cpu": 128,
         "essential": true
       },
       {
         "name": "nginx-prometheus-exporter",
         "image": "docker.io/nginx/nginx-prometheus-exporter:0.8.0",
         "memory": 256,
         "cpu": 256,
         "essential": true,
         "command": [
           "-nginx.plus",
           "-nginx.scrape-uri",
            "http://nginx:8080/api"
       ],
       "links":[
         "nginx"
       ],
         "portMappings":[
           {
             "containerPort": 9113,
             "protocol": "tcp"
           }
         ]
       }
     ],
     "networkMode": "bridge",
     "placementConstraints": [],
     "family": "nginx-plus-sample-stack"
   }
   ```

1. 注册任务定义：

   ```
   aws ecs register-task-definition --cli-input-json file://path-to-your-task-definition-json
   ```

1. 通过输入以下命令创建服务以运行任务：

   ```
   aws ecs create-service \
    --cluster your-cluster-name \
    --service-name nginx-plus-service \
    --task-definition nginx-plus-sample-stack:1 \
    --desired-count 1
   ```

   确保不要更改服务名称。我们将使用配置来运行 CloudWatch 代理服务，该配置使用启动它们的服务的名称模式来搜索任务。例如，要让 CloudWatch 代理查找此命令启动的任务，您可以将 `sd_service_name_pattern` 的值指定为 `^nginx-plus-service$`。下一部分将提供更多详细信息。

### 配置 CloudWatch 代理以抓取 NGINX Plus Prometheus 指标
<a name="ContainerInsights-Prometheus-nginx-plus-ecs-setup-agent"></a>

最后一步是配置 CloudWatch 代理以抓取 NGINX 指标。在此示例中，CloudWatch 代理通过服务名称模式和端口 9113 发现任务，导出器在该端口公开 NGINX 的 prometheus 指标。发现任务且指标可用后，CloudWatch 代理开始将收集的指标发布到日志流 **nginx-prometheus-exporter**。

**配置 CloudWatch 代理以抓取 NGINX 指标**

1. 通过输入以下命令，下载必要 YAML 文件的最新版本。

   ```
   curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/ecs-task-definition-templates/deployment-mode/replica-service/cwagent-prometheus/cloudformation-quickstart/cwagent-ecs-prometheus-metric-for-bridge-host.yaml
   ```

1. 使用文本编辑器打开文件，然后在 `resource:CWAgentConfigSSMParameter` 部分的 `value` 密钥中查找完整的 CloudWatch 代理配置。然后，在 `ecs_service_discovery` 部分中，添加以下 `service_name_list_for_tasks` 部分。

   ```
   "service_name_list_for_tasks": [
     {
       "sd_job_name": "nginx-plus-prometheus-exporter",
       "sd_metrics_path": "/metrics",
       "sd_metrics_ports": "9113",
       "sd_service_name_pattern": "^nginx-plus.*"
      }
   ],
   ```

1. 在同一个文件中，在 `metric_declaration` 的部分中添加以下部分，以允许 NGINX Plus 指标。请务必遵循现有的缩进模式。

   ```
   {
     "source_labels": ["job"],
     "label_matcher": "^nginx-plus.*",
     "dimensions": [["ClusterName", "TaskDefinitionFamily", "ServiceName"]],
     "metric_selectors": [
       "^nginxplus_connections_accepted$",
       "^nginxplus_connections_active$",
       "^nginxplus_connections_dropped$",
       "^nginxplus_connections_idle$",
       "^nginxplus_http_requests_total$",
       "^nginxplus_ssl_handshakes$",
       "^nginxplus_ssl_handshakes_failed$",
       "^nginxplus_up$",
       "^nginxplus_upstream_server_health_checks_fails$"
     ]
   },
   {
     "source_labels": ["job"],
     "label_matcher": "^nginx-plus.*",
     "dimensions": [["ClusterName", "TaskDefinitionFamily", "ServiceName", "upstream"]],
     "metric_selectors": [
       "^nginxplus_upstream_server_response_time$"
     ]
   },
   {
     "source_labels": ["job"],
     "label_matcher": "^nginx-plus.*",
     "dimensions": [["ClusterName", "TaskDefinitionFamily", "ServiceName", "code"]],
     "metric_selectors": [
       "^nginxplus_upstream_server_responses$",
       "^nginxplus_server_zone_responses$"
     ]
   },
   ```

1. 如果您尚未在此集群中部署 CloudWatch 代理，请跳至步骤 8。

   如果您已经使用 AWS CloudFormation 将 CloudWatch 代理部署在 Amazon ECS 集群中，您可以通过输入以下命令来创建更改集：

   ```
   ECS_CLUSTER_NAME=your_cluster_name
   AWS_REGION=your_aws_region
   ECS_NETWORK_MODE=bridge
   CREATE_IAM_ROLES=True
   ECS_TASK_ROLE_NAME=your_selected_ecs_task_role_name
   ECS_EXECUTION_ROLE_NAME=your_selected_ecs_execution_role_name
   
   aws cloudformation create-change-set --stack-name CWAgent-Prometheus-ECS-${ECS_CLUSTER_NAME}-EC2-${ECS_NETWORK_MODE} \
       --template-body file://cwagent-ecs-prometheus-metric-for-bridge-host.yaml \
       --parameters ParameterKey=ECSClusterName,ParameterValue=$ECS_CLUSTER_NAME \
                    ParameterKey=CreateIAMRoles,ParameterValue=$CREATE_IAM_ROLES \
                    ParameterKey=ECSNetworkMode,ParameterValue=$ECS_NETWORK_MODE \
                    ParameterKey=TaskRoleName,ParameterValue=$ECS_TASK_ROLE_NAME \
                    ParameterKey=ExecutionRoleName,ParameterValue=$ECS_EXECUTION_ROLE_NAME \
       --capabilities CAPABILITY_NAMED_IAM \
       --region $AWS_REGION \
       --change-set-name nginx-plus-scraping-support
   ```

1. 通过以下网址打开 CloudFormation 控制台：[https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/)。

1. 查看新创建的变更集 **nginx-plus-scraping-support**。您会看到一项应用于 **CWAgentConfigSSMParameter** 资源的更改。通过输入以下命令，运行变更集并重新启动 CloudWatch 代理任务：

   ```
   aws ecs update-service --cluster $ECS_CLUSTER_NAME \
   --desired-count 0 \
   --service cwagent-prometheus-replica-service-EC2-$ECS_NETWORK_MODE \
   --region $AWS_REGION
   ```

1. 等待大约 10 秒，然后输入以下命令。

   ```
   aws ecs update-service --cluster $ECS_CLUSTER_NAME \
   --desired-count 1 \
   --service cwagent-prometheus-replica-service-EC2-$ECS_NETWORK_MODE \
   --region $AWS_REGION
   ```

1. 如果您是首次在集群上安装带有 Prometheus 指标收集功能的 CloudWatch 代理，请输入以下命令。

   ```
   ECS_CLUSTER_NAME=your_cluster_name
   AWS_REGION=your_aws_region
   ECS_NETWORK_MODE=bridge
   CREATE_IAM_ROLES=True
   ECS_TASK_ROLE_NAME=your_selected_ecs_task_role_name
   ECS_EXECUTION_ROLE_NAME=your_selected_ecs_execution_role_name
   
   aws cloudformation create-stack --stack-name CWAgent-Prometheus-ECS-${ECS_CLUSTER_NAME}-EC2-${ECS_NETWORK_MODE} \
       --template-body file://cwagent-ecs-prometheus-metric-for-bridge-host.yaml \
       --parameters ParameterKey=ECSClusterName,ParameterValue=$ECS_CLUSTER_NAME \
                    ParameterKey=CreateIAMRoles,ParameterValue=$CREATE_IAM_ROLES \
                    ParameterKey=ECSNetworkMode,ParameterValue=$ECS_NETWORK_MODE \
                    ParameterKey=TaskRoleName,ParameterValue=$ECS_TASK_ROLE_NAME \
                    ParameterKey=ExecutionRoleName,ParameterValue=$ECS_EXECUTION_ROLE_NAME \
       --capabilities CAPABILITY_NAMED_IAM \
       --region $AWS_REGION
   ```

## 查看您的 NGINX Plus 指标和日志
<a name="ContainerInsights-Prometheus-Setup-nginx-plus-view"></a>

您现在可以查看正在收集的 NGINX Plus 指标。

**查看示例 NGINX 工作负载的指标**

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 在运行集群的区域中，选择左侧导航窗格中的 **Metrics（指标）**。查找 **ContainerInsights/Prometheus** 命名空间以查看指标。

1. 要查看 CloudWatch Logs 事件，请在导航窗格中选择 **Log groups（日志组）**。事件位于日志流 *nginx-plus-prometheus-exporter* 中的日志组 **/aws/containerinsights/*your\$1cluster\$1name*/prometheus** 中。

# 添加新 Prometheus 抓取目标的教程：Amazon ECS 上的 Memcached
<a name="ContainerInsights-Prometheus-Setup-memcached-ecs"></a>

本教程提供实践介绍，关于如何在 Amazon ECS 集群上使用 EC2 启动类型抓取示例 Memcached 应用程序的 Prometheus 指标。Memcached Prometheus 导出器目标将由 CloudWatch 代理通过基于 ECS 任务定义的服务发现自动发现。

Memcached 是一个通用型分布式内存缓存系统。它通常用于通过在 RAM 中缓存数据和对象来加速动态数据库驱动的网站，以减少必须读取的外部数据源（例如数据库或 API）的次数。有关更多信息，请参阅[什么是 Memcached？](https://www.memcached.org/)

[memchached\$1exporter](https://github.com/prometheus/memcached_exporter)（Apache 许可证 2.0）是 Prometheus 一款官方导出器。默认情况下，memcache\$1exporter 在 `/metrics.` 的端口 0.0.0.0:9150 上提供服务

本教程使用了以下两个 Docker Hub 存储库中的 Docker 镜像：
+ [ Memcached](https://hub.docker.com/_/memcached?tab=description)
+ [prom/memcached-exporter](https://hub.docker.com/r/prom/memcached-exporter/)

**先决条件**

要从 Amazon ECS 的示例 Prometheus 工作负载收集指标，您必须在集群中运行 Container Insights。有关安装 Container Insights 的信息，请参阅 [在 Amazon ECS 上设置 Container Insights](deploy-container-insights-ECS.md)。

**Topics**
+ [设置 Amazon ECS EC2 集群环境变量](#ContainerInsights-Prometheus-Setup-memcached-ecs-environment)
+ [安装 Memcached 示例工作负载](#ContainerInsights-Prometheus-Setup-memcached-ecs-install-workload)
+ [配置 CloudWatch 代理以抓取 Memcached Prometheus 指标](#ContainerInsights-Prometheus-Setup-memcached-ecs-agent)
+ [查看您的 Memcached 指标](#ContainerInsights-Prometheus-ECS-memcached-view)

## 设置 Amazon ECS EC2 集群环境变量
<a name="ContainerInsights-Prometheus-Setup-memcached-ecs-environment"></a>

**设置 Amazon ECS EC2 集群环境变量**

1. 请安装 Amazon ECS CLI（如果尚未安装）。有关更多信息，请参阅[安装 Amazon ECS CLI](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_CLI_installation.html)。

1. 设置新的 Amazon ECS 集群名称和区域。例如：

   ```
   ECS_CLUSTER_NAME=ecs-ec2-memcached-tutorial
   AWS_DEFAULT_REGION=ca-central-1
   ```

1. （可选）如果您还没有要在其中安装示例 Memcached 工作负载和 CloudWatch 代理的、带有 EC2 启动类型的 Amazon ECS 集群，您可以通过输入以下命令来创建一个。

   ```
   ecs-cli up --capability-iam --size 1 \
   --instance-type t3.medium \
   --cluster $ECS_CLUSTER_NAME \
   --region $AWS_REGION
   ```

   此命令的预期结果如下所示：

   ```
   WARN[0000] You will not be able to SSH into your EC2 instances without a key pair. 
   INFO[0000] Using recommended Amazon Linux 2 AMI with ECS Agent 1.44.4 and Docker version 19.03.6-ce 
   INFO[0001] Created cluster                               cluster=ecs-ec2-memcached-tutorial region=ca-central-1
   INFO[0002] Waiting for your cluster resources to be created... 
   INFO[0002] Cloudformation stack status                   stackStatus=CREATE_IN_PROGRESS
   INFO[0063] Cloudformation stack status                   stackStatus=CREATE_IN_PROGRESS
   INFO[0124] Cloudformation stack status                   stackStatus=CREATE_IN_PROGRESS
   VPC created: vpc-xxxxxxxxxxxxxxxxx
   Security Group created: sg-xxxxxxxxxxxxxxxxx
   Subnet created: subnet-xxxxxxxxxxxxxxxxx
   Subnet created: subnet-xxxxxxxxxxxxxxxxx
   Cluster creation succeeded.
   ```

## 安装 Memcached 示例工作负载
<a name="ContainerInsights-Prometheus-Setup-memcached-ecs-install-workload"></a>

**安装公开 Prometheus 指标的示例 Memcached 工作负载**

1. 通过输入以下命令，下载 Memcached CloudFormation 模板。

   ```
   curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/ecs-task-definition-templates/deployment-mode/replica-service/cwagent-prometheus/sample_traffic/memcached/memcached-traffic-sample.yaml
   ```

1. 通过输入以下命令，设置要为 Memcached 创建的 IAM 角色名称。

   ```
   MEMCACHED_ECS_TASK_ROLE_NAME=memcached-prometheus-demo-ecs-task-role-name
   MEMCACHED_ECS_EXECUTION_ROLE_NAME=memcached-prometheus-demo-ecs-execution-role-name
   ```

1. 通过输入以下命令，安装示例 Memcached 工作负载。此示例在 `host` 网络模式下安装工作负载。

   ```
   MEMCACHED_ECS_NETWORK_MODE=host
   
   aws cloudformation create-stack --stack-name Memcached-Prometheus-Demo-ECS-$ECS_CLUSTER_NAME-EC2-$MEMCACHED_ECS_NETWORK_MODE \
       --template-body file://memcached-traffic-sample.yaml \
       --parameters ParameterKey=ECSClusterName,ParameterValue=$ECS_CLUSTER_NAME \
                    ParameterKey=ECSNetworkMode,ParameterValue=$MEMCACHED_ECS_NETWORK_MODE \
                    ParameterKey=TaskRoleName,ParameterValue=$MEMCACHED_ECS_TASK_ROLE_NAME \
                    ParameterKey=ExecutionRoleName,ParameterValue=$MEMCACHED_ECS_EXECUTION_ROLE_NAME \
       --capabilities CAPABILITY_NAMED_IAM \
       --region $AWS_REGION
   ```

CloudFormation 堆栈创建四种资源：
+ 一个 ECS 任务角色
+ 一个 ECS 任务执行角色
+ 一个 Memcached 任务定义
+ 一项 Memcached 服务

在 Memcached 任务定义中，定义了两个容器：
+ 主容器运行一个简单的 Memcached 应用程序并打开端口 11211 以供访问。
+ 另一个容器运行 Redis OSS 导出器进程，以在端口 9150 上公开 Prometheus 指标。该容器将由 CloudWatch 代理发现和抓取。

## 配置 CloudWatch 代理以抓取 Memcached Prometheus 指标
<a name="ContainerInsights-Prometheus-Setup-memcached-ecs-agent"></a>

**配置 CloudWatch 代理以抓取 Memcached Prometheus 指标**

1. 通过输入以下命令，下载 `cwagent-ecs-prometheus-metric-for-awsvpc.yaml` 的最新版本。

   ```
   curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/ecs-task-definition-templates/deployment-mode/replica-service/cwagent-prometheus/cloudformation-quickstart/cwagent-ecs-prometheus-metric-for-awsvpc.yaml
   ```

1. 使用文本编辑器打开该文件，并在 `resource:CWAgentConfigSSMParameter` 部分中的 `value` 密钥后面查找完整的 CloudWatch 代理配置。

   然后，在 `ecs_service_discovery` 部分中，将以下配置添加到 `task_definition_list` 部分中。

   ```
   {
       "sd_job_name": "ecs-memcached",
       "sd_metrics_ports": "9150",
       "sd_task_definition_arn_pattern": ".*:task-definition/memcached-prometheus-demo.*:[0-9]+"
   },
   ```

   对于 `metric_declaration` 部分，默认设置不允许任何 Memcached 指标。添加以下部分以允许 Memcached 指标。请务必遵循现有的缩进模式。

   ```
   {
     "source_labels": ["container_name"],
     "label_matcher": "memcached-exporter-.*",
     "dimensions": [["ClusterName", "TaskDefinitionFamily"]],
     "metric_selectors": [
       "^memcached_current_(bytes|items|connections)$",
       "^memcached_items_(reclaimed|evicted)_total$",
       "^memcached_(written|read)_bytes_total$",
       "^memcached_limit_bytes$",
       "^memcached_commands_total$"
     ]
   },
   {
     "source_labels": ["container_name"],
     "label_matcher": "memcached-exporter-.*",
     "dimensions": [["ClusterName", "TaskDefinitionFamily","status","command"], ["ClusterName", "TaskDefinitionFamily","command"]],
     "metric_selectors": [
       "^memcached_commands_total$"
     ]
   },
   ```

1. 如果 CloudFormation 已在 Amazon ECS 集群中部署 CloudWatch 代理，您可以通过输入以下命令来创建更改集。

   ```
   ECS_NETWORK_MODE=bridge
   CREATE_IAM_ROLES=True
   ECS_TASK_ROLE_NAME=your_selected_ecs_task_role_name
   ECS_EXECUTION_ROLE_NAME=your_selected_ecs_execution_role_name
   
   aws cloudformation create-change-set --stack-name CWAgent-Prometheus-ECS-${ECS_CLUSTER_NAME}-EC2-${ECS_NETWORK_MODE} \
       --template-body file://cwagent-ecs-prometheus-metric-for-bridge-host.yaml \
       --parameters ParameterKey=ECSClusterName,ParameterValue=$ECS_CLUSTER_NAME \
                    ParameterKey=CreateIAMRoles,ParameterValue=$CREATE_IAM_ROLES \
                    ParameterKey=ECSNetworkMode,ParameterValue=$ECS_NETWORK_MODE \
                    ParameterKey=TaskRoleName,ParameterValue=$ECS_TASK_ROLE_NAME \
                    ParameterKey=ExecutionRoleName,ParameterValue=$ECS_EXECUTION_ROLE_NAME \
       --capabilities CAPABILITY_NAMED_IAM \
       --region $AWS_REGION \
       --change-set-name memcached-scraping-support
   ```

1. 通过以下网址打开 CloudFormation 控制台：[https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/)。

1. 查看新创建的变更集 `memcached-scraping-support`。您会看到一项应用于 `CWAgentConfigSSMParameter` 资源的更改。通过输入以下命令执行变更集并重新启动 CloudWatch 代理任务。

   ```
   aws ecs update-service --cluster $ECS_CLUSTER_NAME \
   --desired-count 0 \
   --service cwagent-prometheus-replica-service-EC2-$ECS_NETWORK_MODE \
   --region $AWS_REGION
   ```

1. 等待大约 10 秒，然后输入以下命令。

   ```
   aws ecs update-service --cluster $ECS_CLUSTER_NAME \
   --desired-count 1 \
   --service cwagent-prometheus-replica-service-EC2-$ECS_NETWORK_MODE \
   --region $AWS_REGION
   ```

1. 如果您是首次为集群安装带有 Prometheus 指标收集功能的 CloudWatch 代理，请输入以下命令：

   ```
   ECS_NETWORK_MODEE=bridge
   CREATE_IAM_ROLES=True
   ECS_TASK_ROLE_NAME=your_selected_ecs_task_role_name
   ECS_EXECUTION_ROLE_NAME=your_selected_ecs_execution_role_name
   
   aws cloudformation create-stack --stack-name CWAgent-Prometheus-ECS-${ECS_CLUSTER_NAME}-EC2-${ECS_NETWORK_MODE} \
       --template-body file://cwagent-ecs-prometheus-metric-for-bridge-host.yaml \
       --parameters ParameterKey=ECSClusterName,ParameterValue=$ECS_CLUSTER_NAME \
                    ParameterKey=CreateIAMRoles,ParameterValue=$CREATE_IAM_ROLES \
                    ParameterKey=ECSNetworkMode,ParameterValue=$ECS_NETWORK_MODE \
                    ParameterKey=TaskRoleName,ParameterValue=$ECS_TASK_ROLE_NAME \
                    ParameterKey=ExecutionRoleName,ParameterValue=$ECS_EXECUTION_ROLE_NAME \
       --capabilities CAPABILITY_NAMED_IAM \
       --region $AWS_REGION
   ```

## 查看您的 Memcached 指标
<a name="ContainerInsights-Prometheus-ECS-memcached-view"></a>

本教程会将以下指标发送到 CloudWatch 中的 **ECS/ContainerInsights/Prometheus** 命名空间。您可以使用 CloudWatch 控制台查看该命名空间中的指标。


| 指标名称 | Dimensions | 
| --- | --- | 
|  `memcached_current_items` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `memcached_current_connections` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `memcached_limit_bytes` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `memcached_current_bytes` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `memcached_written_bytes_total` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `memcached_read_bytes_total` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `memcached_items_evicted_total` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `memcached_items_reclaimed_total` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `memcached_commands_total` |  `ClusterName`, `TaskDefinitionFamily` `ClusterName`、TaskDefinitionFinitionFamy、command `ClusterName`、TaskDefinitionFamily、status、command  | 

**注意**  
**命令**维度的值可以是 `delete`、`get`、`cas`、`set`、`decr`、`touch`、`incr` 或 `flush`。  
**状态**维度的值可以是 `hit`、`miss` 或 `badval`。

您还可以为 Memcached Prometheus 指标创建 CloudWatch 控制面板。

**为 Memcached Prometheus 指标创建控制面板**

1. 创建环境变量，替换以下值以匹配部署。

   ```
   DASHBOARD_NAME=your_memcached_cw_dashboard_name
   ECS_TASK_DEF_FAMILY=memcached-prometheus-demo-$ECS_CLUSTER_NAME-EC2-$MEMCACHED_ECS_NETWORK_MOD
   ```

1. 输入以下命令以创建控制面板。

   ```
   curl https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/ecs-task-definition-templates/deployment-mode/replica-service/cwagent-prometheus/sample_cloudwatch_dashboards/memcached/cw_dashboard_memcached.json \
   | sed "s/{{YOUR_AWS_REGION}}/$AWS_REGION/g" \
   | sed "s/{{YOUR_CLUSTER_NAME}}/$ECS_CLUSTER_NAME/g" \
   | sed "s/{{YOUR_TASK_DEF_FAMILY}}/$ECS_TASK_DEF_FAMILY/g" \
   | xargs -0 aws cloudwatch put-dashboard --dashboard-name ${DASHBOARD_NAME} --region $AWS_REGION --dashboard-body
   ```

# 在 Amazon ECS Fargate 上抓取 Redis OSS Prometheus 指标的教程
<a name="ContainerInsights-Prometheus-Setup-redis-ecs"></a>

本教程提供实践介绍，关于如何在 Amazon ECS Fargate 集群中抓取示例 Redis OSS 应用程序的 Prometheus 指标。Redis OSS Prometheus 导出器目标将由 CloudWatch 代理自动发现，并根据容器的 docker 标签提供 Prometheus 指标支持。

Redis OSS（https://redis.io/）是一个开源（获得 BSD 许可）的内存数据结构存储，用作数据库、缓存和消息代理。有关更多信息，请参阅 [ redis](https://redis.io/)。

redis\$1exporter（获得 MIT 许可证）用于在指定端口（默认值：0.0.0.0:9121）上公开 Redis OSS prometheus 指标。有关更多信息，请参阅 [redis\$1exporter](https://github.com/oliver006/redis_exporter)。

本教程使用了以下两个 Docker Hub 存储库中的 Docker 镜像：
+ [redis](https://hub.docker.com/_/redis?tab=description)
+ [redis\$1exporter](https://hub.docker.com/r/oliver006/redis_exporter)

**先决条件**

要从 Amazon ECS 的示例 Prometheus 工作负载收集指标，您必须在集群中运行 Container Insights。有关安装 Container Insights 的信息，请参阅 [在 Amazon ECS 上设置 Container Insights](deploy-container-insights-ECS.md)。

**Topics**
+ [设置 Amazon ECS Fargate 集群环境变量](#ContainerInsights-Prometheus-Setup-redis-ecs-variable)
+ [为 Amazon ECS Fargate 集群设置网络环境变量](#ContainerInsights-Prometheus-Setup-redis-ecs-variable2)
+ [安装 Redis OSS 示例工作负载](#ContainerInsights-Prometheus-Setup-redis-ecs-install-workload)
+ [配置 CloudWatch 代理以抓取 Redis OSS Prometheus 指标](#ContainerInsights-Prometheus-Setup-redis-ecs-agent)
+ [查看您的 Redis OSS 指标](#ContainerInsights-Prometheus-Setup-redis-view)

## 设置 Amazon ECS Fargate 集群环境变量
<a name="ContainerInsights-Prometheus-Setup-redis-ecs-variable"></a>

**设置 Amazon ECS Fargate 集群环境变量**

1. 请安装 Amazon ECS CLI（如果尚未安装）。有关更多信息，请参阅[安装 Amazon ECS CLI](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_CLI_installation.html)。

1. 设置新的 Amazon ECS 集群名称和区域。例如：

   ```
   ECS_CLUSTER_NAME=ecs-fargate-redis-tutorial
   AWS_DEFAULT_REGION=ca-central-1
   ```

1. （可选）如果您还没有要在其中安装示例 Redis OSS 工作负载和 CloudWatch 代理的 Amazon ECS Fargate 集群，可以通过输入以下命令来创建一个。

   ```
   ecs-cli up --capability-iam \
   --cluster $ECS_CLUSTER_NAME \
   --launch-type FARGATE \
   --region $AWS_DEFAULT_REGION
   ```

   此命令的预期结果如下所示：

   ```
   INFO[0000] Created cluster   cluster=ecs-fargate-redis-tutorial region=ca-central-1
   INFO[0001] Waiting for your cluster resources to be created...
   INFO[0001] Cloudformation stack status   stackStatus=CREATE_IN_PROGRESS
   VPC created: vpc-xxxxxxxxxxxxxxxxx
   Subnet created: subnet-xxxxxxxxxxxxxxxxx
   Subnet created: subnet-xxxxxxxxxxxxxxxxx
   Cluster creation succeeded.
   ```

## 为 Amazon ECS Fargate 集群设置网络环境变量
<a name="ContainerInsights-Prometheus-Setup-redis-ecs-variable2"></a>

**为 Amazon ECS Fargate 集群设置网络环境变量**

1. 设置 Amazon ECS 集群的 VPC 和子网 ID。如果您在上一步骤中创建了新集群，您将在最终命令的结果中看到这些值。否则，请使用要与 Redis 一起使用的现有集群的 ID。

   ```
   ECS_CLUSTER_VPC=vpc-xxxxxxxxxxxxxxxxx
   ECS_CLUSTER_SUBNET_1=subnet-xxxxxxxxxxxxxxxxx
   ECS_CLUSTER_SUBNET_2=subnet-xxxxxxxxxxxxxxxxx
   ```

1. 在本教程中，我们将在 Amazon ECS 集群的 VPC 的默认安全组中安装 Redis OSS 应用程序和 CloudWatch 代理。默认安全组允许同一安全组内的所有网络连接，因此 CloudWatch 代理可以抓取 Redis OSS 容器上公开的 Prometheus 指标。在实际生产环境中，您可能希望为 Redis OSS 应用程序和 CloudWatch 代理创建专用安全组并为其设置自定义权限。

   要获取默认安全组 ID，请输入以下命令。

   ```
   aws ec2 describe-security-groups \
   --filters Name=vpc-id,Values=$ECS_CLUSTER_VPC  \
   --region $AWS_DEFAULT_REGION
   ```

   然后通过输入以下命令设置 Fargate 集群默认安全组变量，将 *my-default-security-group* 替换为您在上一个命令中找到的值。

   ```
   ECS_CLUSTER_SECURITY_GROUP=my-default-security-group
   ```

## 安装 Redis OSS 示例工作负载
<a name="ContainerInsights-Prometheus-Setup-redis-ecs-install-workload"></a>

**安装公开 Prometheus 指标的示例 Redis OSS 工作负载**

1. 通过输入以下命令，下载 Redis OSS CloudFormation 模板。

   ```
   curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/ecs-task-definition-templates/deployment-mode/replica-service/cwagent-prometheus/sample_traffic/redis/redis-traffic-sample.yaml
   ```

1. 通过输入以下命令，设置要为 Redis OSS 创建的 IAM 角色名称。

   ```
   REDIS_ECS_TASK_ROLE_NAME=redis-prometheus-demo-ecs-task-role-name
   REDIS_ECS_EXECUTION_ROLE_NAME=redis-prometheus-demo-ecs-execution-role-name
   ```

1. 通过输入以下命令安装 Redis OSS 示例工作负载。

   ```
   aws cloudformation create-stack --stack-name Redis-Prometheus-Demo-ECS-$ECS_CLUSTER_NAME-fargate-awsvpc \
       --template-body file://redis-traffic-sample.yaml \
       --parameters ParameterKey=ECSClusterName,ParameterValue=$ECS_CLUSTER_NAME \
                    ParameterKey=SecurityGroupID,ParameterValue=$ECS_CLUSTER_SECURITY_GROUP \
                    ParameterKey=SubnetID,ParameterValue=$ECS_CLUSTER_SUBNET_1 \
                    ParameterKey=TaskRoleName,ParameterValue=$REDIS_ECS_TASK_ROLE_NAME \
                    ParameterKey=ExecutionRoleName,ParameterValue=$REDIS_ECS_EXECUTION_ROLE_NAME \
       --capabilities CAPABILITY_NAMED_IAM \
       --region $AWS_DEFAULT_REGION
   ```

CloudFormation 堆栈创建四种资源：
+ 一个 ECS 任务角色
+ 一个 ECS 任务执行角色
+ 一个 Redis OSS 任务定义
+ 一项 Redis OSS 服务

在 Redis OSS 任务定义中，定义了两个容器：
+ 主容器运行一个简单的 Redis OSS 应用程序并打开端口 6379 以供访问。
+ 另一个容器运行 Redis OSS 导出器进程，以在端口 9121 上公开 Prometheus 指标。该容器将由 CloudWatch 代理发现和抓取。定义了以下 docker 标签，以便 CloudWatch 代理可以根据它发现该容器。

  ```
  ECS_PROMETHEUS_EXPORTER_PORT: 9121
  ```

## 配置 CloudWatch 代理以抓取 Redis OSS Prometheus 指标
<a name="ContainerInsights-Prometheus-Setup-redis-ecs-agent"></a>

**配置 CloudWatch 代理以抓取 Redis OSS Prometheus 指标**

1. 通过输入以下命令，下载 `cwagent-ecs-prometheus-metric-for-awsvpc.yaml` 的最新版本。

   ```
   curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/ecs-task-definition-templates/deployment-mode/replica-service/cwagent-prometheus/cloudformation-quickstart/cwagent-ecs-prometheus-metric-for-awsvpc.yaml
   ```

1. 使用文本编辑器打开该文件，并在 `resource:CWAgentConfigSSMParameter` 部分中的 `value` 密钥后面查找完整的 CloudWatch 代理配置。

   然后，在此处显示的 `ecs_service_discovery` 部分中，使用基于 `ECS_PROMETHEUS_EXPORTER_PORT` 的默认设置启用基于 `docker_label` 的服务发现，这与我们在 Redis OSS ECS 任务定义中定义的 Docker 标签相匹配。因此，我们无需在此部分进行任何更改：

   ```
   ecs_service_discovery": {
     "sd_frequency": "1m",
     "sd_result_file": "/tmp/cwagent_ecs_auto_sd.yaml",
   *  "docker_label": {
     },*
     ...
   ```

   对于 `metric_declaration` 部分，默认设置不允许任何 Redis OSS 指标。添加以下部分以允许 Redis OSS 指标。请务必遵循现有的缩进模式。

   ```
   {
     "source_labels": ["container_name"],
     "label_matcher": "^redis-exporter-.*$",
     "dimensions": [["ClusterName","TaskDefinitionFamily"]],
     "metric_selectors": [
       "^redis_net_(in|out)put_bytes_total$",
       "^redis_(expired|evicted)_keys_total$",
       "^redis_keyspace_(hits|misses)_total$",
       "^redis_memory_used_bytes$",
       "^redis_connected_clients$"
     ]
   },
   {
     "source_labels": ["container_name"],
     "label_matcher": "^redis-exporter-.*$",
     "dimensions": [["ClusterName","TaskDefinitionFamily","cmd"]],
     "metric_selectors": [
       "^redis_commands_total$"
     ]
   },
   {
     "source_labels": ["container_name"],
     "label_matcher": "^redis-exporter-.*$",
     "dimensions": [["ClusterName","TaskDefinitionFamily","db"]],
     "metric_selectors": [
       "^redis_db_keys$"
     ]
   },
   ```

1. 如果 CloudFormation 已在 Amazon ECS 集群中部署 CloudWatch 代理，您可以通过输入以下命令来创建更改集。

   ```
   ECS_LAUNCH_TYPE=FARGATE
   CREATE_IAM_ROLES=True
   ECS_CLUSTER_SUBNET=$ECS_CLUSTER_SUBNET_1
   ECS_TASK_ROLE_NAME=your_selected_ecs_task_role_name
   ECS_EXECUTION_ROLE_NAME=your_selected_ecs_execution_role_name
   
   aws cloudformation create-change-set --stack-name CWAgent-Prometheus-ECS-$ECS_CLUSTER_NAME-$ECS_LAUNCH_TYPE-awsvpc \
       --template-body file://cwagent-ecs-prometheus-metric-for-awsvpc.yaml \
       --parameters ParameterKey=ECSClusterName,ParameterValue=$ECS_CLUSTER_NAME \
                    ParameterKey=CreateIAMRoles,ParameterValue=$CREATE_IAM_ROLES \
                    ParameterKey=ECSLaunchType,ParameterValue=$ECS_LAUNCH_TYPE \
                    ParameterKey=SecurityGroupID,ParameterValue=$ECS_CLUSTER_SECURITY_GROUP \
                    ParameterKey=SubnetID,ParameterValue=$ECS_CLUSTER_SUBNET \
                    ParameterKey=TaskRoleName,ParameterValue=$ECS_TASK_ROLE_NAME \
                    ParameterKey=ExecutionRoleName,ParameterValue=$ECS_EXECUTION_ROLE_NAME \
       --capabilities CAPABILITY_NAMED_IAM \
       --region ${AWS_DEFAULT_REGION} \
       --change-set-name redis-scraping-support
   ```

1. 通过以下网址打开 CloudFormation 控制台：[https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/)。

1. 查看新创建的变更集 `redis-scraping-support`。您会看到一项应用于 `CWAgentConfigSSMParameter` 资源的更改。通过输入以下命令执行变更集并重新启动 CloudWatch 代理任务。

   ```
   aws ecs update-service --cluster $ECS_CLUSTER_NAME \
   --desired-count 0 \
   --service cwagent-prometheus-replica-service-$ECS_LAUNCH_TYPE-awsvpc \
   --region ${AWS_DEFAULT_REGION}
   ```

1. 等待大约 10 秒，然后输入以下命令。

   ```
   aws ecs update-service --cluster $ECS_CLUSTER_NAME \
   --desired-count 1 \
   --service cwagent-prometheus-replica-service-$ECS_LAUNCH_TYPE-awsvpc \
   --region ${AWS_DEFAULT_REGION}
   ```

1. 如果您是首次为集群安装带有 Prometheus 指标收集功能的 CloudWatch 代理，请输入以下命令：

   ```
   ECS_LAUNCH_TYPE=FARGATE
   CREATE_IAM_ROLES=True
   ECS_CLUSTER_SUBNET=$ECS_CLUSTER_SUBNET_1
   ECS_TASK_ROLE_NAME=your_selected_ecs_task_role_name
   ECS_EXECUTION_ROLE_NAME=your_selected_ecs_execution_role_name
   
   aws cloudformation create-stack --stack-name CWAgent-Prometheus-ECS-$ECS_CLUSTER_NAME-$ECS_LAUNCH_TYPE-awsvpc \
       --template-body file://cwagent-ecs-prometheus-metric-for-awsvpc.yaml \
       --parameters ParameterKey=ECSClusterName,ParameterValue=$ECS_CLUSTER_NAME \
                    ParameterKey=CreateIAMRoles,ParameterValue=$CREATE_IAM_ROLES \
                    ParameterKey=ECSLaunchType,ParameterValue=$ECS_LAUNCH_TYPE \
                    ParameterKey=SecurityGroupID,ParameterValue=$ECS_CLUSTER_SECURITY_GROUP \
                    ParameterKey=SubnetID,ParameterValue=$ECS_CLUSTER_SUBNET \
                    ParameterKey=TaskRoleName,ParameterValue=$ECS_TASK_ROLE_NAME \
                    ParameterKey=ExecutionRoleName,ParameterValue=$ECS_EXECUTION_ROLE_NAME \
       --capabilities CAPABILITY_NAMED_IAM \
       --region ${AWS_DEFAULT_REGION}
   ```

## 查看您的 Redis OSS 指标
<a name="ContainerInsights-Prometheus-Setup-redis-view"></a>

本教程会将以下指标发送到 CloudWatch 中的 **ECS/ContainerInsights/Prometheus** 命名空间。您可以使用 CloudWatch 控制台查看该命名空间中的指标。


| 指标名称 | Dimensions | 
| --- | --- | 
|  `redis_net_input_bytes_total` |  ClusterName、`TaskDefinitionFamily`  | 
|  `redis_net_output_bytes_total` |  ClusterName、`TaskDefinitionFamily`  | 
|  `redis_expired_keys_total` |  ClusterName、`TaskDefinitionFamily`  | 
|  `redis_evicted_keys_total` |  ClusterName、`TaskDefinitionFamily`  | 
|  `redis_keyspace_hits_total` |  ClusterName、`TaskDefinitionFamily`  | 
|  `redis_keyspace_misses_total` |  ClusterName、`TaskDefinitionFamily`  | 
|  `redis_memory_used_bytes` |  ClusterName、`TaskDefinitionFamily`  | 
|  `redis_connected_clients` |  ClusterName、`TaskDefinitionFamily`  | 
|  `redis_commands_total` |  ` ClusterName`, `TaskDefinitionFamily`, `cmd`  | 
|  `redis_db_keys` |  `ClusterName`, `TaskDefinitionFamily`, `db`  | 

**注意**  
**cmd** 维度的值可以是 `append`、`client`、`command`、`config`、`dbsize`、`flushall`、`get`、`incr`、`info`、`latency` 或 `slowlog`。  
**db** 维度的值可以从 `db0` 到 `db15`。

您还可以为 Redis OSS Prometheus 指标创建 CloudWatch 控制面板。

**为 Redis OSS Prometheus 指标创建控制面板**

1. 创建环境变量，替换以下值以匹配部署。

   ```
   DASHBOARD_NAME=your_cw_dashboard_name
   ECS_TASK_DEF_FAMILY=redis-prometheus-demo-$ECS_CLUSTER_NAME-fargate-awsvpc
   ```

1. 输入以下命令以创建控制面板。

   ```
   curl https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/sample_cloudwatch_dashboards/redis/cw_dashboard_redis.json \
   | sed "s/{{YOUR_AWS_REGION}}/${REGION_NAME}/g" \
   | sed "s/{{YOUR_CLUSTER_NAME}}/${CLUSTER_NAME}/g" \
   | sed "s/{{YOUR_NAMESPACE}}/${NAMESPACE}/g" \
   ```

# 在 Amazon EKS 和 Kubernetes 集群上设置和配置 Prometheus 指标收集
<a name="ContainerInsights-Prometheus-install-EKS"></a>

要从运行 Amazon EKS 或 Kubernetes 的集群收集 Prometheus 指标，您可以使用 CloudWatch 代理作为收集器或使用 AWS Distro for OpenTelemetry 收集器。有关使用 AWS Distro for OpenTelemetry 收集器的信息，请参阅 [https://aws-otel.github.io/docs/getting-started/container-insights/eks-prometheus](https://aws-otel.github.io/docs/getting-started/container-insights/eks-prometheus)。

下面几节介绍如何使用 CloudWatch 代理收集 Prometheus 指标。他们说明了如何在运行 Amazon EKS 或 Kubernetes 的集群上安装带有 Prometheus 监控功能的 CloudWatch 代理，以及如何配置该代理以抓取其他目标。他们还提供用于设置示例工作负载的可选教程，以使用 Prometheus 监控进行测试。

**Topics**
+ [在 Amazon EKS 和 Kubernetes 集群上安装带有 Prometheus 指标收集功能的 CloudWatch 代理](ContainerInsights-Prometheus-Setup.md)

# 在 Amazon EKS 和 Kubernetes 集群上安装带有 Prometheus 指标收集功能的 CloudWatch 代理
<a name="ContainerInsights-Prometheus-Setup"></a>

本节介绍如何在运行 Amazon EKS 或 Kubernetes 的集群中设置带有 Prometheus 监控功能的 CloudWatch 代理。执行此操作后，代理会自动抓取并导入该集群中运行的以下工作负载的指标。
+ AWS App Mesh
+ NGINX
+ Memcached
+ Java/JMX
+ HAProxy
+ Fluent Bit

您还可以将代理配置为抓取和导入其他 Prometheus 工作负载和源。

在按照下面这些步骤安装 CloudWatch 代理来收集 Prometheus 指标之前，您必须有在 Amazon EKS 上运行的集群或者在 Amazon EC2 实例上运行的 Kubernetes 集群。

**VPC 安全组要求**

Prometheus 工作负载的安全组的入口规则必须向 CloudWatch 代理打开 Prometheus 端口，以便通过私有 IP 抓取 Prometheus 指标。

CloudWatch 代理的安全组的出口规则必须允许 CloudWatch 代理通过私有 IP 连接到 Prometheus 工作负载的端口。

**Topics**
+ [在 Amazon EKS 和 Kubernetes 集群上安装带有 Prometheus 指标收集功能的 CloudWatch 代理](#ContainerInsights-Prometheus-Setup-roles)
+ [抓取其他 Prometheus 源并导入这些指标](ContainerInsights-Prometheus-Setup-configure.md)
+ [（可选）为 Prometheus 指标测试设置示例容器化 Amazon EKS 工作负载](ContainerInsights-Prometheus-Sample-Workloads.md)

## 在 Amazon EKS 和 Kubernetes 集群上安装带有 Prometheus 指标收集功能的 CloudWatch 代理
<a name="ContainerInsights-Prometheus-Setup-roles"></a>

本节介绍如何在运行 Amazon EKS 或 Kubernetes 的集群中设置带有 Prometheus 监控功能的 CloudWatch 代理。执行此操作后，代理会自动抓取并导入该集群中运行的以下工作负载的指标。
+ AWS App Mesh
+ NGINX
+ Memcached
+ Java/JMX
+ HAProxy
+ Fluent Bit

您还可以将代理配置为抓取和导入其他 Prometheus 工作负载和源。

在按照下面这些步骤安装 CloudWatch 代理来收集 Prometheus 指标之前，您必须有在 Amazon EKS 上运行的集群或者在 Amazon EC2 实例上运行的 Kubernetes 集群。

**VPC 安全组要求**

Prometheus 工作负载的安全组的入口规则必须向 CloudWatch 代理打开 Prometheus 端口，以便通过私有 IP 抓取 Prometheus 指标。

CloudWatch 代理的安全组的出口规则必须允许 CloudWatch 代理通过私有 IP 连接到 Prometheus 工作负载的端口。

**Topics**
+ [设置 IAM 角色](#ContainerInsights-Prometheus-Setup-roles)
+ [安装 CloudWatch 代理以收集 Prometheus 指标](#ContainerInsights-Prometheus-Setup-install-agent)

### 设置 IAM 角色
<a name="ContainerInsights-Prometheus-Setup-roles"></a>

第一步是在集群中设置必要的 IAM 角色。有两种方法：
+ 为服务账户设置 IAM 角色，也称为*服务角色*。此方法适用于 EC2 启动类型和 Fargate 启动类型。
+ 将 IAM 策略添加到集群的 IAM 角色。这仅适用于 EC2 启动类型。

**设置服务角色（EC2 启动类型和 Fargate 启动类型）**

要设置服务角色，请输入以下命令。将 *MyCluster* 替换为集群的名称。

```
eksctl create iamserviceaccount \
 --name cwagent-prometheus \
--namespace amazon-cloudwatch \
 --cluster MyCluster \
--attach-policy-arn arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy \
--approve \
--override-existing-serviceaccounts
```

**向节点组的 IAM 角色添加策略（仅限 EC2 启动类型）**

**在节点组中为 Prometheus 支持设置 IAM 策略**

1. 通过以下网址打开 Amazon EC2 控制台：[https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/)。

1. 在导航窗格中，选择 **Instances (实例)**。

1. 您需要查找集群的 IAM 角色名称的前缀。为此，请选中集群中实例名称旁边的复选框，然后依次选择**操作**、**安全性**、**修改 IAM 角色**。然后复制 IAM 角色的前缀，例如 `eksctl-dev303-workshop-nodegroup`。

1. 通过以下网址打开 IAM 控制台：[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/)。

1. 在导航窗格中，选择**角色**。

1. 使用搜索框查找您在此过程前面复制的前缀，然后选择该角色。

1. 选择**附加策略**。

1. 使用搜索框查找 **CloudWatchAgentServerPolicy**。选中 **CloudWatchAgentServerPolicy** 旁边的复选框，然后选择**附加策略**。

### 安装 CloudWatch 代理以收集 Prometheus 指标
<a name="ContainerInsights-Prometheus-Setup-install-agent"></a>

您必须在集群中安装 CloudWatch 代理才能收集指标。对于 Amazon EKS 集群和 Kubernetes 集群，安装代理的方式有所不同。

**删除具有 Prometheus 支持的 CloudWatch 代理的早期版本**

如果您的集群中已安装了具有 Prometheus 支持的 CloudWatch 代理版本，则必须通过输入以下命令删除该版本。这仅对具有 Prometheus 支持的以前版本的代理是必要的。您无需删除启用了 Container Insights 但没有 Prometheus 支持的 CloudWatch 代理。

```
kubectl delete deployment cwagent-prometheus -n amazon-cloudwatch
```

#### 在具有 EC2 启动类型的 Amazon EKS 集群上安装 CloudWatch 代理
<a name="ContainerInsights-Prometheus-Setup-install-agent-EKS"></a>

要在 Amazon EKS 集群上安装具有 Prometheus 支持的 CloudWatch 代理，请按照下列步骤操作。

**在 Amazon EKS 集群上安装具有 Prometheus 支持的 CloudWatch 代理**

1. 输入以下命令，检查是否已创建 `amazon-cloudwatch` 命名空间：

   ```
   kubectl get namespace
   ```

1. 如果结果中未显示 `amazon-cloudwatch`，请输入以下命令来创建它：

   ```
   kubectl create namespace amazon-cloudwatch
   ```

1. 要使用默认配置部署代理并使其将数据发送到所在的 AWS 区域，请输入以下命令：

   ```
   kubectl apply -f https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/prometheus-eks.yaml
   ```

   要让代理将数据发送到不同的区域，请按照下列步骤操作：

   1. 输入以下命令，下载代理的 YAML 文件：

      ```
      curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/prometheus-eks.yaml
      ```

   1. 使用文本编辑器打开文件，然后搜索文件的 `cwagentconfig.json` 块。

   1. 添加突出显示的行，并指定所需的区域：

      ```
      cwagentconfig.json: |
          {
            "agent": {
              "region": "us-east-2"
            },
            "logs": { ...
      ```

   1. 保存文件并使用更新后的文件部署代理。

      ```
      kubectl apply -f prometheus-eks.yaml
      ```

#### 在具有 Fargate 启动类型的 Amazon EKS 集群上安装 CloudWatch 代理
<a name="ContainerInsights-Prometheus-Setup-install-agent-EKS-fargate"></a>

要在具有 Fargate 启动类型的 Amazon EKS 集群上安装具有 Prometheus 支持的 CloudWatch 代理，请按照下列步骤操作。

**在具有 Fargate 启动类型的 Amazon EKS 集群上安装具有 Prometheus 支持的 CloudWatch 代理**

1. 输入以下命令为 CloudWatch 代理创建 Fargate 配置文件，以便它可以在集群内运行。将 *MyCluster* 替换为集群的名称。

   ```
   eksctl create fargateprofile --cluster MyCluster \
   --name amazon-cloudwatch \
   --namespace amazon-cloudwatch
   ```

1. 要安装 CloudWatch 代理，请输入以下命令。将 *MyCluster* 替换为集群的名称。此名称在存储代理收集的日志事件的日志组名称中使用，也用作代理收集的指标的维度。

   将 *region（区域）*替换为要将指标发送到的区域的名称。例如 `us-west-1`。

   ```
   curl https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/prometheus-eks-fargate.yaml | 
   sed "s/{{cluster_name}}/MyCluster/;s/{{region_name}}/region/" | 
   kubectl apply -f -
   ```

#### 在 Kubernetes 集群上安装 CloudWatch 代理
<a name="ContainerInsights-Prometheus-Setup-install-agent-Kubernetes"></a>

要在运行 Kubernetes 的集群上安装具有 Prometheus 支持的 CloudWatch 代理，请输入以下命令：

```
curl https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/prometheus-k8s.yaml | 
sed "s/{{cluster_name}}/MyCluster/;s/{{region_name}}/region/" | 
kubectl apply -f -
```

将 *MyCluster* 替换为集群的名称。此名称在存储代理收集的日志事件的日志组名称中使用，也用作代理收集的指标的维度。

将 *region（区域）*替换为要将指标发送到的 AWS 区域的名称。例如 **us-west-1**。

#### 验证代理是否正在运行
<a name="ContainerInsights-Prometheus-Setup-install-agent-verify"></a>

在 Amazon EKS 和 Kubernetes 集群上，您可以输入以下命令以确认代理正在运行。

```
kubectl get pod -l "app=cwagent-prometheus" -n amazon-cloudwatch
```

如果结果包含处于 `Running` 状态的单个 CloudWatch 代理 pod，则代理会运行并收集 Prometheus 指标。默认情况下，CloudWatch 代理每分钟会收集 App Mesh、NGINX、Memcached、Java/JMX 和 HAProxy 的指标。有关这些指标的更多信息，请参阅 [CloudWatch 代理收集的 Prometheus 指标](ContainerInsights-Prometheus-metrics.md)。有关如何在 CloudWatch 中查看 Prometheus 指标的说明，请参阅 [查看 Prometheus 指标](ContainerInsights-Prometheus-viewmetrics.md)

您还可以将 CloudWatch 代理配置为从其他 Prometheus 导出程序收集指标。有关更多信息，请参阅 [抓取其他 Prometheus 源并导入这些指标](ContainerInsights-Prometheus-Setup-configure.md)。

# 抓取其他 Prometheus 源并导入这些指标
<a name="ContainerInsights-Prometheus-Setup-configure"></a>

具有 Prometheus 监控功能的 CloudWatch 代理需要两种配置来抓取 Prometheus 指标。一个用于 Prometheus 文档中 [<scrape\$1config>](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#scrape_config) 记录的标准 Prometheus 配置。另一种配置是 CloudWatch 代理配置文件。

对于 Amazon EKS 集群，配置在 `prometheus-eks.yaml`（适用于 EC2 启动类型）或 `prometheus-eks-fargate.yaml`（适用于 Fargate 启动类型）中定义为两个 Config 映射：
+ `name: prometheus-config` 部分包含 Prometheus 抓取的设置。
+ `name: prometheus-cwagentconfig` 部分包含 CloudWatch 代理的配置。您可以使用此部分配置 CloudWatch 如何收集 Prometheus 指标。例如，您指定要导入 CloudWatch 的指标，并定义其维度。

对于在 Amazon EC2 实例上运行的 Kubernetes 集群，配置在 `prometheus-k8s.yaml` YAML 文件中定义为两个 config 映射：
+ `name: prometheus-config` 部分包含 Prometheus 抓取的设置。
+ `name: prometheus-cwagentconfig` 部分包含 CloudWatch 代理的配置。

要抓取其他 Prometheus 指标源并将这些指标导入 CloudWatch，您需要修改 Prometheus 抓取配置和 CloudWatch 代理配置，然后使用更新的配置重新部署代理。

**VPC 安全组要求**

Prometheus 工作负载的安全组的入口规则必须向 CloudWatch 代理打开 Prometheus 端口，以便通过私有 IP 抓取 Prometheus 指标。

CloudWatch 代理的安全组的出口规则必须允许 CloudWatch 代理通过私有 IP 连接到 Prometheus 工作负载的端口。

## Prometheus 抓取配置
<a name="ContainerInsights-Prometheus-Setup-config-global"></a>

CloudWatch 代理支持标准的 Prometheus 抓取配置，如 Prometheus 文档中的 [<scrape\$1config>](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#scrape_config) 所述。您可以编辑此部分以更新此文件中已有的配置，并添加其他 Prometheus 抓取目标。默认情况下，示例配置文件包含以下全局配置行：

```
global:
  scrape_interval: 1m
  scrape_timeout: 10s
```
+ **scrape\$1interval** – 定义抓取目标的频率。
+ **scrape\$1timeout** – 定义抓取请求超时之前的等待时间。

您还可以在作业级别为这些设置定义不同的值，以覆盖全局配置。

### Prometheus 抓取任务
<a name="ContainerInsights-Prometheus-Setup-config-scrape"></a>

CloudWatch 代理 YAML 文件已配置了一些默认的抓取任务。例如在 `prometheus-eks.yaml` 中，在 `scrape_configs` 部分中的 `job_name` 行中配置了默认的抓取任务。在此文件中，以下默认 `kubernetes-pod-jmx` 部分会抓取 JMX Exporter 指标。

```
   - job_name: 'kubernetes-pod-jmx'
      sample_limit: 10000
      metrics_path: /metrics
      kubernetes_sd_configs:
      - role: pod
      relabel_configs:
      - source_labels: [__address__]
        action: keep
        regex: '.*:9404$'
      - action: labelmap
        regex: __meta_kubernetes_pod_label_(.+)
      - action: replace
        source_labels:
        - __meta_kubernetes_namespace
        target_label: Namespace
      - source_labels: [__meta_kubernetes_pod_name]
        action: replace
        target_label: pod_name
      - action: replace
        source_labels:
        - __meta_kubernetes_pod_container_name
        target_label: container_name
      - action: replace
        source_labels:
        - __meta_kubernetes_pod_controller_name
        target_label: pod_controller_name
      - action: replace
        source_labels:
        - __meta_kubernetes_pod_controller_kind
        target_label: pod_controller_kind
      - action: replace
        source_labels:
        - __meta_kubernetes_pod_phase
        target_label: pod_phase
```

这些默认目标中的每个目标都会被抓取，并使用嵌入式指标格式在日志事件中将指标发送到 CloudWatch。有关更多信息，请参阅 [在日志中嵌入指标](CloudWatch_Embedded_Metric_Format.md)。

来自 Amazon EKS 和 Kubernetes 集群的日志事件存储在 CloudWatch Logs 的 **/aws/containerinsights/*cluster\$1name*/prometheus** 日志组中。来自 Amazon ECS 集群的日志事件存储在 **/aws/ecs/containerinsights/*cluster\$1name*/prometheus** 日志组中。

每个抓取作业都包含在此日志组中的不同日志流中。例如，为 App Mesh 定义了 Prometheus 抓取任务 `kubernetes-pod-appmesh-envoy`。所有来自 Amazon EKS 和 Kubernetes 集群的 App Mesh Prometheus 指标都发送到名为 **/aws/containerinsights/*cluster\$1name*>prometheus/kubernetes-pod-appmesh-envoy/** 的日志流。

要添加新的抓取目标，请将新的 `job_name` 部分添加到 YAML 文件的 `scrape_configs` 部分，然后重新启动代理。有关此过程的示例，请参阅 [添加新 Prometheus 抓取目标的教程：Prometheus API 服务器指标](#ContainerInsights-Prometheus-Setup-new-exporters)。

## Prometheus 的 CloudWatch 代理配置
<a name="ContainerInsights-Prometheus-Setup-cw-agent-config2"></a>

CloudWatch 代理配置文件在 `metrics_collected` 下面有一个 `prometheus` 部分用于 Prometheus 抓取配置。它包含以下配置选项：
+ **cluster\$1name** – 指定要在日志事件中添加为标签的集群名称。该字段是可选的。如果省略它，代理可以检测到 Amazon EKS 或 Kubernetes 集群名称。
+ **log\$1group\$1name** – 指定已抓取 Prometheus 指标的日志组名称。该字段是可选的。如果省略它，CloudWatch 会将 **/aws/containerinsights/*cluster\$1name*/prometheus** 用于来自 Amazon EKS 和 Kubernetes 集群的日志。
+ **prometheus\$1config\$1path** – 指定 Prometheus 抓取配置文件路径。如果此字段的值以 `env:` 开头，Prometheus 抓取配置文件内容将从容器的环境变量中检索。请勿更改此字段。
+ **ecs\$1service\$1discovery** – 是指定 Amazon ECS Prometheus 服务发现配置的部分。有关更多信息，请参阅 [Amazon ECS 集群上自动发现的详细指南](ContainerInsights-Prometheus-Setup-autodiscovery-ecs.md)。

  `ecs_service_discovery` 部分包含以下字段：
  + `sd_frequency` 是发现 Prometheus 导出器的频率。指定数字和单位后缀。例如，`1m` 表示每分钟一次或 `30s` 表示每 30 秒一次。有效的单位后缀为 `ns`、`us`、`ms`、`s`、`m` 和 `h`。

    该字段是可选的。默认值为 60 秒（1 分钟）。
  + `sd_target_cluster` 是用于自动发现的目标 Amazon ECS 集群名称。该字段是可选的。默认名称为安装 CloudWatch 代理的 Amazon ECS 集群的名称。
  + `sd_cluster_region` 是目标 Amazon ECS 集群的区域。该字段是可选的。默认区域为安装 CloudWatch 代理的 Amazon ECS 集群的区域。
  + `sd_result_file` 是 Prometheus 目标结果的 YAML 文件的路径。Prometheus 抓取配置将引用此文件。
  + `docker_label` 是可选部分，您可以使用它来指定基于 docker 标签的服务发现的配置。如果省略此部分，则不会使用基于 docker 标签的发现。此部分包含以下字段：
    + `sd_port_label` 是容器的 docker 标签名称，用于指定 Prometheus 指标的容器端口。默认值为 `ECS_PROMETHEUS_EXPORTER_PORT`。如果容器没有此 docker 标签，CloudWatch 代理将跳过它。
    + `sd_metrics_path_label` 是容器的 docker 标签名称，用于指定 Prometheus 指标路径。默认值为 `ECS_PROMETHEUS_METRICS_PATH`。如果容器没有此 docker 标签，则代理会采用默认路径 `/metrics`。
    + `sd_job_name_label` 是容器的 docker 标签名称，用于指定 Prometheus 抓取任务名称。默认值为 `job`。如果容器没有此 docker 标签，CloudWatch 代理会使用 Prometheus 抓取配置中的任务名称。
  + `task_definition_list` 是可选部分，可用于指定基于任务定义的服务发现的配置。如果省略此部分，则不会使用基于任务定义的发现。此部分包含以下字段：
    + `sd_task_definition_arn_pattern` 是用于指定要发现的 Amazon ECS 任务定义的模式。这是正则表达式。
    + `sd_metrics_ports` 列出 Prometheus 指标的 containerPort。用分号分隔 containerPorts。
    + `sd_container_name_pattern` 指定 Amazon ECS 任务容器名称。这是正则表达式。
    + `sd_metrics_path` 指定 Prometheus 指标路径。如果省略此项，代理会采用默认路径 `/metrics`
    + `sd_job_name` 指定 Prometheus 抓取任务名称。如果省略此字段，CloudWatch 代理会使用 Prometheus 抓取配置中的任务名称。
+ **metric\$1declaration** – 是指定要生成的采用嵌入式指标格式的日志数组的部分。默认情况下，CloudWatch 代理从中进行导入的每个 Prometheus 源都有 `metric_declaration` 部分。这些部分各包括以下字段：
  + `label_matcher` 是一个正则表达式，用于检查 `source_labels` 中列出的标签的值。匹配的指标将启用，以包含在发送到 CloudWatch 的嵌入式指标格式中。

    如果您在 `source_labels` 中指定了多个标签，我们建议您不要在 `label_matcher` 的正则表达式中使用 `^` 或 `$` 字符。
  + `source_labels` 指定由 `label_matcher` 行检查的标签的值。
  + `label_separator` 指定要在 ` label_matcher` 行中使用的分隔符（如果指定了多个 `source_labels`）。默认值为 `;`。您可以在以下示例中看到 `label_matcher` 行中使用的此默认值。
  + `metric_selectors` 是一个正则表达式，用于指定要收集并发送到 CloudWatch 的指标。
  + `dimensions` 是要用作每个选定指标的 CloudWatch 维度的标签列表。

请参阅以下 `metric_declaration` 示例。

```
"metric_declaration": [
  {
     "source_labels":[ "Service", "Namespace"],
     "label_matcher":"(.*node-exporter.*|.*kube-dns.*);kube-system",
     "dimensions":[
        ["Service", "Namespace"]
     ],
     "metric_selectors":[
        "^coredns_dns_request_type_count_total$"
     ]
  }
]
```

此示例配置嵌入式指标格式部分，以便在满足以下条件时作为日志事件发送：
+ `Service` 的值包含 `node-exporter` 或 `kube-dns`。
+ `Namespace` 的值为 `kube-system`。
+ Prometheus 指标 `coredns_dns_request_type_count_total` 同时包含 `Service` 和 `Namespace` 标签。

发送的日志事件包括以下突出显示的部分：

```
{
   "CloudWatchMetrics":[
      {
         "Metrics":[
            {
               "Name":"coredns_dns_request_type_count_total"
            }
         ],
         "Dimensions":[
            [
               "Namespace",
               "Service"
            ]
         ],
         "Namespace":"ContainerInsights/Prometheus"
      }
   ],
   "Namespace":"kube-system",
   "Service":"kube-dns",
   "coredns_dns_request_type_count_total":2562,
   "eks_amazonaws_com_component":"kube-dns",
   "instance":"192.168.61.254:9153",
   "job":"kubernetes-service-endpoints",
   ...
}
```

## 添加新 Prometheus 抓取目标的教程：Prometheus API 服务器指标
<a name="ContainerInsights-Prometheus-Setup-new-exporters"></a>

默认情况下，Kubernetes API 服务器会在端点上公开 Prometheus 指标。Kubernetes API 服务器抓取配置的官方示例可在 [Github](https://github.com/prometheus/prometheus/blob/main/documentation/examples/prometheus-kubernetes.yml) 上找到。

以下教程演示如何执行以下步骤以开始将 Kubernetes API 服务器指标导入到 CloudWatch 中：
+ 将 Kubernetes API 服务器的 Prometheus 抓取配置添加到 CloudWatch 代理 YAML 文件。
+ 在 CloudWatch 代理 YAML 文件中配置嵌入式指标格式指标定义。
+ （可选）为 Kubernetes API 服务器指标创建 CloudWatch 控制面板。

**注意**  
Kubernetes API 服务器公开计量表、计数器、直方图和摘要指标。在此版本的 Prometheus 指标支持中，CloudWatch 仅导入具有计量表、计数器和汇总类型的指标。

**开始在 CloudWatch 中收集 Kubernetes API 服务器 Prometheus 指标**

1. 通过输入以下命令之一，下载 `prometheus-eks.yaml`、`prometheus-eks-fargate.yaml` 或 `prometheus-k8s.yaml` 文件的最新版本。

   对于具有 EC2 启动类型的 Amazon EKS 集群，请输入以下命令：

   ```
   curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/prometheus-eks.yaml
   ```

   对于具有 Fargate 启动类型的 Amazon EKS 集群，请输入以下命令：

   ```
   curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/prometheus-eks-fargate.yaml
   ```

   对于在 Amazon EC2 实例上运行的 Kubernetes 集群，请输入以下命令：

   ```
   curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/prometheus-k8s.yaml
   ```

1. 使用文本编辑器打开文件，找到 `prometheus-config` 部分，然后在该部分中添加以下部分。然后，保存更改：

   ```
       # Scrape config for API servers
       - job_name: 'kubernetes-apiservers'
         kubernetes_sd_configs:
           - role: endpoints
             namespaces:
               names:
                 - default
         scheme: https
         tls_config:
           ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
           insecure_skip_verify: true
         bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token
         relabel_configs:
         - source_labels: [__meta_kubernetes_service_name, __meta_kubernetes_endpoint_port_name]
           action: keep
           regex: kubernetes;https
         - action: replace
           source_labels:
           - __meta_kubernetes_namespace
           target_label: Namespace
         - action: replace
           source_labels:
           - __meta_kubernetes_service_name
           target_label: Service
   ```

1. 当 YAML 文件仍在文本编辑器中处于打开状态时，找到 `cwagentconfig.json` 部分。添加以下子部分并保存更改。此部分将 API 服务器指标放到 CloudWatch 代理允许列表中。将三种类型的 API 服务器指标添加到允许列表中：
   + etcd 对象计数
   + API 服务器注册控制器指标
   + API 服务器请求指标

   ```
   {"source_labels": ["job", "resource"],
     "label_matcher": "^kubernetes-apiservers;(services|daemonsets.apps|deployments.apps|configmaps|endpoints|secrets|serviceaccounts|replicasets.apps)",
     "dimensions": [["ClusterName","Service","resource"]],
     "metric_selectors": [
     "^etcd_object_counts$"
     ]
   },
   {"source_labels": ["job", "name"],
      "label_matcher": "^kubernetes-apiservers;APIServiceRegistrationController$",
      "dimensions": [["ClusterName","Service","name"]],
      "metric_selectors": [
      "^workqueue_depth$",
      "^workqueue_adds_total$",
      "^workqueue_retries_total$"
     ]
   },
   {"source_labels": ["job","code"],
     "label_matcher": "^kubernetes-apiservers;2[0-9]{2}$",
     "dimensions": [["ClusterName","Service","code"]],
     "metric_selectors": [
      "^apiserver_request_total$"
     ]
   },
   {"source_labels": ["job"],
     "label_matcher": "^kubernetes-apiservers",
     "dimensions": [["ClusterName","Service"]],
     "metric_selectors": [
     "^apiserver_request_total$"
     ]
   },
   ```

1. 如果您已在集群中部署了具有 Prometheus 支持的 CloudWatch 代理，则必须通过输入以下命令将其删除：

   ```
   kubectl delete deployment cwagent-prometheus -n amazon-cloudwatch
   ```

1. 通过输入以下任一命令，使用更新的配置部署 CloudWatch 代理。对于具有 EC2 启动类型的 Amazon EKS 集群，请输入：

   ```
   kubectl apply -f prometheus-eks.yaml
   ```

   对于具有 Fargate 启动类型的 Amazon EKS 集群，请输入以下命令。将 *MyCluster* 和 *region（区域）*替换为值以匹配您的部署。

   ```
   cat prometheus-eks-fargate.yaml \
   | sed "s/{{cluster_name}}/MyCluster/;s/{{region_name}}/region/" \
   | kubectl apply -f -
   ```

   对于 Kubernetes 集群，请输入以下命令。将 *MyCluster* 和 *region（区域）*替换为值以匹配您的部署。

   ```
   cat prometheus-k8s.yaml \
   | sed "s/{{cluster_name}}/MyCluster/;s/{{region_name}}/region/" \
   | kubectl apply -f -
   ```

完成此操作后，您应该会看到 **/aws/containerinsights/*cluster\$1name*/prometheus** 日志组中名为 **kubernetes-apiservers** 的新日志流。此日志流应使用嵌入式指标格式定义来嵌入日志事件，如下所示：

```
{
   "CloudWatchMetrics":[
      {
         "Metrics":[
            {
               "Name":"apiserver_request_total"
            }
         ],
         "Dimensions":[
            [
               "ClusterName",
               "Service"
            ]
         ],
         "Namespace":"ContainerInsights/Prometheus"
      }
   ],
   "ClusterName":"my-cluster-name",
   "Namespace":"default",
   "Service":"kubernetes",
   "Timestamp":"1592267020339",
   "Version":"0",
   "apiserver_request_count":0,
   "apiserver_request_total":0,
   "code":"0",
   "component":"apiserver",
   "contentType":"application/json",
   "instance":"192.0.2.0:443",
   "job":"kubernetes-apiservers",
   "prom_metric_type":"counter",
   "resource":"pods",
   "scope":"namespace",
   "verb":"WATCH",
   "version":"v1"
}
```

您可以在 **ContainerInsights/Prometheus** 命名空间中的 CloudWatch 控制台中查看您的指标。（可选）还可以为 Prometheus Kubernetes API 服务器指标创建 CloudWatch 控制面板。

### （可选）为 Kubernetes API 服务器指标创建控制面板
<a name="ContainerInsights-Prometheus-Setup-KPI-dashboard"></a>

要在控制面板中查看 Kubernetes API 服务器指标，您必须先完成前面几个部分中的步骤，然后才能开始在 CloudWatch 中收集这些指标。

**为 Kubernetes API 服务器指标创建控制面板**

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 确保选择了正确的 AWS 区域。

1. 在导航窗格中，选择**控制面板**。

1. 选择**创建控制面板**。输入新控制面板的名称，然后选择**创建控制面板**。

1. 在**添加到该控制面板**中，选择**取消**。

1. 依次选择**操作**、**编辑控制面板**。

1. 下载以下 JSON 文件：[Kubernetes API 控制面板源](https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/sample_cloudwatch_dashboards/kubernetes_api_server/cw_dashboard_kubernetes_api_server.json)。

1. 使用文本编辑器打开下载的 JSON 文件，然后执行以下更改：
   + 将所有 `{{YOUR_CLUSTER_NAME}}` 字符串替换为您的集群的确切名称。请勿在文本之前或之后添加空格。
   + 将所有 `{{YOUR_AWS_REGION}}` 字符串替换为在其中收集指标的区域的名称。例如 `us-west-2`。请勿在文本之前或之后添加空格。

1. 复制整个 JSON blob 并将其粘贴到 CloudWatch 控制台的文本框中，替换框中已有的内容。

1. 选择**更新**、**保存控制面板**。

# （可选）为 Prometheus 指标测试设置示例容器化 Amazon EKS 工作负载
<a name="ContainerInsights-Prometheus-Sample-Workloads"></a>

要测试 CloudWatch Container Insights 中的 Prometheus 指标支持，您可设置以下一个或多个容器化工作负载。具有 Prometheus 支持的 CloudWatch 代理会自动从这些工作负载中的每一个收集指标。要查看默认情况下收集的指标，请参阅 [CloudWatch 代理收集的 Prometheus 指标](ContainerInsights-Prometheus-metrics.md)。

在安装任意这些工作负载之前，您必须输入以下命令来安装 Helm 3.x：

```
brew install helm
```

有关更多信息，请参阅 [Helm](https://helm.sh)。

**Topics**
+ [为 Amazon EKS 和 Kubernetes 设置 AWS App Mesh 示例工作负载](ContainerInsights-Prometheus-Sample-Workloads-appmesh.md)
+ [使用 Amazon EKS 和 Kubernetes 上的示例流量设置 NGINX](ContainerInsights-Prometheus-Sample-Workloads-nginx.md)
+ [使用 Amazon EKS 和 Kubernetes 上的指标导出器设置 memcached](ContainerInsights-Prometheus-Sample-Workloads-memcached.md)
+ [在 Amazon EKS 和 Kubernetes 上设置 Java/JMX 示例工作负载](ContainerInsights-Prometheus-Sample-Workloads-javajmx.md)
+ [使用 Amazon EKS 和 Kubernetes 上的指标导出器设置 HAProxy](ContainerInsights-Prometheus-Sample-Workloads-haproxy.md)
+ [添加新 Prometheus 抓取目标的教程：Amazon EKS 和 Kubernetes 集群上的 Redis OSS](ContainerInsights-Prometheus-Setup-redis-eks.md)

# 为 Amazon EKS 和 Kubernetes 设置 AWS App Mesh 示例工作负载
<a name="ContainerInsights-Prometheus-Sample-Workloads-appmesh"></a>

CloudWatch Container Insights 支持 AWS App Mesh 中的 Prometheus 支持。以下部分介绍了如何设置 App Mesh。

**Topics**
+ [在具有 EC2 启动类型或 Kubernetes 集群的 Amazon EKS 集群上设置 AWS App Mesh 示例工作负载](ContainerInsights-Prometheus-Sample-Workloads-appmesh-EKS.md)
+ [使用 Fargate 启动类型在 Amazon EKS 集群上设置 AWS App Mesh 示例工作负载](ContainerInsights-Prometheus-Sample-Workloads-appmesh-Fargate.md)

# 在具有 EC2 启动类型或 Kubernetes 集群的 Amazon EKS 集群上设置 AWS App Mesh 示例工作负载
<a name="ContainerInsights-Prometheus-Sample-Workloads-appmesh-EKS"></a>

如果您要在运行 Amazon EKS 且具有 EC2 启动类型的集群或 Kubernetes 集群上设置 App Mesh，请使用这些说明。

## 配置 IAM 权限
<a name="ContainerInsights-Prometheus-Sample-Workloads-appmesh-iam"></a>

必须将 **AWSAppMeshFullAccess** 策略添加到您的 Amazon EKS 或 Kubernetes 节点组的 IAM 角色中。在 Amazon EKS 上，此节点组名称类似于 `eksctl-integ-test-eks-prometheus-NodeInstanceRole-ABCDEFHIJKL`。在 Kubernetes 上，它可能类似于 `nodes.integ-test-kops-prometheus.k8s.local`。

## 安装 App Mesh
<a name="ContainerInsights-Prometheus-Sample-Workloads-appmesh-install"></a>

要安装 App Mesh Kubernetes 控制器，请按照 [App Mesh 控制器](https://github.com/aws/eks-charts/tree/master/stable/appmesh-controller#app-mesh-controller)中的说明进行操作。

## 安装示例应用程序
<a name="ContainerInsights-Prometheus-Sample-Workloads-appmesh-application"></a>

[aws-app-mesh-examples](https://github.com/aws/aws-app-mesh-examples) 包含多个 Kubernetes App Mesh 演练。在本教程中，您将安装一个示例颜色应用程序，该应用程序会展示 http 路由如何使用标头来匹配传入请求。

**使用示例 App Mesh 应用程序来测试 Container Insights**

1. 按照以下说明安装应用程序：[https://github.com/aws/aws-app-mesh-examples/tree/main/walkthroughs/howto-k8s-http-headers](https://github.com/aws/aws-app-mesh-examples/tree/main/walkthroughs/howto-k8s-http-headers)。

1. 启动 curler pod 以生成流量：

   ```
   kubectl -n default run -it curler --image=tutum/curl /bin/bash
   ```

1. 通过更改 HTTP 标头来对不同的端点执行 curl。多次运行 curl 命令，如下所示：

   ```
   curl -H "color_header: blue" front.howto-k8s-http-headers.svc.cluster.local:8080/; echo;
   
   curl -H "color_header: red" front.howto-k8s-http-headers.svc.cluster.local:8080/; echo;
   
   curl -H "color_header: yellow" front.howto-k8s-http-headers.svc.cluster.local:8080/; echo;
   ```

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 在集群运行的 AWS 区域的导航窗格中，选择 **Metrics（指标）**。指标位于 **ContainerInsights/Prometheus** 命名空间中。

1. 要查看 CloudWatch Logs 事件，请在导航窗格中选择 **Log groups（日志组）**。事件位于日志流 `kubernetes-pod-appmesh-envoy` 的日志组 ` /aws/containerinsights/your_cluster_name/prometheus ` 中。

## 删除 App Mesh 测试环境
<a name="ContainerInsights-Prometheus-Sample-Workloads-appmesh-delete"></a>

App Mesh 和示例应用程序使用完成后，请使用以下命令删除不必要的资源。输入以下命令删除示例应用程序：

```
cd aws-app-mesh-examples/walkthroughs/howto-k8s-http-headers/
kubectl delete -f _output/manifest.yaml
```

输入以下命令删除 App Mesh 控制器：

```
helm delete appmesh-controller -n appmesh-system
```

# 使用 Fargate 启动类型在 Amazon EKS 集群上设置 AWS App Mesh 示例工作负载
<a name="ContainerInsights-Prometheus-Sample-Workloads-appmesh-Fargate"></a>

如果您要在运行 Amazon EKS 且具有 Fargate 启动类型的集群上设置 App Mesh，请遵循这些说明。

## 配置 IAM 权限
<a name="ContainerInsights-Prometheus-Sample-Workloads-appmesh--fargate-iam"></a>

要设置 IAM 权限，请输入以下命令。将 *MyCluster* 替换为您的集群的名称。

```
eksctl create iamserviceaccount --cluster MyCluster \
 --namespace howto-k8s-fargate \
 --name appmesh-pod \
 --attach-policy-arn arn:aws:iam::aws:policy/AWSAppMeshEnvoyAccess \
 --attach-policy-arn arn:aws:iam::aws:policy/AWSCloudMapDiscoverInstanceAccess \
 --attach-policy-arn arn:aws:iam::aws:policy/AWSXRayDaemonWriteAccess \
 --attach-policy-arn arn:aws:iam::aws:policy/CloudWatchLogsFullAccess \
 --attach-policy-arn arn:aws:iam::aws:policy/AWSAppMeshFullAccess \
 --attach-policy-arn arn:aws:iam::aws:policy/AWSCloudMapFullAccess \
 --override-existing-serviceaccounts \
 --approve
```

## 安装 App Mesh
<a name="ContainerInsights-Prometheus-Sample-Workloads-appmesh-fargate-install"></a>

要安装 App Mesh Kubernetes 控制器，请按照 [App Mesh 控制器](https://github.com/aws/eks-charts/tree/master/stable/appmesh-controller#app-mesh-controller)中的说明进行操作。请务必按照有关 Fargate 启动类型的 Amazon EKS 的说明进行操作。

## 安装示例应用程序
<a name="ContainerInsights-Prometheus-Sample-Workloads-appmesh-fargate-application"></a>

[aws-app-mesh-examples](https://github.com/aws/aws-app-mesh-examples) 包含多个 Kubernetes App Mesh 演练。在本教程中，您将安装适用于 Fargate 启动类型的 Amazon EKS 集群的示例颜色应用程序。

**使用示例 App Mesh 应用程序来测试 Container Insights**

1. 按照以下说明安装应用程序：[https://github.com/aws/aws-app-mesh-examples/tree/main/walkthroughs/howto-k8s-fargate](https://github.com/aws/aws-app-mesh-examples/tree/main/walkthroughs/howto-k8s-fargate)。

   这些说明假定您正在使用正确的 Fargate 配置文件创建新集群。如果您想使用已设置的 Amazon EKS 集群，您可以使用以下命令为本演示设置该集群。将 *MyCluster* 替换为您的集群的名称。

   ```
   eksctl create iamserviceaccount --cluster MyCluster \
    --namespace howto-k8s-fargate \
    --name appmesh-pod \
    --attach-policy-arn arn:aws:iam::aws:policy/AWSAppMeshEnvoyAccess \
    --attach-policy-arn arn:aws:iam::aws:policy/AWSCloudMapDiscoverInstanceAccess \
    --attach-policy-arn arn:aws:iam::aws:policy/AWSXRayDaemonWriteAccess \
    --attach-policy-arn arn:aws:iam::aws:policy/CloudWatchLogsFullAccess \
    --attach-policy-arn arn:aws:iam::aws:policy/AWSAppMeshFullAccess \
    --attach-policy-arn arn:aws:iam::aws:policy/AWSCloudMapFullAccess \
    --override-existing-serviceaccounts \
    --approve
   ```

   ```
   eksctl create fargateprofile --cluster MyCluster \
   --namespace howto-k8s-fargate --name howto-k8s-fargate
   ```

1. 端口转发前端应用程序部署：

   ```
   kubectl -n howto-k8s-fargate port-forward deployment/front 8080:8080
   ```

1. Curl 前端应用程序：

   ```
   while true; do  curl -s http://localhost:8080/color; sleep 0.1; echo ; done
   ```

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 在集群运行的 AWS 区域的导航窗格中，选择 **Metrics（指标）**。指标位于 **ContainerInsights/Prometheus** 命名空间中。

1. 要查看 CloudWatch Logs 事件，请在导航窗格中选择 **Log groups（日志组）**。事件位于日志流 `kubernetes-pod-appmesh-envoy` 的日志组 ` /aws/containerinsights/your_cluster_name/prometheus ` 中。

## 删除 App Mesh 测试环境
<a name="ContainerInsights-Prometheus-Sample-Workloads-appmesh-fargate-delete"></a>

App Mesh 和示例应用程序使用完成后，请使用以下命令删除不必要的资源。输入以下命令删除示例应用程序：

```
cd aws-app-mesh-examples/walkthroughs/howto-k8s-fargate/
kubectl delete -f _output/manifest.yaml
```

输入以下命令删除 App Mesh 控制器：

```
helm delete appmesh-controller -n appmesh-system
```

# 使用 Amazon EKS 和 Kubernetes 上的示例流量设置 NGINX
<a name="ContainerInsights-Prometheus-Sample-Workloads-nginx"></a>

NGINX 是一个 Web 服务器，也可以用作负载均衡器和反向代理。有关 Kubernetes 如何使用 NGINX for ingress 的更多信息，请参阅 [kubernetes/ingress-nginx](https://github.com/kubernetes/ingress-nginx)。

**安装带有示例流量服务的 Ingress-NGINX 以测试 Container Insights Prometheus 支持**

1. 输入以下命令以添加 Helm ingress-nginx 存储库：

   ```
   helm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx
   ```

1. 输入以下命令：

   ```
   kubectl create namespace nginx-ingress-sample
   
   helm install my-nginx ingress-nginx/ingress-nginx \
   --namespace nginx-ingress-sample \
   --set controller.metrics.enabled=true \
   --set-string controller.metrics.service.annotations."prometheus\.io/port"="10254" \
   --set-string controller.metrics.service.annotations."prometheus\.io/scrape"="true"
   ```

1. 通过输入以下命令检查服务是否正确启动：

   ```
   kubectl get service -n nginx-ingress-sample
   ```

   此命令的输出应显示多列，包括一个 `EXTERNAL-IP` 列。

1. 将 `EXTERNAL-IP` 变量设置为 NGINX 摄取控制器的行中 `EXTERNAL-IP` 列的值。

   ```
   EXTERNAL_IP=your-nginx-controller-external-ip
   ```

1. 输入以下命令启动一些示例 NGINX 流量。

   ```
   SAMPLE_TRAFFIC_NAMESPACE=nginx-sample-traffic
   curl https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/sample_traffic/nginx-traffic/nginx-traffic-sample.yaml | 
   sed "s/{{external_ip}}/$EXTERNAL_IP/g" | 
   sed "s/{{namespace}}/$SAMPLE_TRAFFIC_NAMESPACE/g" | 
   kubectl apply -f -
   ```

1. 输入以下命令以确认所有三个 pod 都处于 `Running` 状态。

   ```
   kubectl get pod -n $SAMPLE_TRAFFIC_NAMESPACE
   ```

   如果它们正在运行，您应该很快在 **ContainerInsights/Prometheus** 命名空间中看到指标。

**卸载 NGINX 和示例流量应用程序**

1. 输入以下命令删除示例流量服务：

   ```
   kubectl delete namespace $SAMPLE_TRAFFIC_NAMESPACE
   ```

1. 按 Helm 版本名称删除 NGINX 出口。

   ```
   helm uninstall my-nginx --namespace nginx-ingress-sample
   kubectl delete namespace nginx-ingress-sample
   ```

# 使用 Amazon EKS 和 Kubernetes 上的指标导出器设置 memcached
<a name="ContainerInsights-Prometheus-Sample-Workloads-memcached"></a>

memcached 是一个开源内存对象缓存系统。有关更多信息，请参阅[什么是 Memcached？](https://www.memcached.org)

如果您在具有 Fargate 启动类型的集群上运行 memcached，则需要在执行此过程中的步骤之前设置 Fargate 配置文件。要设置配置文件，请输入以下命令。将 *MyCluster* 替换为您的集群的名称。

```
eksctl create fargateprofile --cluster MyCluster \
--namespace memcached-sample --name memcached-sample
```

**安装带有 Metric Exporter 的 memcached 以测试 Container Insights Prometheus 支持**

1. 输入以下命令以添加存储库：

   ```
   helm repo add bitnami https://charts.bitnami.com/bitnami
   ```

1. 输入以下命令以创建新的命名空间：

   ```
   kubectl create namespace memcached-sample
   ```

1. 输入以下命令以安装 Memcached

   ```
   helm install my-memcached bitnami/memcached --namespace memcached-sample \
   --set metrics.enabled=true \
   --set-string serviceAnnotations.prometheus\\.io/port="9150" \
   --set-string serviceAnnotations.prometheus\\.io/scrape="true"
   ```

1. 输入以下命令以确认正在运行的服务的注释：

   ```
   kubectl describe service my-memcached-metrics -n memcached-sample
   ```

   您应该看到以下两个注释：

   ```
   Annotations:   prometheus.io/port: 9150
                  prometheus.io/scrape: true
   ```

**卸载 memcached**
+ 输入以下命令：

  ```
  helm uninstall my-memcached --namespace memcached-sample
  kubectl delete namespace memcached-sample
  ```

# 在 Amazon EKS 和 Kubernetes 上设置 Java/JMX 示例工作负载
<a name="ContainerInsights-Prometheus-Sample-Workloads-javajmx"></a>

JMX Exporter 是 Prometheus 的官方导出程序，可以将 JMX MBeans 作为 Prometheus 指标进行抓取和公开。有关详细信息，请参阅 [prometheus/jmx\$1exporter](https://github.com/prometheus/jmx_exporter)。

Container Insights 可以使用 JMX Exporter 从 Java 虚拟机 (JVM)、Java 和 Tomcat (Catalina) 收集预定义的 Prometheus 指标。

## 默认 Prometheus 抓取配置
<a name="ContainerInsights-Prometheus-Sample-Workloads-javajmx-default"></a>

默认情况下，支持 Prometheus 的 CloudWatch 代理从 Amazon EKS 或 Kubernetes 集群中的每个 pod 上的 `http://CLUSTER_IP:9404/metrics` 抓取 Java/JMX Prometheus 指标。这是通过 Prometheus `kubernetes_sd_config` 的 `role: pod` 发现来完成的。9404 是 Prometheus 为 JMX Exporter 分配的默认端口。有关 `role: pod` 发现的更多信息，请参阅 [pod](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#pod)。您可以将 JMX Exporter 配置为在不同端口或 metrics\$1path 上公开指标。如果您更改了端口或路径，请更新 CloudWatch 代理 config 映射中的默认 jmx scrape\$1config。运行以下命令以获取当前 CloudWatch 代理 Prometheus 配置：

```
kubectl describe cm prometheus-config -n amazon-cloudwatch
```

要更改的字段是 `/metrics` 和 `regex: '.*:9404$'` 字段，如以下示例中突出显示所示。

```
job_name: 'kubernetes-jmx-pod'
sample_limit: 10000
metrics_path: /metrics
kubernetes_sd_configs:
- role: pod
relabel_configs:
- source_labels: [__address__]
  action: keep
  regex: '.*:9404$'
- action: replace
  regex: (.+)
  source_labels:
```

## 其他 Prometheus 抓取配置
<a name="ContainerInsights-Prometheus-Sample-Workloads-javajmx-other"></a>

如果您通过 Kubernetes Service 使用 Java/JMX Prometheus 导出器公开在一组 pod 上运行的应用程序，您还可以切换到使用 Prometheus `kubernetes_sd_config` 的 `role: service` 发现或 `role: endpoint` 发现。有关这些发现方法的更多信息，请参阅[服务](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#service)、[端点](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#endpoints) 和 [<kubernetes\$1sd\$1config>](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#kubernetes_sd_config)。

这两种服务发现模式提供了更多元标签，这对构建 CloudWatch 指标维度大有裨益。例如，您可以将 `__meta_kubernetes_service_name` 其重新标记为 `Service` 并将其包含在指标维度中。有关自定义 CloudWatch 指标及其维度的更多信息，请参阅 [Prometheus 的 CloudWatch 代理配置](ContainerInsights-Prometheus-Setup-configure-ECS.md#ContainerInsights-Prometheus-Setup-cw-agent-config)。

## 带有 JMX Exporter 的 Docker 镜像
<a name="ContainerInsights-Prometheus-Sample-Workloads-javajmx-docker"></a>

接下来，构建 Docker 镜像。以下各节提供了两个示例 Dockerfiles。

构建镜像后，请将其加载到 Amazon EKS 或 Kubernetes 中，然后运行以下命令以验证 `JMX_EXPORTER` 是否在端口 9404 上公开 Prometheus 指标。使用正在运行的 pod 名称替换 *\$1JAR\$1SAMPLE\$1TRAFFIC\$1POD*，并使用您的应用程序命名空间替换 *\$1JAR\$1SAMPLE\$1TRAFFIC\$1NAMESPACE*。

如果您在具有 Fargate 启动类型的集群上运行 JMX Exporter，则在执行此过程中的步骤之前，您还需要设置 Fargate 配置文件。要设置配置文件，请输入以下命令。将 *MyCluster* 替换为您的集群的名称。

```
eksctl create fargateprofile --cluster MyCluster \
--namespace $JAR_SAMPLE_TRAFFIC_NAMESPACE\
 --name $JAR_SAMPLE_TRAFFIC_NAMESPACE
```

```
kubectl exec $JAR_SAMPLE_TRAFFIC_POD -n $JARCAT_SAMPLE_TRAFFIC_NAMESPACE -- curl http://localhost:9404
```

## 示例：具有 Prometheus 指标的 Apache Tomcat Docker 镜像
<a name="ContainerInsights-Prometheus-Sample-Workloads-javajmx-tomcat"></a>

默认情况下，Apache Tomcat 服务器公开 JMX MBeans。您可以将 JMX Exporter 与 Tomcat 集成，以便将 JMX MBeans 作为 Prometheus 指标公开。以下示例 Dockerfile 显示了构建测试镜像的步骤：

```
# From Tomcat 9.0 JDK8 OpenJDK 
FROM tomcat:9.0-jdk8-openjdk 

RUN mkdir -p /opt/jmx_exporter

COPY ./jmx_prometheus_javaagent-0.12.0.jar /opt/jmx_exporter
COPY ./config.yaml /opt/jmx_exporter
COPY ./setenv.sh /usr/local/tomcat/bin 
COPY your web application.war /usr/local/tomcat/webapps/

RUN chmod  o+x /usr/local/tomcat/bin/setenv.sh

ENTRYPOINT ["catalina.sh", "run"]
```

下面的列表解释了此 Dockerfile 中的四个 `COPY` 行。
+ 从 [https://github.com/prometheus/jmx\$1exporter](https://github.com/prometheus/jmx_exporter) 下载最新的 JMX Exporter jar 文件。
+ `config.yaml` 是 JMX Exporter 配置文件。有关更多信息，请参阅 [https://github.com/prometheus/jmx\$1exporter\$1Configuration](https://github.com/prometheus/jmx_exporter#Configuration )。

  以下是 Java 和 Tomcat 的示例配置文件：

  ```
  lowercaseOutputName: true
  lowercaseOutputLabelNames: true
  
  rules:
  - pattern: 'java.lang<type=OperatingSystem><>(FreePhysicalMemorySize|TotalPhysicalMemorySize|FreeSwapSpaceSize|TotalSwapSpaceSize|SystemCpuLoad|ProcessCpuLoad|OpenFileDescriptorCount|AvailableProcessors)'
    name: java_lang_OperatingSystem_$1
    type: GAUGE
  
  - pattern: 'java.lang<type=Threading><>(TotalStartedThreadCount|ThreadCount)'
    name: java_lang_threading_$1
    type: GAUGE
  
  - pattern: 'Catalina<type=GlobalRequestProcessor, name=\"(\w+-\w+)-(\d+)\"><>(\w+)'
    name: catalina_globalrequestprocessor_$3_total
    labels:
      port: "$2"
      protocol: "$1"
    help: Catalina global $3
    type: COUNTER
  
  - pattern: 'Catalina<j2eeType=Servlet, WebModule=//([-a-zA-Z0-9+&@#/%?=~_|!:.,;]*[-a-zA-Z0-9+&@#/%=~_|]), name=([-a-zA-Z0-9+/$%~_-|!.]*), J2EEApplication=none, J2EEServer=none><>(requestCount|maxTime|processingTime|errorCount)'
    name: catalina_servlet_$3_total
    labels:
      module: "$1"
      servlet: "$2"
    help: Catalina servlet $3 total
    type: COUNTER
  
  - pattern: 'Catalina<type=ThreadPool, name="(\w+-\w+)-(\d+)"><>(currentThreadCount|currentThreadsBusy|keepAliveCount|pollerThreadCount|connectionCount)'
    name: catalina_threadpool_$3
    labels:
      port: "$2"
      protocol: "$1"
    help: Catalina threadpool $3
    type: GAUGE
  
  - pattern: 'Catalina<type=Manager, host=([-a-zA-Z0-9+&@#/%?=~_|!:.,;]*[-a-zA-Z0-9+&@#/%=~_|]), context=([-a-zA-Z0-9+/$%~_-|!.]*)><>(processingTime|sessionCounter|rejectedSessions|expiredSessions)'
    name: catalina_session_$3_total
    labels:
      context: "$2"
      host: "$1"
    help: Catalina session $3 total
    type: COUNTER
  
  - pattern: ".*"
  ```
+ `setenv.sh` 是一个 Tomcat 启动脚本，用于启动 JMX Exporter 和 Tomcat，并在本地主机的端口 9404 上公开 Prometheus 指标。它还为 JMX Exporter 提供 `config.yaml` 文件路径。

  ```
  $ cat setenv.sh 
  export JAVA_OPTS="-javaagent:/opt/jmx_exporter/jmx_prometheus_javaagent-0.12.0.jar=9404:/opt/jmx_exporter/config.yaml $JAVA_OPTS"
  ```
+ 您的 Web 应用程序 .war 是由 Tomcat 加载的 Web 应用程序 `war` 文件。

使用此配置构建 Docker 镜像并将其上载到镜像存储库。

## 示例：具有 Prometheus 指标的 Java Jar 应用程序 Docker 镜像
<a name="ContainerInsights-Prometheus-Sample-Workloads-javajmx-jar"></a>

以下示例 Dockerfile 显示了构建测试镜像的步骤：

```
# Alpine Linux with OpenJDK JRE
FROM openjdk:8-jre-alpine

RUN mkdir -p /opt/jmx_exporter

COPY ./jmx_prometheus_javaagent-0.12.0.jar /opt/jmx_exporter
COPY ./SampleJavaApplication-1.0-SNAPSHOT.jar /opt/jmx_exporter
COPY ./start_exporter_example.sh /opt/jmx_exporter
COPY ./config.yaml /opt/jmx_exporter

RUN chmod -R o+x /opt/jmx_exporter
RUN apk add curl

ENTRYPOINT exec /opt/jmx_exporter/start_exporter_example.sh
```

下面的列表解释了此 Dockerfile 中的四个 `COPY` 行。
+ 从 [https://github.com/prometheus/jmx\$1exporter](https://github.com/prometheus/jmx_exporter) 下载最新的 JMX Exporter jar 文件。
+ `config.yaml` 是 JMX Exporter 配置文件。有关更多信息，请参阅 [https://github.com/prometheus/jmx\$1exporter\$1Configuration](https://github.com/prometheus/jmx_exporter#Configuration )。

  以下是 Java 和 Tomcat 的示例配置文件：

  ```
  lowercaseOutputName: true
  lowercaseOutputLabelNames: true
  
  rules:
  - pattern: 'java.lang<type=OperatingSystem><>(FreePhysicalMemorySize|TotalPhysicalMemorySize|FreeSwapSpaceSize|TotalSwapSpaceSize|SystemCpuLoad|ProcessCpuLoad|OpenFileDescriptorCount|AvailableProcessors)'
    name: java_lang_OperatingSystem_$1
    type: GAUGE
  
  - pattern: 'java.lang<type=Threading><>(TotalStartedThreadCount|ThreadCount)'
    name: java_lang_threading_$1
    type: GAUGE
  
  - pattern: 'Catalina<type=GlobalRequestProcessor, name=\"(\w+-\w+)-(\d+)\"><>(\w+)'
    name: catalina_globalrequestprocessor_$3_total
    labels:
      port: "$2"
      protocol: "$1"
    help: Catalina global $3
    type: COUNTER
  
  - pattern: 'Catalina<j2eeType=Servlet, WebModule=//([-a-zA-Z0-9+&@#/%?=~_|!:.,;]*[-a-zA-Z0-9+&@#/%=~_|]), name=([-a-zA-Z0-9+/$%~_-|!.]*), J2EEApplication=none, J2EEServer=none><>(requestCount|maxTime|processingTime|errorCount)'
    name: catalina_servlet_$3_total
    labels:
      module: "$1"
      servlet: "$2"
    help: Catalina servlet $3 total
    type: COUNTER
  
  - pattern: 'Catalina<type=ThreadPool, name="(\w+-\w+)-(\d+)"><>(currentThreadCount|currentThreadsBusy|keepAliveCount|pollerThreadCount|connectionCount)'
    name: catalina_threadpool_$3
    labels:
      port: "$2"
      protocol: "$1"
    help: Catalina threadpool $3
    type: GAUGE
  
  - pattern: 'Catalina<type=Manager, host=([-a-zA-Z0-9+&@#/%?=~_|!:.,;]*[-a-zA-Z0-9+&@#/%=~_|]), context=([-a-zA-Z0-9+/$%~_-|!.]*)><>(processingTime|sessionCounter|rejectedSessions|expiredSessions)'
    name: catalina_session_$3_total
    labels:
      context: "$2"
      host: "$1"
    help: Catalina session $3 total
    type: COUNTER
  
  - pattern: ".*"
  ```
+ `start_exporter_example.sh` 是用于启动导出了 Prometheus 指标的 JAR 应用程序的脚本。它还为 JMX Exporter 提供 `config.yaml` 文件路径。

  ```
  $ cat start_exporter_example.sh 
  java -javaagent:/opt/jmx_exporter/jmx_prometheus_javaagent-0.12.0.jar=9404:/opt/jmx_exporter/config.yaml -cp  /opt/jmx_exporter/SampleJavaApplication-1.0-SNAPSHOT.jar com.gubupt.sample.app.App
  ```
+ SampleJavaApplication-1.0-SNAPSHOT.jar 是示例 Java 应用程序 jar 文件。将其替换为要监控的 Java 应用程序。

使用此配置构建 Docker 镜像并将其上载到镜像存储库。

# 使用 Amazon EKS 和 Kubernetes 上的指标导出器设置 HAProxy
<a name="ContainerInsights-Prometheus-Sample-Workloads-haproxy"></a>

HAProxy 是一个开源代理应用程序。有关更多信息，请参阅 [HAProxy](https://www.haproxy.org)。

如果您在具有 Fargate 启动类型的集群上运行 HAProxy，则在执行此过程中的步骤之前，您需要设置 Fargate 配置文件。要设置配置文件，请输入以下命令。将 *MyCluster* 替换为您的集群的名称。

```
eksctl create fargateprofile --cluster MyCluster \
--namespace haproxy-ingress-sample --name haproxy-ingress-sample
```

**安装带有 Metric Exporter 的 HAProxy 以测试 Container Insights Prometheus 支持**

1. 输入以下命令以添加 Helm incubator 存储库：

   ```
   helm repo add haproxy-ingress https://haproxy-ingress.github.io/charts
   ```

1. 输入以下命令以创建新的命名空间：

   ```
   kubectl create namespace haproxy-ingress-sample
   ```

1. 输入以下命令来安装 HAProxy：

   ```
   helm install haproxy haproxy-ingress/haproxy-ingress \
   --namespace haproxy-ingress-sample \
   --set defaultBackend.enabled=true \
   --set controller.stats.enabled=true \
   --set controller.metrics.enabled=true \
   --set-string controller.metrics.service.annotations."prometheus\.io/port"="9101" \
   --set-string controller.metrics.service.annotations."prometheus\.io/scrape"="true"
   ```

1. 输入以下命令以确认服务的注释：

   ```
   kubectl describe service haproxy-haproxy-ingress-metrics -n haproxy-ingress-sample
   ```

   您应该看到以下注释。

   ```
   Annotations:   prometheus.io/port: 9101
                  prometheus.io/scrape: true
   ```

**卸载 HAProxy**
+ 输入以下命令：

  ```
  helm uninstall haproxy --namespace haproxy-ingress-sample
  kubectl delete namespace haproxy-ingress-sample
  ```

# 添加新 Prometheus 抓取目标的教程：Amazon EKS 和 Kubernetes 集群上的 Redis OSS
<a name="ContainerInsights-Prometheus-Setup-redis-eks"></a>

本教程提供了在 Amazon EKS 和 Kubernetes 上抓取示例 Redis OSS 应用程序的 Prometheus 指标的实践介绍。Redis OSS（https://redis.io/）是一个开源（获得 BSD 许可）的内存数据结构存储，用作数据库、缓存和消息代理。有关更多信息，请参阅 [ redis](https://redis.io/)。

redis\$1exporter（获得 MIT 许可证）用于在指定端口（默认值：0.0.0.0:9121）上公开 Redis OSS prometheus 指标。有关更多信息，请参阅 [redis\$1exporter](https://github.com/oliver006/redis_exporter)。

本教程使用了以下两个 Docker Hub 存储库中的 Docker 镜像：
+ [redis](https://hub.docker.com/_/redis?tab=description)
+ [redis\$1exporter](https://hub.docker.com/r/oliver006/redis_exporter)

**安装公开 Prometheus 指标的示例 Redis OSS 工作负载**

1. 为示例 Redis OSS 工作负载设置命名空间。

   ```
   REDIS_NAMESPACE=redis-sample
   ```

1. 如果您在具有 Fargate 启动类型的集群上运行 Redis OSS，则需要设置 Fargate 配置文件。要设置配置文件，请输入以下命令。将 *MyCluster* 替换为您的集群的名称。

   ```
   eksctl create fargateprofile --cluster MyCluster \
   --namespace $REDIS_NAMESPACE --name $REDIS_NAMESPACE
   ```

1. 输入以下命令以安装示例 Redis OSS 工作负载。

   ```
   curl https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/sample_traffic/redis/redis-traffic-sample.yaml \
   | sed "s/{{namespace}}/$REDIS_NAMESPACE/g" \
   | kubectl apply -f -
   ```

1. 安装包括一个名为 `my-redis-metrics` 的服务，该服务在端口 9121 上公开 Redis OSS Prometheus 指标。输入以下命令以获取该服务的详细信息：

   ```
   kubectl describe service/my-redis-metrics  -n $REDIS_NAMESPACE
   ```

   在结果的 `Annotations` 部分，您将看到与 CloudWatch 代理的 Prometheus 抓取配置相匹配的两个注释，以便其可以自动发现工作负载：

   ```
   prometheus.io/port: 9121
   prometheus.io/scrape: true
   ```

   相关的 Prometheus 抓取配置可以在 `kubernetes-eks.yaml` 或 `kubernetes-k8s.yaml` 部分的 `- job_name: kubernetes-service-endpoints` 中找到。

**开始在 CloudWatch 中收集 Redis OSS Prometheus 指标**

1. 通过输入以下任一命令，下载 `kubernetes-eks.yaml` 或 `kubernetes-k8s.yaml` 文件的最新版本。对于具有 EC2 启动类型的 Amazon EKS 集群，请输入此命令。

   ```
   curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/prometheus-eks.yaml
   ```

   对于具有 Fargate 启动类型的 Amazon EKS 集群，请输入此命令。

   ```
   curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/prometheus-eks-fargate.yaml
   ```

   对于在 Amazon EC2 实例上运行的 Kubernetes 集群，请输入此命令。

   ```
   curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/prometheus-k8s.yaml
   ```

1. 使用文本编辑器打开文件，然后找到 `cwagentconfig.json` 部分。添加以下子部分并保存更改。确保遵循现有模式缩进。

   ```
   {
     "source_labels": ["pod_name"],
     "label_matcher": "^redis-instance$",
     "dimensions": [["Namespace","ClusterName"]],
     "metric_selectors": [
       "^redis_net_(in|out)put_bytes_total$",
       "^redis_(expired|evicted)_keys_total$",
       "^redis_keyspace_(hits|misses)_total$",
       "^redis_memory_used_bytes$",
       "^redis_connected_clients$"
     ]
   },
   {
     "source_labels": ["pod_name"],
     "label_matcher": "^redis-instance$",
     "dimensions": [["Namespace","ClusterName","cmd"]],
     "metric_selectors": [
       "^redis_commands_total$"
     ]
   },
   {
     "source_labels": ["pod_name"],
     "label_matcher": "^redis-instance$",
     "dimensions": [["Namespace","ClusterName","db"]],
     "metric_selectors": [
       "^redis_db_keys$"
     ]
   },
   ```

   您添加的部分会将 Redis OSS 指标放入 CloudWatch 代理允许列表中。有关这些指标的列表，请参阅以下部分。

1. 如果您已在此集群中部署了具有 Prometheus 支持的 CloudWatch 代理，则必须通过输入以下命令将其删除。

   ```
   kubectl delete deployment cwagent-prometheus -n amazon-cloudwatch
   ```

1. 通过输入以下任一命令，使用更新的配置部署 CloudWatch 代理。替换 *MyCluster* 和 *region（区域）*以匹配您的设置。

   对于具有 EC2 启动类型的 Amazon EKS 集群，请输入此命令。

   ```
   kubectl apply -f prometheus-eks.yaml
   ```

   对于具有 Fargate 启动类型的 Amazon EKS 集群，请输入此命令。

   ```
   cat prometheus-eks-fargate.yaml \
   | sed "s/{{cluster_name}}/MyCluster/;s/{{region_name}}/region/" \
   | kubectl apply -f -
   ```

   对于 Kubernetes 集群，请输入此命令。

   ```
   cat prometheus-k8s.yaml \
   | sed "s/{{cluster_name}}/MyCluster/;s/{{region_name}}/region/" \
   | kubectl apply -f -
   ```

## 查看 Redis OSS Prometheus 指标
<a name="ContainerInsights-Prometheus-Setup-redis-eks-view"></a>

本教程会将以下指标发送到 CloudWatch 中的 **ContainerInsights/Prometheus** 命名空间。您可以使用 CloudWatch 控制台查看该命名空间中的指标。


| 指标名称 | Dimensions | 
| --- | --- | 
|  `redis_net_input_bytes_total` |  ClusterName、`Namespace`  | 
|  `redis_net_output_bytes_total` |  ClusterName、`Namespace`  | 
|  `redis_expired_keys_total` |  ClusterName、`Namespace`  | 
|  `redis_evicted_keys_total` |  ClusterName、`Namespace`  | 
|  `redis_keyspace_hits_total` |  ClusterName、`Namespace`  | 
|  `redis_keyspace_misses_total` |  ClusterName、`Namespace`  | 
|  `redis_memory_used_bytes` |  ClusterName、`Namespace`  | 
|  `redis_connected_clients` |  ClusterName、`Namespace`  | 
|  `redis_commands_total` |  ClusterName、`Namespace`、cmd  | 
|  `redis_db_keys` |  Cluster、`Namespace`、db  | 

**注意**  
**cmd** 维度的值可以是 `append`、`client`、`command`、`config`、`dbsize`、`flushall`、`get`、`incr`、`info`、`latency` 或 `slowlog`。  
**db** 维度的值可以从 `db0` 到 `db15`。

您还可以为 Redis OSS Prometheus 指标创建 CloudWatch 控制面板。

**为 Redis OSS Prometheus 指标创建控制面板**

1. 创建环境变量，替换以下值以匹配部署。

   ```
   DASHBOARD_NAME=your_cw_dashboard_name
   REGION_NAME=your_metric_region_such_as_us-east-1
   CLUSTER_NAME=your_k8s_cluster_name_here
   NAMESPACE=your_redis_service_namespace_here
   ```

1. 输入以下命令以创建控制面板。

   ```
   curl https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/sample_cloudwatch_dashboards/redis/cw_dashboard_redis.json \
   | sed "s/{{YOUR_AWS_REGION}}/${REGION_NAME}/g" \
   | sed "s/{{YOUR_CLUSTER_NAME}}/${CLUSTER_NAME}/g" \
   | sed "s/{{YOUR_NAMESPACE}}/${NAMESPACE}/g" \
   ```

# CloudWatch 代理的 Prometheus 指标类型转换
<a name="ContainerInsights-Prometheus-metrics-conversion"></a>

Prometheus 客户端库提供四种核心指标类型：
+ 计数器
+ 计量表
+ 摘要
+ 直方图

CloudWatch 代理支持计数器、计量表和汇总指标类型。

 CloudWatch 代理会删除具有不受支持的直方图指标类型的 Prometheus 指标。有关更多信息，请参阅 [录入丢弃的 Prometheus 指标](ContainerInsights-Prometheus-troubleshooting-EKS.md#ContainerInsights-Prometheus-troubleshooting-droppedmetrics)。

**计量表指标**

Prometheus 计量表指标是表示可以任意上下的单个数值的度量。CloudWatch 代理会抓取计量表指标并直接发送这些值。

**计数器指标**

Prometheus 计数器指标是一个累积指标，表示单个单调增加的计数器，其值只能增加或重置为零。CloudWatch 代理根据上次抓取计算增量，并将增量值作为日志事件中的指标值发送。因此，CloudWatch 代理将从第二次抓取开始生成一个日志事件，并继续进行后续抓取（如果有）。

**汇总指标**

Prometheus 汇总指标是一种复杂的指标类型，由多个数据点表示。它提供观察的总数和所有观察值的总和。它在滑动时间窗口内计算可配置的分位数。

汇总指标的总和和计数是累积的，但分位数不是。以下示例显示了分位数的方差。

```
# TYPE go_gc_duration_seconds summary
go_gc_duration_seconds{quantile="0"} 7.123e-06
go_gc_duration_seconds{quantile="0.25"} 9.204e-06
go_gc_duration_seconds{quantile="0.5"} 1.1065e-05
go_gc_duration_seconds{quantile="0.75"} 2.8731e-05
go_gc_duration_seconds{quantile="1"} 0.003841496
go_gc_duration_seconds_sum 0.37630427
go_gc_duration_seconds_count 9774
```

CloudWatch 代理以与处理计数器指标相同的方式处理汇总指标的总和和计数，如上一节所述。CloudWatch 代理会保留最初报告的分位数值。

# CloudWatch 代理收集的 Prometheus 指标
<a name="ContainerInsights-Prometheus-metrics"></a>

具有 Prometheus 支持的 CloudWatch 代理可自动从多个服务和工作负载收集指标。以下部分列出了默认情况下收集的指标。您还可以将代理配置为从这些服务收集更多指标，并从其他应用程序和服务收集 Prometheus 指标。有关可收集的其他指标的更多信息，请参阅 [Prometheus 的 CloudWatch 代理配置](ContainerInsights-Prometheus-Setup-configure-ECS.md#ContainerInsights-Prometheus-Setup-cw-agent-config)。

从 Amazon EKS 和 Kubernetes 集群收集的 Prometheus 指标位于 **ContainerInsights/Prometheus** 命名空间中。从 Amazon ECS 集群收集的 Prometheus 指标位于 **ECS/ContainerInsights/Prometheus** 命名空间中。

**Topics**
+ [App Mesh 的 Prometheus 指标](#ContainerInsights-Prometheus-metrics-appmesh)
+ [NGINX 的 Prometheus 指标](#ContainerInsights-Prometheus-metrics-nginx)
+ [Memcached 的 Prometheus 指标](#ContainerInsights-Prometheus-metrics-memcached)
+ [Java/JMX 的 Prometheus 指标](#ContainerInsights-Prometheus-metrics-jmx)
+ [HAProxy 的 Prometheus 指标](#ContainerInsights-Prometheus-metrics-haproxy)

## App Mesh 的 Prometheus 指标
<a name="ContainerInsights-Prometheus-metrics-appmesh"></a>

从 App Mesh 自动收集以下指标。

**Amazon EKS 和 Kubernetes 集群上 App Mesh 的 Prometheus 指标**


| 指标名称 | Dimensions | 
| --- | --- | 
|  `envoy_http_downstream_rq_total` |  ClusterName、`Namespace`  | 
|  `envoy_http_downstream_rq_xx` |  ClusterName、`Namespace` ClusterName、`Namespace`、envoy\$1http\$1conn\$1manager\$1prefix、envoy\$1response\$1code\$1class  | 
|  `envoy_cluster_upstream_cx_rx_bytes_total` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_upstream_cx_tx_bytes_total` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_membership_healthy` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_membership_total` |  ClusterName、`Namespace`  | 
|  `envoy_server_memory_heap_size` |  ClusterName、`Namespace`  | 
|  `envoy_server_memory_allocated` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_upstream_cx_connect_timeout` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_upstream_rq_pending_failure_eject` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_upstream_rq_pending_overflow` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_upstream_rq_timeout` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_upstream_rq_try_per_timeout` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_upstream_rq_rx_reset` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_upstream_cx_destroy_local_with_active_rq` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_upstream_cx_destroy_remote_active_rq` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_upstream_rq_maintenance_mode` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_upstream_flow_control_paused_reading_total` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_upstream_flow_control_resumed_reading_total` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_upstream_flow_control_backed_up_total` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_upstream_flow_control_drained_total` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_upstream_rq_retry` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_upstream_rq_retry_success` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_upstream_rq_retry_overflow` |  ClusterName、`Namespace`  | 
|  `envoy_server_live` |  ClusterName、`Namespace`  | 
|  `envoy_server_uptime` |  ClusterName、`Namespace`  | 

**Amazon ECS 集群上 App Mesh 的 Prometheus 指标**


| 指标名称 | Dimensions | 
| --- | --- | 
|  `envoy_http_downstream_rq_total` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_http_downstream_rq_xx` |  ClusterName、`TaskDefinitionFamily` | 
|  `envoy_cluster_upstream_cx_rx_bytes_total` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_upstream_cx_tx_bytes_total` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_membership_healthy` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_membership_total` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_server_memory_heap_size` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_server_memory_allocated` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_upstream_cx_connect_timeout` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_upstream_rq_pending_failure_eject` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_upstream_rq_pending_overflow` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_upstream_rq_timeout` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_upstream_rq_try_per_timeout` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_upstream_rq_rx_reset` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_upstream_cx_destroy_local_with_active_rq` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_upstream_cx_destroy_remote_active_rq` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_upstream_rq_maintenance_mode` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_upstream_flow_control_paused_reading_total` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_upstream_flow_control_resumed_reading_total` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_upstream_flow_control_backed_up_total` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_upstream_flow_control_drained_total` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_upstream_rq_retry` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_upstream_rq_retry_success` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_upstream_rq_retry_overflow` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_server_live` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_server_uptime` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_http_downstream_rq_xx` |  ClusterName、TaskDefinitionFamily、envoy\$1http\$1conn\$1manager\$1prefix、envoy\$1response\$1code\$1class ClusterName、TaskDefinitionFamily、envoy\$1response\$1code\$1class | 

**注意**  
`TaskDefinitionFamily` 是网格的 Kubernetes 命名空间。  
`envoy_http_conn_manager_prefix` 的值可以是 `ingress`、`egress` 或 `admin`。  
`envoy_response_code_class` 的值可以是 `1`（代表 `1xx`）、`2`（代表 `2xx`）、`3`（代表 `3xx`）、`4`（代表 `4xx`）或 `5`（代表 `5xx`）。

## NGINX 的 Prometheus 指标
<a name="ContainerInsights-Prometheus-metrics-nginx"></a>

从 Amazon EKS 和 Kubernetes 集群上的 NGINX 自动收集以下指标。


| 指标名称 | Dimensions | 
| --- | --- | 
|  `nginx_ingress_controller_nginx_process_cpu_seconds_total` |  ClusterName、`Namespace`、Service  | 
|  `nginx_ingress_controller_success` |  ClusterName、`Namespace`、Service  | 
|  `nginx_ingress_controller_requests` |  ClusterName、`Namespace`、Service  | 
|  `nginx_ingress_controller_nginx_process_connections` |  ClusterName、`Namespace`、Service  | 
|  `nginx_ingress_controller_nginx_process_connections_total` |  ClusterName、`Namespace`、Service  | 
|  `nginx_ingress_controller_nginx_process_resident_memory_bytes` |  ClusterName、`Namespace`、Service  | 
|  `nginx_ingress_controller_config_last_reload_successful` |  ClusterName、`Namespace`、Service  | 
|  `nginx_ingress_controller_requests` |  ClusterName、`Namespace`、Service、status  | 

## Memcached 的 Prometheus 指标
<a name="ContainerInsights-Prometheus-metrics-memcached"></a>

从 Amazon EKS 和 Kubernetes 集群上的 Memcached 中自动收集以下指标。


| 指标名称 | Dimensions | 
| --- | --- | 
|  `memcached_current_items` |  ClusterName、`Namespace`、Service  | 
|  `memcached_current_connections` |  ClusterName、`Namespace`、Service  | 
|  `memcached_limit_bytes` |  ClusterName、`Namespace`、Service  | 
|  `memcached_current_bytes` |  ClusterName、`Namespace`、Service  | 
|  `memcached_written_bytes_total` |  ClusterName、`Namespace`、Service  | 
|  `memcached_read_bytes_total` |  ClusterName、`Namespace`、Service  | 
|  `memcached_items_evicted_total` |  ClusterName、`Namespace`、Service  | 
|  `memcached_items_reclaimed_total` |  ClusterName、`Namespace`、Service  | 
|  `memcached_commands_total` |  ClusterName、`Namespace`、Service ClusterName、`Namespace`、Service、command ClusterName、`Namespace`、Service、status、command  | 

## Java/JMX 的 Prometheus 指标
<a name="ContainerInsights-Prometheus-metrics-jmx"></a>

**在 Amazon EKS 和 Kubernetes 集群上收集的指标**

在 Amazon EKS 和 Kubernetes 集群上，Container Insights 可以使用 JMX Exporter 从 Java 虚拟机 (JVM)、Java 和 Tomcat (Catalina) 收集以下预定义的 Prometheus 指标。有关更多信息，请参阅 Github 上的 [ prometheus/jmx\$1exporter](https://github.com/prometheus/jmx_exporter)。

**Amazon EKS 和 Kubernetes 集群上的 Java/JMX**


| 指标名称 | Dimensions | 
| --- | --- | 
|  `jvm_classes_loaded` |  `ClusterName`, `Namespace`  | 
|  `jvm_threads_current` |  `ClusterName`, `Namespace`  | 
|  `jvm_threads_daemon` |  `ClusterName`, `Namespace`  | 
|  `java_lang_operatingsystem_totalswapspacesize` |  `ClusterName`, `Namespace`  | 
|  `java_lang_operatingsystem_systemcpuload` |  `ClusterName`, `Namespace`  | 
|  `java_lang_operatingsystem_processcpuload` |  `ClusterName`, `Namespace`  | 
|  `java_lang_operatingsystem_freeswapspacesize` |  `ClusterName`, `Namespace`  | 
|  `java_lang_operatingsystem_totalphysicalmemorysize` |  `ClusterName`, `Namespace`  | 
|  `java_lang_operatingsystem_freephysicalmemorysize` |  `ClusterName`, `Namespace`  | 
|  `java_lang_operatingsystem_openfiledescriptorcount` |  `ClusterName`, `Namespace`  | 
|  `java_lang_operatingsystem_availableprocessors` |  `ClusterName`, `Namespace`  | 
|  `jvm_memory_bytes_used` |  `ClusterName`、`Namespace`、area  | 
|  `jvm_memory_pool_bytes_used` |  `ClusterName`、`Namespace`、pool  | 

**注意**  
`area` 维度的值可以是 `heap` 或 `nonheap`。  
`pool` 维度的值可以是 `Tenured Gen`、`Compress Class Space`、`Survivor Space`、`Eden Space`、`Code Cache` 或 `Metaspace`。

**Amazon EKS 和 Kubernetes 集群上的 Tomcat/JMX**

除了上表中的 Java/JMX 指标外，还收集 Tomcat 工作负载的以下指标。


| 指标名称 | Dimensions | 
| --- | --- | 
|  `catalina_manager_activesessions` |  `ClusterName`, `Namespace`  | 
|  `catalina_manager_rejectedsessions` |  `ClusterName`, `Namespace`  | 
|  `catalina_globalrequestprocessor_bytesreceived` |  `ClusterName`, `Namespace`  | 
|  `catalina_globalrequestprocessor_bytessent` |  `ClusterName`, `Namespace`  | 
|  `catalina_globalrequestprocessor_requestcount` |  `ClusterName`, `Namespace`  | 
|  `catalina_globalrequestprocessor_errorcount` |  `ClusterName`, `Namespace`  | 
|  `catalina_globalrequestprocessor_processingtime` |  `ClusterName`, `Namespace`  | 

**Amazon ECS 集群上的 Java/JMX**


| 指标名称 | Dimensions | 
| --- | --- | 
|  `jvm_classes_loaded` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `jvm_threads_current` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `jvm_threads_daemon` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `java_lang_operatingsystem_totalswapspacesize` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `java_lang_operatingsystem_systemcpuload` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `java_lang_operatingsystem_processcpuload` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `java_lang_operatingsystem_freeswapspacesize` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `java_lang_operatingsystem_totalphysicalmemorysize` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `java_lang_operatingsystem_freephysicalmemorysize` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `java_lang_operatingsystem_openfiledescriptorcount` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `java_lang_operatingsystem_availableprocessors` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `jvm_memory_bytes_used` |  `ClusterName`、TaskDefinitionFamily、area  | 
|  `jvm_memory_pool_bytes_used` |  `ClusterName`、TaskDefinitionFamily、pool  | 

**注意**  
`area` 维度的值可以是 `heap` 或 `nonheap`。  
`pool` 维度的值可以是 `Tenured Gen`、`Compress Class Space`、`Survivor Space`、`Eden Space`、`Code Cache` 或 `Metaspace`。

**Amazon ECS 集群上的 Tomcat/JMX**

除上表中的 Java/JMX 指标外，还收集了 Amazon ECS 集群上 Tomcat 工作负载的以下指标。


| 指标名称 | Dimensions | 
| --- | --- | 
|  `catalina_manager_activesessions` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `catalina_manager_rejectedsessions` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `catalina_globalrequestprocessor_bytesreceived` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `catalina_globalrequestprocessor_bytessent` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `catalina_globalrequestprocessor_requestcount` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `catalina_globalrequestprocessor_errorcount` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `catalina_globalrequestprocessor_processingtime` |  `ClusterName`, `TaskDefinitionFamily`  | 

## HAProxy 的 Prometheus 指标
<a name="ContainerInsights-Prometheus-metrics-haproxy"></a>

从 Amazon EKS 和 Kubernetes 集群上的 HAProxy 自动收集以下指标。

收集的指标取决于您使用的 HAProxy Ingress 版本。有关 HAProxy Ingress 及其版本的更多信息，请参阅 [haproxy-ingress](https://artifacthub.io/packages/helm/haproxy-ingress/haproxy-ingress)。


| 指标名称 | Dimensions | 可用性 | 
| --- | --- | --- | 
|  `haproxy_backend_bytes_in_total` |  `ClusterName`、`Namespace`、Service  | 所有版本的 HAProxy Ingress | 
|  `haproxy_backend_bytes_out_total` |  `ClusterName`、`Namespace`、Service  | 所有版本的 HAProxy Ingress | 
|  `haproxy_backend_connection_errors_total` |  `ClusterName`、`Namespace`、Service  | 所有版本的 HAProxy Ingress | 
|  `haproxy_backend_connections_total` |  `ClusterName`、`Namespace`、Service  | 所有版本的 HAProxy Ingress | 
|  `haproxy_backend_current_sessions` |  `ClusterName`、`Namespace`、Service  | 所有版本的 HAProxy Ingress | 
|  `haproxy_backend_http_responses_total` |  `ClusterName`、`Namespace`、Service、code、backend  | 所有版本的 HAProxy Ingress | 
|  `haproxy_backend_status` |  `ClusterName`、`Namespace`、Service  |  仅在 HAProxy Ingress 0.10 或更高版本中  | 
|  `haproxy_backend_up` |  `ClusterName`、`Namespace`、Service  |  仅在 HAProxy Ingress 0.10 的更早版本中  | 
|  `haproxy_frontend_bytes_in_total` |  `ClusterName`、`Namespace`、Service  | 所有版本的 HAProxy Ingress | 
|  `haproxy_frontend_bytes_out_total` |  `ClusterName`、`Namespace`、Service  | 所有版本的 HAProxy Ingress | 
|  `haproxy_frontend_connections_total` |  `ClusterName`、`Namespace`、Service  | 所有版本的 HAProxy Ingress | 
|  `haproxy_frontend_current_sessions` |  `ClusterName`、`Namespace`、Service  | 所有版本的 HAProxy Ingress | 
|  `haproxy_frontend_http_requests_total` |  `ClusterName`、`Namespace`、Service  | 所有版本的 HAProxy Ingress | 
|  `haproxy_frontend_http_responses_total` |  `ClusterName`、`Namespace`、Service、code、frontend  | 所有版本的 HAProxy Ingress | 
|  `haproxy_frontend_request_errors_total` |  `ClusterName`、`Namespace`、Service  | 所有版本的 HAProxy Ingress | 
|  `haproxy_frontend_requests_denied_total` |  `ClusterName`、`Namespace`、Service  | 所有版本的 HAProxy Ingress | 

**注意**  
`code` 维度的值可以是 `1xx`、`2xx`、`3xx`、`4xx`、`5xx` 或 `other`。  
`backend` 维度的值可以是：  
适用于 HAProxy Ingress 0.0.27 或更早版本的 `http-default-backend`、`http-shared-backend` 或 `httpsback-shared-backend`。
适用于高于 HAProxy Ingress 0.0.27 版本的 `_default_backend`。
`frontend` 维度的值可以是：  
适用于 HAProxy Ingress 0.0.27 或更早版本的 `httpfront-default-backend`、`httpfront-shared-frontend` 或 `httpfronts`。
适用于高于 HAProxy Ingress 0.0.27 版本的 `_front_http` 或 `_front_https`。

# 查看 Prometheus 指标
<a name="ContainerInsights-Prometheus-viewmetrics"></a>

您可以监控所有 Prometheus 指标并发出告警，包括来自 App Mesh、NGINX、Java/JMX、Memcached 和 HAProxy 的精选预聚合指标，以及任何其他您可能已添加的手动配置的 Prometheus 导出程序。有关从其他 Prometheus 导出程序收集指标的更多信息，请参阅[添加新 Prometheus 抓取目标的教程：Prometheus API 服务器指标](ContainerInsights-Prometheus-Setup-configure.md#ContainerInsights-Prometheus-Setup-new-exporters)。

在 CloudWatch 控制台中，Container Insights 提供以下预构建报告：
+ 对于 Amazon EKS 和 Kubernetes 集群，有针对 App Mesh、NGINX、HAPROXY、Memcached 和 Java/JMX 的预构建报告。
+ 对于 Amazon ECS 集群，有针对 App Mesh 和 Java/JMX 的预构建报告。

Container Insights 还为 Container Insights 从中收集策管指标的每个工作负载提供自定义控制面板。您可以从 GitHub 下载这些控制面板 

**查看所有 Prometheus 指标**

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 在导航窗格中，选择**指标**。

1. 在命名空间列表中，选择 **ContainerInsights/Prometheus** 或 **ECS/ContainerInsights/Prometheus**。

1. 在以下列表中选择一组维度。然后选中您要查看的指标旁边的复选框。

**查看有关 Prometheus 指标的预构建报告**

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 在导航窗格中，选择**性能监控**。

1. 在页面顶部附近的下拉框中，选择任一 Prometheus 选项。

   在另一个下拉框中，选择要查看的集群

我们还为 NGINX、App Mesh、Memcached、HAProxy 和 Java/JMX 提供了自定义控制面板。

**使用 Amazon 提供的自定义控制面板**

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 在导航窗格中，选择 **Dashboards（控制面板）**。

1. 选择**创建控制面板**。输入新控制面板的名称，然后选择**创建控制面板**。

1. 在**添加到该控制面板**中，选择**取消**。

1. 依次选择**操作**、**编辑控制面板**。

1. 下载以下 JSON 文件之一：
   + [Github 上的 NGINX 自定义控制面板源代码](https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/sample_cloudwatch_dashboards/nginx-ingress/cw_dashboard_nginx_ingress_controller.json)。
   + [Github 上的 App Mesh 自定义控制面板源代码](https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/sample_cloudwatch_dashboards/appmesh/cw_dashboard_awsappmesh.json)。
   + [Github 上的 Memcached 自定义控制面板源代码](https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/sample_cloudwatch_dashboards/memcached/cw_dashboard_memcached.json)
   + [Github 上的 HAProxy-Ingress 自定义控制面板源代码](https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/sample_cloudwatch_dashboards/haproxy-ingress/cw_dashboard_haproxy_ingress.json)
   + [Github 上的 Java/JMX 自定义控制面板源代码](https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/sample_cloudwatch_dashboards/javajmx/cw_dashboard_javajmx.json)。

1. 使用文本编辑器打开下载的 JSON 文件，然后执行以下更改：
   + 将所有 `{{YOUR_CLUSTER_NAME}}` 字符串替换为您的集群的确切名称。请勿在文本之前或之后添加空格。
   + 将所有 `{{YOUR_REGION}}` 字符串替换为正在运行集群的 AWS 区域。例如，**us-west-1** 请勿在文本之前或之后添加空格。
   + 将所有 `{{YOUR_NAMESPACE}}` 字符串替换为您的工作负载的确切命名空间。
   + 将所有 `{{YOUR_SERVICE_NAME}}` 字符串替换为您的工作负载的确切服务名称。例如，**haproxy-haproxy-ingress-controller-metrics**

1. 复制整个 JSON blob 并将其粘贴到 CloudWatch 控制台的文本框中，替换框中已有的内容。

1. 选择**更新**、**保存控制面板**。

# Prometheus 指标故障排除
<a name="ContainerInsights-Prometheus-troubleshooting"></a>

本节提供有关排除 Prometheus 指标设置故障排除的帮助。

**Topics**
+ [对 Amazon ECS 上的 Prometheus 指标进行故障排除](ContainerInsights-Prometheus-troubleshooting-ECS.md)
+ [Amazon EKS 和 Kubernetes 集群上的 Prometheus 指标故障排除](ContainerInsights-Prometheus-troubleshooting-EKS.md)

# 对 Amazon ECS 上的 Prometheus 指标进行故障排除
<a name="ContainerInsights-Prometheus-troubleshooting-ECS"></a>

本节提供有关对 Amazon ECS 集群上的 Prometheus 指标设置进行故障排除的帮助。

## 我没有看到发送到 CloudWatch Logs 的 Prometheus 指标
<a name="ContainerInsights-Prometheus-troubleshooting-ECS-nometrics"></a>

Prometheus 指标在日志组 **/aws/ecs/containerinsights/cluster-name/Prometheus** 中摄取作为日志事件。如果未创建日志组或未将 Prometheus 指标发送到日志组，您需要首先检查 CloudWatch 代理是否已成功发现 Prometheus 目标。然后检查 CloudWatch 代理的安全组和权限设置。以下步骤会指导您进行调试。

**步骤 1：启用 CloudWatch 代理调试模式**

首先，通过将以下粗体行添加到 CloudFormation 模版文件、`cwagent-ecs-prometheus-metric-for-bridge-host.yaml` 或 `cwagent-ecs-prometheus-metric-for-awsvpc.yaml` 中并保存文件，将 CloudWatch 代理更改为调试模式。然后保存文件。

```
cwagentconfig.json: |
    {
      "agent": {
        "debug": true
      },
      "logs": {
        "metrics_collected": {
```

针对现有堆栈创建一个新的 CloudFormation 变更集。将变更集中的其他参数设置为与现有 CloudFormation 堆栈中相同的值。以下示例适用于使用 EC2 启动类型和桥式网络模式安装在 Amazon ECS 集群中的 CloudWatch 代理。

```
ECS_NETWORK_MODE=bridge
 CREATE_IAM_ROLES=True
ECS_TASK_ROLE_NAME=your_selected_ecs_task_role_name
ECS_EXECUTION_ROLE_NAME=your_selected_ecs_execution_role_name
NEW_CHANGESET_NAME=your_selected_ecs_execution_role_name

aws cloudformation create-change-set --stack-name CWAgent-Prometheus-ECS-${ECS_CLUSTER_NAME}-EC2-${ECS_NETWORK_MODE} \
    --template-body file://cwagent-ecs-prometheus-metric-for-bridge-host.yaml \
    --parameters ParameterKey=ECSClusterName,ParameterValue=$ECS_CLUSTER_NAME \
                 ParameterKey=CreateIAMRoles,ParameterValue=$CREATE_IAM_ROLES \
                 ParameterKey=ECSNetworkMode,ParameterValue=$ECS_NETWORK_MODE \
                 ParameterKey=TaskRoleName,ParameterValue=$ECS_TASK_ROLE_NAME \
                 ParameterKey=ExecutionRoleName,ParameterValue=$ECS_EXECUTION_ROLE_NAME \
    --capabilities CAPABILITY_NAMED_IAM \
    --region $AWS_REGION \
    --change-set-name $NEW_CHANGESET_NAME
```

转至 CloudFormation 控制台查看新的变更集，请参阅 `$NEW_CHANGESET_NAME`。应该对 **CWAgentConfigSSMParameter** 资源应用一项更改。通过输入以下命令执行变更集并重新启动 CloudWatch 代理任务。

```
aws ecs update-service --cluster $ECS_CLUSTER_NAME \
--desired-count 0 \
--service your_service_name_here \
--region $AWS_REGION
```

等待大约 10 秒，然后输入以下命令。

```
aws ecs update-service --cluster $ECS_CLUSTER_NAME \
--desired-count 1 \
--service your_service_name_here \
--region $AWS_REGION
```

**步骤 2：检查 ECS 服务发现日志**

CloudWatch 代理的 ECS 任务定义默认启用以下部分中的日志。日志将发送到 **/ecs/ecs-cwagent-prometheus** 日志组中的 CloudWatch Logs。

```
LogConfiguration:
  LogDriver: awslogs
    Options:
      awslogs-create-group: 'True'
      awslogs-group: "/ecs/ecs-cwagent-prometheus"
      awslogs-region: !Ref AWS::Region
      awslogs-stream-prefix: !Sub 'ecs-${ECSLaunchType}-awsvpc'
```

根据字符串 `ECS_SD_Stats` 筛选日志以获取与 ECS 服务发现相关的指标，如下例所示。

```
2020-09-1T01:53:14Z D! ECS_SD_Stats: AWSCLI_DescribeContainerInstances: 1
2020-09-1T01:53:14Z D! ECS_SD_Stats: AWSCLI_DescribeInstancesRequest: 1
2020-09-1T01:53:14Z D! ECS_SD_Stats: AWSCLI_DescribeTaskDefinition: 2
2020-09-1T01:53:14Z D! ECS_SD_Stats: AWSCLI_DescribeTasks: 1
2020-09-1T01:53:14Z D! ECS_SD_Stats: AWSCLI_ListTasks: 1
2020-09-1T01:53:14Z D! ECS_SD_Stats: Exporter_DiscoveredTargetCount: 1
2020-09-1T01:53:14Z D! ECS_SD_Stats: LRUCache_Get_EC2MetaData: 1
2020-09-1T01:53:14Z D! ECS_SD_Stats: LRUCache_Get_TaskDefinition: 2
2020-09-1T01:53:14Z D! ECS_SD_Stats: LRUCache_Size_ContainerInstance: 1
2020-09-1T01:53:14Z D! ECS_SD_Stats: LRUCache_Size_TaskDefinition: 2
2020-09-1T01:53:14Z D! ECS_SD_Stats: Latency: 43.399783ms
```

特定 ECS 服务发现周期的每个指标的含义如下：
+ **AWSCLI\$1DescribeContainerInstances** – `ECS::DescribeContainerInstances` 进行的 API 调用次数。
+ **AWSCLI\$1DescribeInstancesRequest** – `ECS::DescribeInstancesRequest` 进行的 API 调用次数。
+ **AWSCLI\$1DescribeTaskDefinition** – `ECS::DescribeTaskDefinition` 进行的 API 调用次数。
+ **AWSCLI\$1DescribeTasks** – `ECS::DescribeTasks` 进行的 API 调用次数。
+ **AWSCLI\$1ListTasks** – `ECS::ListTasks` 进行的 API 调用次数。
+ **ExporterDiscoveredTargetCount** – 已发现并成功导出到容器内的目标结果文件中的 Prometheus 目标数量。
+ **LRUCache\$1Get\$1EC2MetaData** – 从缓存中检索容器实例元数据的次数。
+ **LRUCache\$1Get\$1TaskDefinition** – 从缓存中检索 ECS 任务定义元数据的次数。
+ **LRUCache\$1Size\$1ContainerInstance** – 缓存在内存中的唯一容器实例元数据的数量。
+ **LRUCache\$1Size\$1TaskDefinition** – 缓存在内存中的唯一 ECS 任务定义的数量。
+ **延迟** – 服务发现周期所需的时间。

检查 `ExporterDiscoveredTargetCount` 的值以查看发现的 Prometheus 目标是否符合您的预期。如果不符合，可能的原因如下：
+ ECS 服务发现的配置可能与应用程序的设置不匹配。对于基于 docker 标签的服务发现，您的目标容器可能并未在 CloudWatch 代理中配置必要的 docker 标签以将其自动发现。对于 ECS 任务定义 ARN 基于正则表达式的服务发现，CloudWatch 代理中的正则表达式设置可能与应用程序的任务定义不匹配。
+ CloudWatch 代理的 ECS 任务角色可能没有权限检索 ECS 任务的元数据。检查 CloudWatch 代理是否已被授予以下只读权限：
  + `ec2:DescribeInstances`
  + `ecs:ListTasks`
  + `ecs:DescribeContainerInstances`
  + `ecs:DescribeTasks`
  + `ecs:DescribeTaskDefinition`

**步骤 3：检查网络连接以及 ECS 任务角色策略**

如果即使 `Exporter_DiscoveredTargetCount` 的值表明已发现 Prometheus 目标，仍然没有日志事件发送到目标 CloudWatch Logs 日志组，这可能是由以下任一原因引起的：
+ CloudWatch 代理可能无法连接到 Prometheus 目标端口。检查 CloudWatch 代理背后的安全组设置。私有 IP 应允许 CloudWatch 代理连接到 Prometheus 导出器端口。
+ CloudWatch 代理的 ECS 任务角色可能没有 **CloudWatchAgentServerPolicy** 托管策略。CloudWatch 代理的 ECS 任务角色需要具有此策略才能将 Prometheus 指标作为日志事件发送。如果您使用示例 CloudFormation 模板自动创建 IAM 角色，则 ECS 任务角色和 ECS 执行角色都会被授予执行 Prometheus 监控的最低权限。

# Amazon EKS 和 Kubernetes 集群上的 Prometheus 指标故障排除
<a name="ContainerInsights-Prometheus-troubleshooting-EKS"></a>

本节提供有关对 Amazon EKS 和 Kubernetes 集群上的 Prometheus 指标设置进行故障排除的帮助。

## Amazon EKS 上的一般故障排除步骤
<a name="ContainerInsights-Prometheus-troubleshooting-general"></a>

要确认 CloudWatch 代理正在运行，请输入以下命令。

```
kubectl get pod -n amazon-cloudwatch
```

输出应包含其 `NAME` 列中包含 `cwagent-prometheus-id` 并且 `STATUS column.`中包含 `Running` 的行。

要显示有关正在运行的 pod 的详细信息，请输入以下命令。将 *pod-name* 替换为名称以 `cw-agent-prometheus` 开头的 pod 的完整名称。

```
kubectl describe pod pod-name -n amazon-cloudwatch
```

如果您安装了 CloudWatch Container Insights，则可以使用 CloudWatch Logs Insights 从收集 Prometheus 指标的 CloudWatch 代理查询日志。

**查询应用程序日志**

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 在导航窗格中，选择 **CloudWatch Logs Insights**。

1. 选择应用程序日志的日志组 **/aws/containerinsights/*cluster-name*/application**

1. 使用以下查询替换搜索查询表达式，然后选择**运行查询**

   ```
   fields ispresent(kubernetes.pod_name) as haskubernetes_pod_name, stream, kubernetes.pod_name, log | 
   filter haskubernetes_pod_name and kubernetes.pod_name like /cwagent-prometheus
   ```

您还可以确认 Prometheus 指标和元数据是否摄取作为 CloudWatch Logs 事件。

**确认正在摄取 Prometheus 数据**

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 在导航窗格中，选择 **CloudWatch Logs Insights**。

1. 选择 **/aws/containerinsights/*cluster-name*/prometheus**

1. 使用以下查询替换搜索查询表达式，然后选择**运行查询**

   ```
   fields @timestamp, @message | sort @timestamp desc | limit 20
   ```

## 录入丢弃的 Prometheus 指标
<a name="ContainerInsights-Prometheus-troubleshooting-droppedmetrics"></a>

此版本不会收集直方图的 Prometheus 指标。您可以使用 CloudWatch 代理来检查是否因为任何 Prometheus 指标是直方图指标而丢弃了这些指标。您还可以记录由于是直方图指标，因此丢弃而未发送到 CloudWatch 的前 500 个 Prometheus 指标列表。

要查看是否丢弃了任何指标，请输入以下命令：

```
kubectl logs -l "app=cwagent-prometheus" -n amazon-cloudwatch --tail=-1
```

如果丢弃了任何指标，您将在 `/opt/aws/amazon-cloudwatch-agent/logs/amazon-cloudwatch-agent.log` 文件中看到以下行。

```
I! Drop Prometheus metrics with unsupported types. Only Gauge, Counter and Summary are supported.
I! Please enable CWAgent debug mode to view the first 500 dropped metrics
```

如果您看到这些行并想知道丢弃了哪些指标，请使用以下步骤。

**记录已丢弃的 Prometheus 指标列表**

1. 通过将以下粗体行添加到 `prometheus-eks.yaml` 或 `prometheus-k8s.yaml` 文件中并保存文件，将 CloudWatch 代理更改为调试模式。

   ```
   {
         "agent": {
           "debug": true
         },
   ```

   该文件的这一部分随后应该如下所示：

   ```
   cwagentconfig.json: |
       {
         "agent": {
           "debug": true
         },
         "logs": {
           "metrics_collected": {
   ```

1. 通过输入以下命令重新安装 CloudWatch 代理以启用调试模式：

   ```
   kubectl delete deployment cwagent-prometheus -n amazon-cloudwatch
   kubectl apply -f prometheus.yaml
   ```

   丢弃的指标将在 CloudWatch 代理 pod 中录入。

1. 要从 CloudWatch 代理 pod 检索日志，请输入以下命令：

   ```
   kubectl logs -l "app=cwagent-prometheus" -n amazon-cloudwatch --tail=-1
   ```

   或者，如果您安装了 Container Insights Fluentd 日志记录，日志也会保存在 CloudWatch Logs 日志组 **/aws/containerinsights/*cluster\$1name*/application** 中。

   要查询这些日志，您可以按照[Amazon EKS 上的一般故障排除步骤](#ContainerInsights-Prometheus-troubleshooting-general)中的步骤查询应用程序日志。

## 在哪里摄取 Prometheus 指标作为 CloudWatch Logs 日志事件？
<a name="ContainerInsights-Prometheus-troubleshooting-metrics_ingested"></a>

CloudWatch 代理为每个 Prometheus 抓取任务配置创建一个日志流。例如，在 `prometheus-eks.yaml` 和 `prometheus-k8s.yaml` 文件中，`job_name: 'kubernetes-pod-appmesh-envoy'` 行将抓取 App Mesh 指标。Prometheus 目标被定义为 `kubernetes-pod-appmesh-envoy`。因此，所有 App Mesh Prometheus 指标都作为 CloudWatch Logs 事件摄取到名为 **/aws/containerinsights/cluster-name/Prometheus** 的日志组下的 **kubernetes-pod-appmesh-envoy** 日志流中。

## 我在 CloudWatch 指标中没有看到 Amazon EKS 或 Kubernetes Prometheus 指标
<a name="ContainerInsights-Prometheus-troubleshooting-no-metrics"></a>

首先，确保 Prometheus 指标在日志组 **/aws/containerinsights/cluster-name/Prometheus** 中摄取作为日志事件。使用[在哪里摄取 Prometheus 指标作为 CloudWatch Logs 日志事件？](#ContainerInsights-Prometheus-troubleshooting-metrics_ingested)中的信息可帮助您检查目标日志流。如果未创建日志流或日志流中没有新的日志事件，请检查以下内容：
+ 检查 Prometheus 指标导出程序端点是否正确设置
+ 检查 CloudWatch 代理 YAML 文件 `config map: cwagent-prometheus` 部分中的 Prometheus 抓取配置是否正确。该配置应与 Prometheus 配置文件中的配置相同。有关更多信息，请参阅 Prometheus 文档中的 [<scrape\$1config>](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#scrape_config)。

如果正确摄取了 Prometheus 指标作为日志事件，请检查嵌入式指标格式设置是否已添加到日志事件以生成 CloudWatch 指标。

```
"CloudWatchMetrics":[
   {
      "Metrics":[
         {
            "Name":"envoy_http_downstream_cx_destroy_remote_active_rq"
         }
      ],
      "Dimensions":[
         [
            "ClusterName",
            "Namespace"
         ]
      ],
      "Namespace":"ContainerInsights/Prometheus"
   }
],
```

有关嵌入式指标格式的更多信息，请参阅[规范：嵌入式指标格式](CloudWatch_Embedded_Metric_Format_Specification.md)。

如果日志事件中没有嵌入式指标格式，请检查在 CloudWatch 代理安装 YAML 文件的 `config map: prometheus-cwagentconfig` 部分是否正确配置了 `metric_declaration` 部分。有关更多信息，请参阅 [添加新 Prometheus 抓取目标的教程：Prometheus API 服务器指标](ContainerInsights-Prometheus-Setup-configure.md#ContainerInsights-Prometheus-Setup-new-exporters)。

# 与 Application Insights 集成
<a name="container-insights-appinsights"></a>

Amazon CloudWatch Application Insights 可帮助您监控应用程序，并在应用程序资源和技术堆栈中指定和设置关键指标、日志和告警。有关更多信息，请参阅 [使用 CloudWatch Application Insights 检测常见应用程序问题](cloudwatch-application-insights.md)。

您可以启用 Application Insights，从容器化应用程序和微服务中收集其他数据。如果您尚未执行此操作，可以通过在 Container Insights 控制面板中的性能视图下方选择 **Auto-configure Application Insights**（自动配置 Application Insights）将其启用。

如果您已设置 CloudWatch Application Insights 来监控容器化应用程序，Application Insights 控制面板将显示在 Container Insights 控制面板下方。

有关 Application Insights 和容器化应用程序的更多信息，请参阅 [为 Amazon ECS 和 Amazon EKS 资源监控启用 Application Insights](appinsights-setting-up-console.md#appinsights-container-insights)。

# 在 Container Insights 内查看 Amazon ECS 生命周期事件
<a name="container-insights-ECS-lifecycle-events"></a>

您可以在 Container Insights 控制台中查看 Amazon ECS 生命周期事件。这样有助于您在一个视图中将容器指标、日志和事件关联在一起，从而便于您更完整地了解运行情况。

事件包括容器实例状态更改事件、任务状态更改事件和服务操作事件。它们会由 Amazon ECS 自动发送到 Amazon EventBridge，同时以事件日志的形式收集到 CloudWatch 中。有关这些事件的更多信息，请参阅 [Amazon ECS 事件](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs_cwe_events.html)。

Amazon ECS 生命周期事件适用标准 Continer Insights 定价。有关更多信息，请参阅 [Amazon CloudWatch 定价](https://aws.amazon.com/cloudwatch/pricing/)。

要配置生命周期事件表并为集群创建规则，您必须拥有 `events:PutRule`、`events:PutTargets` 和 `logs:CreateLogGroup` 权限。您还必须确保有资源策略让 EventBridge 能够创建日志流并将日志发送到 CloudWatch Logs。如果此资源策略不存在，则可以输入以下命令进行创建：

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Principal": {
        "Service": ["events.amazonaws.com", "delivery.logs.amazonaws.com"]
      },
      "Resource": "arn:aws:logs:us-east-1:111122223333:log-group:/aws/events/ecs/containerinsights/*:*",
      "Condition": {
        "StringEquals": {
        "aws:SourceAccount": "111122223333"
        },
        "ArnLike": {
        "aws:SourceArn": "arn:aws:events:us-east-1:111122223333:rule/eventsToLog*"
        }
      },
      "Sid": "TrustEventBridgeToStoreECSLifecycleLogEvents"
    }
  ]
}
```

------

您可以使用以下命令来检查您是否已有此策略，并确认附加策略的操作已正确执行。

```
aws logs describe-resource-policies --region region --output json
```

要查看生命周期事件表，您必须拥有 `events:DescribeRule`、`events:ListTargetsByRule` 和 `logs:DescribeLogGroups` 权限。

**要在 CloudWatch Container Insights 控制台中查看 Amazon ECS 生命周期事件**

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 选择 **Insights**、**Container Insights**。

1. 选择**查看性能控制面板**。

1. 在下一个下拉列表中，选择 **ECS Clusters**（ECS 集群）、**ECS Services**（ECS 服务）或 **ECS Tasks**（ECS 任务）。

1. 如果您在上一步中选择了 **ECS Services**（ECS 服务）或 **ECS Tasks**（ECS 任务），则选择 **Lifecycle events**（生命周期事件）选项卡。

1. 在页面底部，如果您看到 **Configure lifecycle events**（配置生命周期事件），选择它来为您的集群创建 EventBridge 规则。

   这些事件会显示在 Container Insights 窗格的下方和 Application Insights 部分的上方。要对这些事件进行额外分析并创建其他可视化效果，请在生命周期事件表中选择 **View in Logs Insights**（在 Logs Insights 中查看）。

# Container Insights 问题排查
<a name="ContainerInsights-troubleshooting"></a>

如果在使用 Container Insights 时遇到问题，以下部分可为您提供帮助。

## 在 Amazon EKS 或 Kubernetes 上部署失败
<a name="ContainerInsights-setup-EKS-troubleshooting-general"></a>

如果未在 Kubernetes 集群上正确部署该代理，请尝试执行以下操作：
+ 运行以下命令以获取 pod 列表。

  ```
  kubectl get pods -n amazon-cloudwatch
  ```
+ 运行以下命令并在输出底部检查事件。

  ```
  kubectl describe pod pod-name -n amazon-cloudwatch
  ```
+ 运行以下命令以检查日志。

  ```
  kubectl logs pod-name -n amazon-cloudwatch
  ```

## 未经授权的 panic：无法从 kubelet 检索 cadvisor 数据
<a name="ContainerInsights-setup-EKS-troubleshooting-permissions"></a>

如果您的部署失败，并显示错误 `Unauthorized panic: Cannot retrieve cadvisor data from kubelet`，则您的 kubelet 可能未启用 Webhook 授权模式。Container Insights 需要此模式。有关更多信息，请参阅 [在 CloudWatch 中验证 Container Insights 的先决条件](Container-Insights-prerequisites.md)。

## 在 Amazon ECS 上已删除和重新创建的集群上部署 Container Insights
<a name="ContainerInsights-troubleshooting-recreate"></a>

如果删除未启用 Container Insights 的现有 Amazon ECS 集群，并使用相同名称重新创建它，则无法在重新创建此集群时在此新集群上启用 Container Insights。您可以通过重新创建来启用它，然后输入以下命令：

```
aws ecs update-cluster-settings --cluster myCICluster --settings name=container Insights,value=enabled
```

## 端点无效错误
<a name="ContainerInsights-setup-invalid-endpoint"></a>

如果您看到类似于以下内容的错误消息，请检查以确保已将正在使用的命令中的所有占位符（例如 *cluster-name* 和 *region-name*）替换为正确的部署信息。

```
"log": "2020-04-02T08:36:16Z E! cloudwatchlogs: code: InvalidEndpointURL, message: invalid endpoint uri, original error: &url.Error{Op:\"parse\", URL:\"https://logs.{{region_name}}.amazonaws.com/\", Err:\"{\"}, &awserr.baseError{code:\"InvalidEndpointURL\", message:\"invalid endpoint uri\", errs:[]error{(*url.Error)(0xc0008723c0)}}\n",
```

## 指标未显示在控制台中
<a name="ContainerInsights-setup-EKS-troubleshooting-nometrics"></a>

如果您在 AWS 管理控制台中未看到任何 Container Insights 指标，请确保已完成 Container Insights 的设置。在完全设置 Container Insights 之前，不会显示指标。有关更多信息，请参阅 [设置 Container Insights](deploy-container-insights.md)。

## 升级集群后，Amazon EKS 或 Kubernetes 上缺少 Pod 指标
<a name="ContainerInsights-troubleshooting-podmetrics-missing"></a>

如果在您将 CloudWatch 代理作为进程守护程序集部署在新的或升级的集群上后，全部或部分容器组（pod）指标丢失，或者您看到包含 `W! No pod metric collected` 消息的错误日志，则本节可能很有帮助。

这些错误可能是由容器运行时的更改引起的，例如 containerd 或 docker systemd cgroup 驱动程序。您通常可以通过更新部署清单来解决此问题，以便将主机的 containerd 套接字挂载到容器中。请参见以下示例：

```
# For full example see https://github.com/aws-samples/amazon-cloudwatch-container-insights/blob/latest/k8s-deployment-manifest-templates/deployment-mode/daemonset/container-insights-monitoring/cwagent/cwagent-daemonset.yaml
apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: cloudwatch-agent
  namespace: amazon-cloudwatch
spec:
  template:
    spec:
      containers:
        - name: cloudwatch-agent
# ...
          # Don't change the mountPath
          volumeMounts:
# ...
            - name: dockersock
              mountPath: /var/run/docker.sock
              readOnly: true
            - name: varlibdocker
              mountPath: /var/lib/docker
              readOnly: true
            - name: containerdsock # NEW mount
              mountPath: /run/containerd/containerd.sock
              readOnly: true
# ...
      volumes:
# ...
        - name: dockersock
          hostPath:
            path: /var/run/docker.sock
        - name: varlibdocker
          hostPath:
            path: /var/lib/docker
        - name: containerdsock # NEW volume
          hostPath:
            path: /run/containerd/containerd.sock
```

## 使用 Bottlerocket for Amazon EKS 时没有 pod 指标
<a name="ContainerInsights-troubleshooting-bottlerocket"></a>

Bottlerocket 是一个基于 Linux 的开源操作系统，AWS 专为运行容器而构建。

Bottlerocket 在主机上使用不同的 `containerd` 路径，因此您需要将卷更改为其位置。如果未这样设置，包含 `W! No pod metric collected` 的日志会显示错误。请参阅以下示例。

```
volumes:
  # ... 
    - name: containerdsock
      hostPath:
        # path: /run/containerd/containerd.sock
        # bottlerocket does not mount containerd sock at normal place
        # https://github.com/bottlerocket-os/bottlerocket/commit/91810c85b83ff4c3660b496e243ef8b55df0973b
        path: /run/dockershim.sock
```

## 将 containerd 运行时用于 Amazon EKS 或 Kubernetes 时，没有容器文件系统指标
<a name="ContainerInsights-troubleshooting-containerd"></a>

这是一个已知问题，正在由社群贡献者解决。有关更多信息，请参阅 GitHub 上的 [containerd 的磁盘使用指标](https://github.com/google/cadvisor/issues/2785)和 [containerd 的 cadvisor 不支持容器文件系统指标](https://github.com/aws/amazon-cloudwatch-agent/issues/192)。

## 收集 Prometheus 指标时，CloudWatch 代理的日志卷意外增加
<a name="ContainerInsights-troubleshooting-log-volume-increase"></a>

这是 CloudWatch 代理的 1.247347.6b250880 版本中推出的回归。此回归已在代理的更新版本中得到修复。它的影响仅限于客户收集 CloudWatch 代理本身的日志并且仍在使用 Prometheus 的情况。有关更多信息，请参阅 GitHub 上的 [[prometheus] 代理正在日志中打印所有收集的指标](https://github.com/aws/amazon-cloudwatch-agent/issues/209)。

## 未从 Dockerhub 找到发布说明中提到的最新 docker 镜像
<a name="ContainerInsights-troubleshooting-docker-image"></a>

在内部开始实际发布之前，我们会更新 Github 上的发布说明和标签。在 Github 上增加版本号后，通常需要 1 – 2 周才能在注册表上看到最新的 Docker 镜像。CloudWatch 代理容器镜像不会在夜间发布。您可以在以下位置直接从源代码构建镜像：[https://github.com/aws/amazon-cloudwatch-agent/tree/main/amazon-cloudwatch-container-insights/cloudwatch-agent-dockerfile](https://github.com/aws/amazon-cloudwatch-agent/tree/main/amazon-cloudwatch-container-insights/cloudwatch-agent-dockerfile)

## CloudWatch 代理上的 CrashLoopBackoff 错误
<a name="ContainerInsights-troubleshooting-crashloopbackoff"></a>

如果您看到 CloudWatch 代理出现 `CrashLoopBackOff` 错误，请确保您的 IAM 权限设置正确。有关更多信息，请参阅 [在 CloudWatch 中验证 Container Insights 的先决条件](Container-Insights-prerequisites.md)。

## CloudWatch 代理或 Fluentd 容器组（pod）卡在待处理状态
<a name="ContainerInsights-troubleshooting-pending"></a>

如果您有一个 CloudWatch 代理或 Fluentd 容器组（pod）卡在 `Pending` 状态或出现 `FailedScheduling` 错误，请根据代理所需的内核数量和 RAM 量确定您的节点是否有足够的计算资源。使用以下命令描述此 pod：

```
kubectl describe pod cloudwatch-agent-85ppg -n amazon-cloudwatch
```

# 构建您自己的 CloudWatch 代理 Docker 镜像
<a name="ContainerInsights-build-docker-image"></a>

您可以通过引用位于以下网址的 Dockerfile 来构建自己的 CloudWatch 代理 Docker 镜像：[ https://github.com/aws-samples/amazon-cloudwatch-container-insights/blob/latest/cloudwatch-agent-dockerfile/Dockerfile](https://github.com/aws-samples/amazon-cloudwatch-container-insights/blob/latest/cloudwatch-agent-dockerfile/Dockerfile)。

Dockerfile 支持直接使用 `docker buildx` 构建多架构镜像。

# 在容器中部署其他 CloudWatch 代理功能
<a name="ContainerInsights-other-agent-features"></a>

您可以使用 CloudWatch 代理在容器中部署其他监控功能。这些功能如下所示：
+ **嵌入式指标格式** – 有关更多信息，请参阅 [在日志中嵌入指标](CloudWatch_Embedded_Metric_Format.md)。
+ **StatsD** – 有关更多信息，请参阅 [使用 StatsD 检索自定义指标](CloudWatch-Agent-custom-metrics-statsd.md)。

说明和必要的文件位于 GitHub 上的以下位置：
+ 对于 Amazon ECS 容器，请参阅[基于部署模式的 Amazon ECS 任务定义示例](https://github.com/aws-samples/amazon-cloudwatch-container-insights/tree/latest/ecs-task-definition-templates/deployment-mode)。
+ 对于 Amazon EKS 和 Kubernetes 容器，请参阅[基于部署模式的 Kubernetes YAML 文件示例](https://github.com/aws-samples/amazon-cloudwatch-container-insights/tree/latest/k8s-deployment-manifest-templates/deployment-mode)。

# Lambda Insights
<a name="Lambda-Insights"></a>

CloudWatch Lambda Insights 是针对在 AWS Lambda 上运行的无服务器应用程序的监控和故障排除解决方案。此解决方案收集、聚合和汇总系统级指标，包括 CPU 时间、内存、磁盘和网络。它还收集、聚合和汇总诊断信息（如冷启动和 Lambda 工件关闭），以帮助您隔离 Lambda 函数的问题并快速解决这些问题。

Lambda Insights 使用作为 Lambda 层提供的全新 CloudWatch Lambda 扩展程序。在 Lambda 函数上安装此扩展程序时，其会收集系统级指标，并为每次调用该 Lambda 函数发出一个性能日志事件。CloudWatch 使用嵌入式指标格式从日志事件中提取指标。

**注意**  
Lambda 洞察代理仅在使用 Amazon Linux 2 和 Amazon Linux 2023 的 Lambda 运行时上受支持。

有关 Lambda 扩展程序的更多信息，请参阅[使用 AWS Lambda 扩展程序](https://docs.aws.amazon.com/lambda/latest/dg/using-extensions.html)。有关嵌入式指标格式的更多信息，请参阅[在日志中嵌入指标](CloudWatch_Embedded_Metric_Format.md)。

您可以将 Lambda Insights 与使用 Lambda 运行时（支持 Lambda 扩展程序）的 Lambda 函数一起使用。有关这些运行时的列表，请参阅 [Lambda 扩展程序 API](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-extensions-api.html)。

**定价**

对于为 Lambda Insights 启用的每个 Lambda 函数，您只需为用于指标和日志的流量付费。有关定价示例，请参阅 [Amazon CloudWatch 定价](https://aws.amazon.com/cloudwatch/pricing/)。

您需要按 Lambda 扩展程序所占用的执行时间（以 1 毫秒为增量计费）付费。有关 Lambda 定价的更多信息，请参阅 [AWS Lambda 定价](https://aws.amazon.com/lambda/pricing/)。

# 开始使用 Lambda Insights
<a name="Lambda-Insights-Getting-Started"></a>

要在 Lambda 函数上启用 Lambda Insights，您可以使用 Lambda 控制台中的一键切换。除此之外，您也可以使用 AWS CLI、CloudFormation、AWS Serverless Application Model CLI 或 AWS Cloud Development Kit (AWS CDK)。

下面几节提供了完成这些步骤的详细说明。

**Topics**
+ [Lambda Insights 扩展程序的可用版本](Lambda-Insights-extension-versions.md)
+ [使用控制台对现有 Lambda 函数启用 Lambda Insights](Lambda-Insights-Getting-Started-console.md)
+ [使用 AWS CLI 对现有 Lambda 函数启用 Lambda Insights](Lambda-Insights-Getting-Started-cli.md)
+ [使用 AWS SAM CLI 对现有 Lambda 函数启用 Lambda Insights](Lambda-Insights-Getting-Started-SAM-CLI.md)
+ [使用 CloudFormation 对现有 Lambda 函数启用 Lambda Insights](Lambda-Insights-Getting-Started-cloudformation.md)
+ [使用 AWS CDK 对现有 Lambda 函数启用 Lambda Insights](Lambda-Insights-Getting-Started-clouddevelopmentkit.md)
+ [使用无服务器框架对现有 Lambda 函数启用 Lambda Insights](Lambda-Insights-Getting-Started-serverless.md)
+ [对 Lambda 容器映像部署启用 Lambda Insights](Lambda-Insights-Getting-Started-docker.md)
+ [更新函数的 Lambda Insights 扩展程序版本](Lambda-Insights-Update-Extension.md)

# Lambda Insights 扩展程序的可用版本
<a name="Lambda-Insights-extension-versions"></a>

本节列出了 Lambda Insights 扩展程序的版本，以及要在每个 AWS 区域用于这些扩展程序的 ARN。

**Topics**
+ [x86-64 平台](Lambda-Insights-extension-versionsx86-64.md)
+ [ARM64 平台](Lambda-Insights-extension-versionsARM.md)

# x86-64 平台
<a name="Lambda-Insights-extension-versionsx86-64"></a>

本节列出了适用于 x84-64 平台的 Lambda Insights 扩展程序版本，以及要在每个 AWS 区域用于这些扩展程序的 ARN。

**重要**  
Lambda Insights 扩展版 1.0.317.0 和更高版本不支持 Amazon Linux 1。

## 1.0.660.0
<a name="Lambda-Insights-extension-1.0.660.0"></a>

1.0.660.0 版本为运行于 Lambda 托管实例的 Lambda 函数新增 Lambda 洞察扩展支持。对于运行在 Lambda 托管实例上的函数，该扩展程序将每分钟发送一次 EMF 日志事件，以 1 分钟粒度生成 12 项 CloudWatch Metrics 指标。

**适用于 1.0.660.0 版本的 ARN**

下表列出了要在各个 AWS 区域中用于此版本扩展程序的适用 ARN。


| 区域 | ARN | 
| --- | --- | 
|  美国东部（弗吉尼亚州北部） |  `arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:64`  | 
|  美国东部（俄亥俄州） |  `arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension:64`  | 
|  美国西部（北加利福尼亚） |  `arn:aws:lambda:us-west-1:580247275435:layer:LambdaInsightsExtension:64`  | 
|  美国西部（俄勒冈州） |  `arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension:64`  | 
|  非洲（开普敦） |  `arn:aws:lambda:af-south-1:012438385374:layer:LambdaInsightsExtension:56`  | 
|  亚太地区（香港） |  `arn:aws:lambda:ap-east-1:519774774795:layer:LambdaInsightsExtension:56`  | 
|  亚太地区（海得拉巴） |  `arn:aws:lambda:ap-south-2:891564319516:layer:LambdaInsightsExtension:38`  | 
|  亚太地区（雅加达） |  `arn:aws:lambda:ap-southeast-3:439286490199:layer:LambdaInsightsExtension:40`  | 
|  亚太地区（马来西亚） |  `arn:aws:lambda:ap-southeast-5:590183865173:layer:LambdaInsightsExtension:13`  | 
|  亚太地区（墨尔本） |  `arn:aws:lambda:ap-southeast-4:158895979263:layer:LambdaInsightsExtension:33`  | 
|  亚太地区（孟买） |  `arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension:62`  | 
|  亚太地区（新西兰） |  `arn:aws:lambda:ap-southeast-6:727646510379:layer:LambdaInsightsExtension:6`  | 
|  亚太地区（大阪） |  `arn:aws:lambda:ap-northeast-3:194566237122:layer:LambdaInsightsExtension:45`  | 
|  亚太地区（首尔） |  `arn:aws:lambda:ap-northeast-2:580247275435:layer:LambdaInsightsExtension:63`  | 
|  亚太地区（新加坡） |  `arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension:64`  | 
|  亚太地区（悉尼） |  `arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension:64`  | 
|  亚太地区（台北） |  `arn:aws:lambda:ap-east-2:145023102084:layer:LambdaInsightsExtension:13`  | 
|  亚太地区（泰国） |  `arn:aws:lambda:ap-southeast-7:761018874580:layer:LambdaInsightsExtension:13`  | 
|  亚太地区（东京） |  `arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension:91`  | 
|  加拿大（中部） |  `arn:aws:lambda:ca-central-1:580247275435:layer:LambdaInsightsExtension:63`  | 
|  加拿大西部（卡尔加里） |  `arn:aws:lambda:ca-west-1:946466191631:layer:LambdaInsightsExtension:25`  | 
|  中国（北京） |  `arn:aws-cn:lambda:cn-north-1:488211338238:layer:LambdaInsightsExtension:51`  | 
|  中国（宁夏） |  `arn:aws-cn:lambda:cn-northwest-1:488211338238:layer:LambdaInsightsExtension:51`  | 
|  欧洲地区（法兰克福） |  `arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension:64`  | 
|  欧洲地区（爱尔兰） |  `arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension:64`  | 
|  欧洲地区（伦敦） |  `arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension:64`  | 
|  欧洲地区（米兰） |  `arn:aws:lambda:eu-south-1:339249233099:layer:LambdaInsightsExtension:56`  | 
|  欧洲地区（巴黎） |  `arn:aws:lambda:eu-west-3:580247275435:layer:LambdaInsightsExtension:63`  | 
|  欧洲（西班牙） |  `arn:aws:lambda:eu-south-2:352183217350:layer:LambdaInsightsExtension:40`  | 
|  欧洲地区（斯德哥尔摩） |  `arn:aws:lambda:eu-north-1:580247275435:layer:LambdaInsightsExtension:61`  | 
|  欧洲（苏黎世） |  `arn:aws:lambda:eu-central-2:033019950311:layer:LambdaInsightsExtension:39`  | 
|  以色列（特拉维夫） |  `arn:aws:lambda:il-central-1:459530977127:layer:LambdaInsightsExtension:33`  | 
|  墨西哥（中部） |  `arn:aws:lambda:mx-central-1:879381266642:layer:LambdaInsightsExtension:13`  | 
|  中东（巴林） |  `arn:aws:lambda:me-south-1:285320876703:layer:LambdaInsightsExtension:56`  | 
|  中东（阿联酋）： |  `arn:aws:lambda:me-central-1:732604637566:layer:LambdaInsightsExtension:39`  | 
|  南美洲（圣保罗） |  `arn:aws:lambda:sa-east-1:580247275435:layer:LambdaInsightsExtension:63`  | 
|  AWS GovCloud（美国东部） |  `arn:aws-us-gov:lambda:us-gov-east-1:122132214140:layer:LambdaInsightsExtension:24`  | 
|  AWS GovCloud（美国西部） |  `arn:aws-us-gov:lambda:us-gov-west-1:751350123760:layer:LambdaInsightsExtension:24`  | 

## 1.0.498.0
<a name="Lambda-Insights-extension-1.0.498.0"></a>

1.0.498.0 版本包含错误修复与性能改进。

**适用于 1.0.498.0 版本的 ARN**

下表列出了要在各个 AWS 区域中用于此版本扩展程序的适用 ARN。


| 区域 | ARN | 
| --- | --- | 
|  美国东部（弗吉尼亚州北部） |  `arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:60`  | 
|  美国东部（俄亥俄州） |  `arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension:60`  | 
|  美国西部（北加利福尼亚） |  `arn:aws:lambda:us-west-1:580247275435:layer:LambdaInsightsExtension:60`  | 
|  美国西部（俄勒冈州） |  `arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension:60`  | 
|  非洲（开普敦） |  `arn:aws:lambda:af-south-1:012438385374:layer:LambdaInsightsExtension:52`  | 
|  亚太地区（泰国） |  `arn:aws:lambda:ap-southeast-7:761018874580:layer:LambdaInsightsExtension:8`  | 
|  亚太地区（香港） |  `arn:aws:lambda:ap-east-1:519774774795:layer:LambdaInsightsExtension:52`  | 
|  亚太地区（海得拉巴） |  `arn:aws:lambda:ap-south-2:891564319516:layer:LambdaInsightsExtension:34`  | 
|  亚太地区（雅加达） |  `arn:aws:lambda:ap-southeast-3:439286490199:layer:LambdaInsightsExtension:36`  | 
|  亚太地区（马来西亚） |  `arn:aws:lambda:ap-southeast-5:590183865173:layer:LambdaInsightsExtension:9`  | 
|  亚太地区（墨尔本） |  `arn:aws:lambda:ap-southeast-4:158895979263:layer:LambdaInsightsExtension:29`  | 
|  亚太地区（孟买） |  `arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension:58`  | 
|  亚太地区（大阪） |  `arn:aws:lambda:ap-northeast-3:194566237122:layer:LambdaInsightsExtension:41`  | 
|  亚太地区（首尔） |  `arn:aws:lambda:ap-northeast-2:580247275435:layer:LambdaInsightsExtension:59`  | 
|  亚太地区（新加坡） |  `arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension:60`  | 
|  亚太地区（悉尼） |  `arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension:60`  | 
|  亚太地区（东京） |  `arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension:87`  | 
|  加拿大（中部） |  `arn:aws:lambda:ca-central-1:580247275435:layer:LambdaInsightsExtension:59`  | 
|  加拿大西部（卡尔加里） |  `arn:aws:lambda:ca-west-1:946466191631:layer:LambdaInsightsExtension:21`  | 
|  中国（北京） |  `arn:aws-cn:lambda:cn-north-1:488211338238:layer:LambdaInsightsExtension:48`  | 
|  中国（宁夏）； |  `arn:aws-cn:lambda:cn-northwest-1:488211338238:layer:LambdaInsightsExtension:48`  | 
|  欧洲地区（法兰克福） |  `arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension:60`  | 
|  欧洲地区（爱尔兰） |  `arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension:60`  | 
|  欧洲地区（伦敦） |  `arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension:60`  | 
|  欧洲地区（米兰） |  `arn:aws:lambda:eu-south-1:339249233099:layer:LambdaInsightsExtension:52`  | 
|  欧洲地区（巴黎） |  `arn:aws:lambda:eu-west-3:580247275435:layer:LambdaInsightsExtension:59`  | 
|  欧洲（西班牙） |  `arn:aws:lambda:eu-south-2:352183217350:layer:LambdaInsightsExtension:36`  | 
|  欧洲地区（斯德哥尔摩） |  `arn:aws:lambda:eu-north-1:580247275435:layer:LambdaInsightsExtension:57`  | 
|  欧洲（苏黎世） |  `arn:aws:lambda:eu-central-2:033019950311:layer:LambdaInsightsExtension:35`  | 
|  以色列（特拉维夫） |  `arn:aws:lambda:il-central-1:459530977127:layer:LambdaInsightsExtension:29`  | 
|  墨西哥（中部） |  `arn:aws:lambda:mx-central-1:879381266642:layer:LambdaInsightsExtension:8`  | 
|  中东（巴林） |  `arn:aws:lambda:me-south-1:285320876703:layer:LambdaInsightsExtension:52`  | 
|  中东（阿联酋）： |  `arn:aws:lambda:me-central-1:732604637566:layer:LambdaInsightsExtension:35`  | 
|  南美洲（圣保罗） |  `arn:aws:lambda:sa-east-1:580247275435:layer:LambdaInsightsExtension:59`  | 
|  AWS GovCloud（美国东部） |  `arn:aws-us-gov:lambda:us-gov-east-1:122132214140:layer:LambdaInsightsExtension:24`  | 
|  AWS GovCloud（美国西部） |  `arn:aws-us-gov:lambda:us-gov-west-1:751350123760:layer:LambdaInsightsExtension:24`  | 
|  亚太地区（新西兰） |  `arn:aws:lambda:ap-southeast-6:727646510379:layer:LambdaInsightsExtension:1`  | 
|  亚太地区（台北） |  `arn:aws:lambda:ap-east-2:145023102084:layer:LambdaInsightsExtension:8`  | 

## 1.0.404.0
<a name="Lambda-Insights-extension-1.0.404.0"></a>

版本 1.0.404.0 将 Lambda Insights 扩展程序的二进制大小从约 10MB 减少到约 6MB，随后将 Lambda Insights 扩展层的 zip 大小从约 4MB 减少到约 2.7MB。还可以将代理的总体内存消耗量从约 10MB 减少到约 7MB。

**适用于版本 1.0.404.0 的 ARN**

下表列出了要在各个 AWS 区域中用于此版本扩展程序的适用 ARN。


| 区域 | ARN | 
| --- | --- | 
|  美国东部（弗吉尼亚州北部） |  `arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:56`  | 
|  美国东部（俄亥俄州） |  `arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension:56`  | 
|  美国西部（北加利福尼亚） |  `arn:aws:lambda:us-west-1:580247275435:layer:LambdaInsightsExtension:56`  | 
|  美国西部（俄勒冈州） |  `arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension:56`  | 
|  非洲（开普敦） |  `arn:aws:lambda:af-south-1:012438385374:layer:LambdaInsightsExtension:47`  | 
|  亚太地区（泰国） |  `arn:aws:lambda:ap-southeast-7:761018874580:layer:LambdaInsightsExtension:3`  | 
|  亚太地区（香港） |  `arn:aws:lambda:ap-east-1:519774774795:layer:LambdaInsightsExtension:47`  | 
|  亚太地区（海得拉巴） |  `arn:aws:lambda:ap-south-2:891564319516:layer:LambdaInsightsExtension:29`  | 
|  亚太地区（雅加达） |  `arn:aws:lambda:ap-southeast-3:439286490199:layer:LambdaInsightsExtension:33`  | 
|  亚太地区（马来西亚） |  `arn:aws:lambda:ap-southeast-5:590183865173:layer:LambdaInsightsExtension:4`  | 
|  亚太地区（墨尔本） |  `arn:aws:lambda:ap-southeast-4:158895979263:layer:LambdaInsightsExtension:24`  | 
|  亚太地区（孟买） |  `arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension:54`  | 
|  亚太地区（大阪） |  `arn:aws:lambda:ap-northeast-3:194566237122:layer:LambdaInsightsExtension:37`  | 
|  亚太地区（首尔） |  `arn:aws:lambda:ap-northeast-2:580247275435:layer:LambdaInsightsExtension:55`  | 
|  亚太地区（新加坡） |  `arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension:56`  | 
|  亚太地区（悉尼） |  `arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension:56`  | 
|  亚太地区（东京） |  `arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension:83`  | 
|  加拿大（中部） |  `arn:aws:lambda:ca-central-1:580247275435:layer:LambdaInsightsExtension:55`  | 
|  加拿大西部（卡尔加里） |  `arn:aws:lambda:ca-west-1:946466191631:layer:LambdaInsightsExtension:16`  | 
|  中国（北京） |  `arn:aws-cn:lambda:cn-north-1:488211338238:layer:LambdaInsightsExtension:46`  | 
|  中国（宁夏）； |  `arn:aws-cn:lambda:cn-northwest-1:488211338238:layer:LambdaInsightsExtension:46`  | 
|  欧洲地区（法兰克福） |  `arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension:56`  | 
|  欧洲地区（爱尔兰） |  `arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension:56`  | 
|  欧洲地区（伦敦） |  `arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension:56`  | 
|  欧洲地区（米兰） |  `arn:aws:lambda:eu-south-1:339249233099:layer:LambdaInsightsExtension:47`  | 
|  欧洲地区（巴黎） |  `arn:aws:lambda:eu-west-3:580247275435:layer:LambdaInsightsExtension:55`  | 
|  欧洲（西班牙） |  `arn:aws:lambda:eu-south-2:352183217350:layer:LambdaInsightsExtension:31`  | 
|  欧洲地区（斯德哥尔摩） |  `arn:aws:lambda:eu-north-1:580247275435:layer:LambdaInsightsExtension:53`  | 
|  欧洲（苏黎世） |  `arn:aws:lambda:eu-central-2:033019950311:layer:LambdaInsightsExtension:30`  | 
|  以色列（特拉维夫） |  `arn:aws:lambda:il-central-1:459530977127:layer:LambdaInsightsExtension:23`  | 
|  墨西哥（中部） |  `arn:aws:lambda:mx-central-1:879381266642:layer:LambdaInsightsExtension:3`  | 
|  中东（巴林） |  `arn:aws:lambda:me-south-1:285320876703:layer:LambdaInsightsExtension:47`  | 
|  中东（阿联酋）： |  `arn:aws:lambda:me-central-1:732604637566:layer:LambdaInsightsExtension:30`  | 
|  南美洲（圣保罗） |  `arn:aws:lambda:sa-east-1:580247275435:layer:LambdaInsightsExtension:55`  | 
|  AWS GovCloud（美国东部） |  `arn:aws-us-gov:lambda:us-gov-east-1:122132214140:layer:LambdaInsightsExtension:24`  | 
|  AWS GovCloud（美国西部） |  `arn:aws-us-gov:lambda:us-gov-west-1:751350123760:layer:LambdaInsightsExtension:24`  | 

## 1.0.391.0
<a name="Lambda-Insights-extension-1.0.391.0"></a>

**重要**  
版本 1.0.391.0 更改了 Lambda Insights 收集和报告线程使用情况的方式。在此扩展程序的早期版本中，`threads_max` 指标报告的是进程 ID 为 1 的进程中运行的最大线程数。从版本 1.0.391.0 开始，此指标将报告在函数执行期间任何时间点执行环境中所有进程中运行的最大线程数。这包括 Lambda 函数的进程、扩展程序的进程、特定于系统/运行时的进程等。这样，`threads_max` 指标在评估可供您使用的剩余线程时更加全面。有关线程和进程配额的更多信息，请参阅 [Lambda 配额](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-limits.html)。

版本 1.0.391.0 还增加了对亚太地区（泰国）和墨西哥（中部）两个区域的支持。

**适用于版本 1.0.391.0 的 ARN**

下表列出了要在各个 AWS 区域中用于此版本扩展程序的适用 ARN。


| 区域 | ARN | 
| --- | --- | 
|  美国东部（弗吉尼亚州北部） |  `arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:55`  | 
|  美国东部（俄亥俄州） |  `arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension:55`  | 
|  美国西部（北加利福尼亚） |  `arn:aws:lambda:us-west-1:580247275435:layer:LambdaInsightsExtension:55`  | 
|  美国西部（俄勒冈州） |  `arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension:55`  | 
|  非洲（开普敦） |  `arn:aws:lambda:af-south-1:012438385374:layer:LambdaInsightsExtension:46`  | 
|  亚太地区（泰国） |  `arn:aws:lambda:ap-southeast-7:761018874580:layer:LambdaInsightsExtension:2`  | 
|  亚太地区（香港） |  `arn:aws:lambda:ap-east-1:519774774795:layer:LambdaInsightsExtension:46`  | 
|  亚太地区（海得拉巴） |  `arn:aws:lambda:ap-south-2:891564319516:layer:LambdaInsightsExtension:28`  | 
|  亚太地区（雅加达） |  `arn:aws:lambda:ap-southeast-3:439286490199:layer:LambdaInsightsExtension:32`  | 
|  亚太地区（马来西亚） |  `arn:aws:lambda:ap-southeast-5:590183865173:layer:LambdaInsightsExtension:3`  | 
|  亚太地区（墨尔本） |  `arn:aws:lambda:ap-southeast-4:158895979263:layer:LambdaInsightsExtension:23`  | 
|  亚太地区（孟买） |  `arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension:53`  | 
|  亚太地区（大阪） |  `arn:aws:lambda:ap-northeast-3:194566237122:layer:LambdaInsightsExtension:36`  | 
|  亚太地区（首尔） |  `arn:aws:lambda:ap-northeast-2:580247275435:layer:LambdaInsightsExtension:54`  | 
|  亚太地区（新加坡） |  `arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension:55`  | 
|  亚太地区（悉尼） |  `arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension:55`  | 
|  亚太地区（东京） |  `arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension:82`  | 
|  加拿大（中部） |  `arn:aws:lambda:ca-central-1:580247275435:layer:LambdaInsightsExtension:54`  | 
|  加拿大西部（卡尔加里） |  `arn:aws:lambda:ca-west-1:946466191631:layer:LambdaInsightsExtension:15`  | 
|  中国（北京） |  `arn:aws-cn:lambda:cn-north-1:488211338238:layer:LambdaInsightsExtension:45`  | 
|  中国（宁夏）； |  `arn:aws-cn:lambda:cn-northwest-1:488211338238:layer:LambdaInsightsExtension:45`  | 
|  欧洲地区（法兰克福） |  `arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension:55`  | 
|  欧洲地区（爱尔兰） |  `arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension:55`  | 
|  欧洲地区（伦敦） |  `arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension:55`  | 
|  欧洲地区（米兰） |  `arn:aws:lambda:eu-south-1:339249233099:layer:LambdaInsightsExtension:46`  | 
|  欧洲地区（巴黎） |  `arn:aws:lambda:eu-west-3:580247275435:layer:LambdaInsightsExtension:54`  | 
|  欧洲（西班牙） |  `arn:aws:lambda:eu-south-2:352183217350:layer:LambdaInsightsExtension:30`  | 
|  欧洲地区（斯德哥尔摩） |  `arn:aws:lambda:eu-north-1:580247275435:layer:LambdaInsightsExtension:52`  | 
|  欧洲（苏黎世） |  `arn:aws:lambda:eu-central-2:033019950311:layer:LambdaInsightsExtension:29`  | 
|  以色列（特拉维夫） |  `arn:aws:lambda:il-central-1:459530977127:layer:LambdaInsightsExtension:23`  | 
|  墨西哥（中部） |  `arn:aws:lambda:mx-central-1:879381266642:layer:LambdaInsightsExtension:2`  | 
|  中东（巴林） |  `arn:aws:lambda:me-south-1:285320876703:layer:LambdaInsightsExtension:46`  | 
|  中东（阿联酋）： |  `arn:aws:lambda:me-central-1:732604637566:layer:LambdaInsightsExtension:29`  | 
|  南美洲（圣保罗） |  `arn:aws:lambda:sa-east-1:580247275435:layer:LambdaInsightsExtension:54`  | 
|  AWS GovCloud（美国东部） |  `arn:aws-us-gov:lambda:us-gov-east-1:122132214140:layer:LambdaInsightsExtension:23`  | 
|  AWS GovCloud（美国西部） |  `arn:aws-us-gov:lambda:us-gov-west-1:751350123760:layer:LambdaInsightsExtension:23`  | 

## 1.0.333.0
<a name="Lambda-Insights-extension-1.0.333.0"></a>

版本 1.0.333.0 包括错误修复。

**适用于版本 1.0.333.0 的 ARN**

下表列出了要在各个 AWS 区域中用于此版本扩展程序的适用 ARN。


| 区域 | ARN | 
| --- | --- | 
|  美国东部（弗吉尼亚州北部） |  `arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:53`  | 
|  美国东部（俄亥俄州） |  `arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension:53`  | 
|  美国西部（北加利福尼亚） |  `arn:aws:lambda:us-west-1:580247275435:layer:LambdaInsightsExtension:53`  | 
|  美国西部（俄勒冈州） |  `arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension:53`  | 
|  非洲（开普敦） |  `arn:aws:lambda:af-south-1:012438385374:layer:LambdaInsightsExtension:44`  | 
|  亚太地区（香港） |  `arn:aws:lambda:ap-east-1:519774774795:layer:LambdaInsightsExtension:44`  | 
|  亚太地区（海得拉巴） |  `arn:aws:lambda:ap-south-2:891564319516:layer:LambdaInsightsExtension:26`  | 
|  亚太地区（雅加达） |  `arn:aws:lambda:ap-southeast-3:439286490199:layer:LambdaInsightsExtension:30`  | 
|  亚太地区（马来西亚） |  `arn:aws:lambda:ap-southeast-5:590183865173:layer:LambdaInsightsExtension:1`  | 
|  亚太地区（墨尔本） |  `arn:aws:lambda:ap-southeast-4:158895979263:layer:LambdaInsightsExtension:21`  | 
|  亚太地区（孟买） |  `arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension:51`  | 
|  亚太地区（大阪） |  `arn:aws:lambda:ap-northeast-3:194566237122:layer:LambdaInsightsExtension:34`  | 
|  亚太地区（首尔） |  `arn:aws:lambda:ap-northeast-2:580247275435:layer:LambdaInsightsExtension:52`  | 
|  亚太地区（新加坡） |  `arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension:53`  | 
|  亚太地区（悉尼） |  `arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension:53`  | 
|  亚太地区（东京） |  `arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension:80`  | 
|  加拿大（中部） |  `arn:aws:lambda:ca-central-1:580247275435:layer:LambdaInsightsExtension:52`  | 
|  加拿大西部（卡尔加里） |  `arn:aws:lambda:ca-west-1:946466191631:layer:LambdaInsightsExtension:13`  | 
|  中国（北京） |  `arn:aws-cn:lambda:cn-north-1:488211338238:layer:LambdaInsightsExtension:43`  | 
|  中国（宁夏）； |  `arn:aws-cn:lambda:cn-northwest-1:488211338238:layer:LambdaInsightsExtension:43`  | 
|  欧洲地区（法兰克福） |  `arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension:53`  | 
|  欧洲地区（爱尔兰） |  `arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension:53`  | 
|  欧洲地区（伦敦） |  `arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension:53`  | 
|  欧洲地区（米兰） |  `arn:aws:lambda:eu-south-1:339249233099:layer:LambdaInsightsExtension:44`  | 
|  欧洲地区（巴黎） |  `arn:aws:lambda:eu-west-3:580247275435:layer:LambdaInsightsExtension:52`  | 
|  欧洲（西班牙） |  `arn:aws:lambda:eu-south-2:352183217350:layer:LambdaInsightsExtension:28`  | 
|  欧洲地区（斯德哥尔摩） |  `arn:aws:lambda:eu-north-1:580247275435:layer:LambdaInsightsExtension:50`  | 
|  欧洲（苏黎世） |  `arn:aws:lambda:eu-central-2:033019950311:layer:LambdaInsightsExtension:27`  | 
|  以色列（特拉维夫） |  `arn:aws:lambda:il-central-1:459530977127:layer:LambdaInsightsExtension:21`  | 
|  中东（巴林） |  `arn:aws:lambda:me-south-1:285320876703:layer:LambdaInsightsExtension:44`  | 
|  中东（阿联酋）： |  `arn:aws:lambda:me-central-1:732604637566:layer:LambdaInsightsExtension:27`  | 
|  南美洲（圣保罗） |  `arn:aws:lambda:sa-east-1:580247275435:layer:LambdaInsightsExtension:52`  | 
|  AWS GovCloud（美国东部） |  `arn:aws-us-gov:lambda:us-gov-east-1:122132214140:layer:LambdaInsightsExtension:21`  | 
|  AWS GovCloud（美国西部） |  `arn:aws-us-gov:lambda:us-gov-west-1:751350123760:layer:LambdaInsightsExtension:21`  | 

## 1.0.317.0
<a name="Lambda-Insights-extension-1.0.317.0"></a>

版本 1.0.317.0 包括取消对 Amazon Linux 1 平台的支持和错误修复。它还包括对 AWS GovCloud (US) 区域的支持。

**适用于版本 1.0.317.0 的 ARN**

下表列出了要在各个 AWS 区域中用于此版本扩展程序的适用 ARN。


| 区域 | ARN | 
| --- | --- | 
|  美国东部（弗吉尼亚州北部） |  `arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:52`  | 
|  美国东部（俄亥俄州） |  `arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension:52`  | 
|  美国西部（北加利福尼亚） |  `arn:aws:lambda:us-west-1:580247275435:layer:LambdaInsightsExtension:52`  | 
|  美国西部（俄勒冈州） |  `arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension:52`  | 
|  非洲（开普敦） |  `arn:aws:lambda:af-south-1:012438385374:layer:LambdaInsightsExtension:43`  | 
|  亚太地区（香港） |  `arn:aws:lambda:ap-east-1:519774774795:layer:LambdaInsightsExtension:43`  | 
|  亚太地区（海得拉巴） |  `arn:aws:lambda:ap-south-2:891564319516:layer:LambdaInsightsExtension:25`  | 
|  亚太地区（雅加达） |  `arn:aws:lambda:ap-southeast-3:439286490199:layer:LambdaInsightsExtension:29`  | 
|  亚太地区（墨尔本） |  `arn:aws:lambda:ap-southeast-4:158895979263:layer:LambdaInsightsExtension:20`  | 
|  亚太地区（孟买） |  `arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension:50`  | 
|  亚太地区（大阪） |  `arn:aws:lambda:ap-northeast-3:194566237122:layer:LambdaInsightsExtension:33`  | 
|  亚太地区（首尔） |  `arn:aws:lambda:ap-northeast-2:580247275435:layer:LambdaInsightsExtension:51`  | 
|  亚太地区（新加坡） |  `arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension:52`  | 
|  亚太地区（悉尼） |  `arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension:52`  | 
|  亚太地区（东京） |  `arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension:79`  | 
|  加拿大（中部） |  `arn:aws:lambda:ca-central-1:580247275435:layer:LambdaInsightsExtension:51`  | 
|  加拿大西部（卡尔加里） |  `arn:aws:lambda:ca-west-1:946466191631:layer:LambdaInsightsExtension:12`  | 
|  中国（北京） |  `arn:aws-cn:lambda:cn-north-1:488211338238:layer:LambdaInsightsExtension:42`  | 
|  中国（宁夏）； |  `arn:aws-cn:lambda:cn-northwest-1:488211338238:layer:LambdaInsightsExtension:42`  | 
|  欧洲地区（法兰克福） |  `arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension:52`  | 
|  欧洲地区（爱尔兰） |  `arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension:52`  | 
|  欧洲地区（伦敦） |  `arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension:52`  | 
|  欧洲地区（米兰） |  `arn:aws:lambda:eu-south-1:339249233099:layer:LambdaInsightsExtension:43`  | 
|  欧洲地区（巴黎） |  `arn:aws:lambda:eu-west-3:580247275435:layer:LambdaInsightsExtension:51`  | 
|  欧洲（西班牙） |  `arn:aws:lambda:eu-south-2:352183217350:layer:LambdaInsightsExtension:27`  | 
|  欧洲地区（斯德哥尔摩） |  `arn:aws:lambda:eu-north-1:580247275435:layer:LambdaInsightsExtension:49`  | 
|  欧洲（苏黎世） |  `arn:aws:lambda:eu-central-2:033019950311:layer:LambdaInsightsExtension:26`  | 
|  以色列（特拉维夫） |  `arn:aws:lambda:il-central-1:459530977127:layer:LambdaInsightsExtension:20`  | 
|  中东（巴林） |  `arn:aws:lambda:me-south-1:285320876703:layer:LambdaInsightsExtension:43`  | 
|  中东（阿联酋）： |  `arn:aws:lambda:me-central-1:732604637566:layer:LambdaInsightsExtension:26`  | 
|  南美洲（圣保罗） |  `arn:aws:lambda:sa-east-1:580247275435:layer:LambdaInsightsExtension:51`  | 
|  AWS GovCloud（美国东部） |  `arn:aws-us-gov:lambda:us-gov-east-1:122132214140:layer:LambdaInsightsExtension:19`  | 
|  AWS GovCloud（美国西部） |  `arn:aws-us-gov:lambda:us-gov-west-1:751350123760:layer:LambdaInsightsExtension:19`  | 

## 1.0.295.0
<a name="Lambda-Insights-extension-1.0.295.0"></a>

版本 1.0.295.0 包含对所有兼容的运行时的依赖项更新。

**适用于版本 1.0.295.0 的 ARN**

下表列出了要在各个 AWS 区域中用于此版本扩展程序的适用 ARN。


| 区域 | ARN | 
| --- | --- | 
|  美国东部（弗吉尼亚州北部） |  `arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:51`  | 
|  美国东部（俄亥俄州） |  `arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension:51`  | 
|  美国西部（北加利福尼亚） |  `arn:aws:lambda:us-west-1:580247275435:layer:LambdaInsightsExtension:51`  | 
|  美国西部（俄勒冈州） |  `arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension:51`  | 
|  非洲（开普敦） |  `arn:aws:lambda:af-south-1:012438385374:layer:LambdaInsightsExtension:42`  | 
|  亚太地区（香港） |  `arn:aws:lambda:ap-east-1:519774774795:layer:LambdaInsightsExtension:42`  | 
|  亚太地区（海得拉巴） |  `arn:aws:lambda:ap-south-2:891564319516:layer:LambdaInsightsExtension:24`  | 
|  亚太地区（雅加达） |  `arn:aws:lambda:ap-southeast-3:439286490199:layer:LambdaInsightsExtension:28`  | 
|  亚太地区（墨尔本） |  `arn:aws:lambda:ap-southeast-4:158895979263:layer:LambdaInsightsExtension:19`  | 
|  亚太地区（孟买） |  `arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension:49`  | 
|  亚太地区（大阪） |  `arn:aws:lambda:ap-northeast-3:194566237122:layer:LambdaInsightsExtension:32`  | 
|  亚太地区（首尔） |  `arn:aws:lambda:ap-northeast-2:580247275435:layer:LambdaInsightsExtension:50`  | 
|  亚太地区（新加坡） |  `arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension:51`  | 
|  亚太地区（悉尼） |  `arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension:51`  | 
|  亚太地区（东京） |  `arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension:78`  | 
|  加拿大（中部） |  `arn:aws:lambda:ca-central-1:580247275435:layer:LambdaInsightsExtension:50`  | 
|  加拿大西部（卡尔加里） |  `arn:aws:lambda:ca-west-1:946466191631:layer:LambdaInsightsExtension:11`  | 
|  中国（北京） |  `arn:aws-cn:lambda:cn-north-1:488211338238:layer:LambdaInsightsExtension:41`  | 
|  中国（宁夏）； |  `arn:aws-cn:lambda:cn-northwest-1:488211338238:layer:LambdaInsightsExtension:41`  | 
|  欧洲地区（法兰克福） |  `arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension:51`  | 
|  欧洲地区（爱尔兰） |  `arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension:51`  | 
|  欧洲地区（伦敦） |  `arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension:51`  | 
|  欧洲地区（米兰） |  `arn:aws:lambda:eu-south-1:339249233099:layer:LambdaInsightsExtension:42`  | 
|  欧洲地区（巴黎） |  `arn:aws:lambda:eu-west-3:580247275435:layer:LambdaInsightsExtension:50`  | 
|  欧洲（西班牙） |  `arn:aws:lambda:eu-south-2:352183217350:layer:LambdaInsightsExtension:26`  | 
|  欧洲地区（斯德哥尔摩） |  `arn:aws:lambda:eu-north-1:580247275435:layer:LambdaInsightsExtension:48`  | 
|  欧洲（苏黎世） |  `arn:aws:lambda:eu-central-2:033019950311:layer:LambdaInsightsExtension:25`  | 
|  以色列（特拉维夫） |  `arn:aws:lambda:il-central-1:459530977127:layer:LambdaInsightsExtension:19`  | 
|  中东（巴林） |  `arn:aws:lambda:me-south-1:285320876703:layer:LambdaInsightsExtension:42`  | 
|  中东（阿联酋）： |  `arn:aws:lambda:me-central-1:732604637566:layer:LambdaInsightsExtension:25`  | 
|  南美洲（圣保罗） |  `arn:aws:lambda:sa-east-1:580247275435:layer:LambdaInsightsExtension:50`  | 

## 1.0.275.0
<a name="Lambda-Insights-extension-1.0.275.0"></a>

版本 1.0.275.0 包含对所有兼容的运行时系统的重要依赖项更新。

**适用于版本 1.0.275.0 的 ARN**

下表列出了要在各个 AWS 区域中用于此版本扩展程序的适用 ARN。


| 区域 | ARN | 
| --- | --- | 
|  美国东部（弗吉尼亚州北部） |  `arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:49`  | 
|  美国东部（俄亥俄州） |  `arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension:49`  | 
|  美国西部（北加利福尼亚） |  `arn:aws:lambda:us-west-1:580247275435:layer:LambdaInsightsExtension:49`  | 
|  美国西部（俄勒冈州） |  `arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension:49`  | 
|  非洲（开普敦） |  `arn:aws:lambda:af-south-1:012438385374:layer:LambdaInsightsExtension:40`  | 
|  亚太地区（香港） |  `arn:aws:lambda:ap-east-1:519774774795:layer:LambdaInsightsExtension:40`  | 
|  亚太地区（海得拉巴） |  `arn:aws:lambda:ap-south-2:891564319516:layer:LambdaInsightsExtension:22`  | 
|  亚太地区（雅加达） |  `arn:aws:lambda:ap-southeast-3:439286490199:layer:LambdaInsightsExtension:26`  | 
|  亚太地区（墨尔本） |  `arn:aws:lambda:ap-southeast-4:158895979263:layer:LambdaInsightsExtension:17`  | 
|  亚太地区（孟买） |  `arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension:47`  | 
|  亚太地区（大阪） |  `arn:aws:lambda:ap-northeast-3:194566237122:layer:LambdaInsightsExtension:30`  | 
|  亚太地区（首尔） |  `arn:aws:lambda:ap-northeast-2:580247275435:layer:LambdaInsightsExtension:48`  | 
|  亚太地区（新加坡） |  `arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension:49`  | 
|  亚太地区（悉尼） |  `arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension:49`  | 
|  亚太地区（东京） |  `arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension:76`  | 
|  加拿大（中部） |  `arn:aws:lambda:ca-central-1:580247275435:layer:LambdaInsightsExtension:48`  | 
|  加拿大西部（卡尔加里） |  `arn:aws:lambda:ca-west-1:946466191631:layer:LambdaInsightsExtension:9`  | 
|  中国（北京） |  `arn:aws-cn:lambda:cn-north-1:488211338238:layer:LambdaInsightsExtension:39`  | 
|  中国（宁夏）； |  `arn:aws-cn:lambda:cn-northwest-1:488211338238:layer:LambdaInsightsExtension:39`  | 
|  欧洲地区（法兰克福） |  `arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension:49`  | 
|  欧洲地区（爱尔兰） |  `arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension:49`  | 
|  欧洲地区（伦敦） |  `arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension:49`  | 
|  欧洲地区（米兰） |  `arn:aws:lambda:eu-south-1:339249233099:layer:LambdaInsightsExtension:40`  | 
|  欧洲地区（巴黎） |  `arn:aws:lambda:eu-west-3:580247275435:layer:LambdaInsightsExtension:48`  | 
|  欧洲（西班牙） |  `arn:aws:lambda:eu-south-2:352183217350:layer:LambdaInsightsExtension:24`  | 
|  欧洲地区（斯德哥尔摩） |  `arn:aws:lambda:eu-north-1:580247275435:layer:LambdaInsightsExtension:46`  | 
|  欧洲（苏黎世） |  `arn:aws:lambda:eu-central-2:033019950311:layer:LambdaInsightsExtension:23`  | 
|  以色列（特拉维夫） |  `arn:aws:lambda:il-central-1:459530977127:layer:LambdaInsightsExtension:17`  | 
|  中东（巴林） |  `arn:aws:lambda:me-south-1:285320876703:layer:LambdaInsightsExtension:40`  | 
|  中东（阿联酋）： |  `arn:aws:lambda:me-central-1:732604637566:layer:LambdaInsightsExtension:23`  | 
|  南美洲（圣保罗） |  `arn:aws:lambda:sa-east-1:580247275435:layer:LambdaInsightsExtension:48`  | 

## 1.0.273.0
<a name="Lambda-Insights-extension-1.0.273.0"></a>

版本 1.0.273.0 包含了对所有兼容运行时系统的重要错误修复，并增加了对加拿大西部（卡尔加里）区域的支持。

**适用于版本 1.0.273.0 的 ARN**

下表列出了要在各个 AWS 区域中用于此版本扩展程序的适用 ARN。


| 区域 | ARN | 
| --- | --- | 
|  美国东部（弗吉尼亚州北部） |  `arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:45`  | 
|  美国东部（俄亥俄州） |  `arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension:45`  | 
|  美国西部（北加利福尼亚） |  `arn:aws:lambda:us-west-1:580247275435:layer:LambdaInsightsExtension:45`  | 
|  美国西部（俄勒冈州） |  `arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension:45`  | 
|  非洲（开普敦） |  `arn:aws:lambda:af-south-1:012438385374:layer:LambdaInsightsExtension:35`  | 
|  亚太地区（香港） |  `arn:aws:lambda:ap-east-1:519774774795:layer:LambdaInsightsExtension:35`  | 
|  亚太地区（海得拉巴） |  `arn:aws:lambda:ap-south-2:891564319516:layer:LambdaInsightsExtension:17`  | 
|  亚太地区（雅加达） |  `arn:aws:lambda:ap-southeast-3:439286490199:layer:LambdaInsightsExtension:21`  | 
|  亚太地区（墨尔本） |  `arn:aws:lambda:ap-southeast-4:158895979263:layer:LambdaInsightsExtension:12`  | 
|  亚太地区（孟买） |  `arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension:43`  | 
|  亚太地区（大阪） |  `arn:aws:lambda:ap-northeast-3:194566237122:layer:LambdaInsightsExtension:26`  | 
|  亚太地区（首尔） |  `arn:aws:lambda:ap-northeast-2:580247275435:layer:LambdaInsightsExtension:44`  | 
|  亚太地区（新加坡） |  `arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension:45`  | 
|  亚太地区（悉尼） |  `arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension:45`  | 
|  亚太地区（东京） |  `arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension:72`  | 
|  加拿大（中部） |  `arn:aws:lambda:ca-central-1:580247275435:layer:LambdaInsightsExtension:44`  | 
|  加拿大西部（卡尔加里） |  `arn:aws:lambda:ca-west-1:946466191631:layer:LambdaInsightsExtension:4`  | 
|  中国（北京） |  `arn:aws-cn:lambda:cn-north-1:488211338238:layer:LambdaInsightsExtension:36`  | 
|  中国（宁夏）； |  `arn:aws-cn:lambda:cn-northwest-1:488211338238:layer:LambdaInsightsExtension:36`  | 
|  欧洲地区（法兰克福） |  `arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension:45`  | 
|  欧洲地区（爱尔兰） |  `arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension:45`  | 
|  欧洲地区（伦敦） |  `arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension:45`  | 
|  欧洲地区（米兰） |  `arn:aws:lambda:eu-south-1:339249233099:layer:LambdaInsightsExtension:35`  | 
|  欧洲地区（巴黎） |  `arn:aws:lambda:eu-west-3:580247275435:layer:LambdaInsightsExtension:44`  | 
|  欧洲（西班牙） |  `arn:aws:lambda:eu-south-2:352183217350:layer:LambdaInsightsExtension:19`  | 
|  欧洲地区（斯德哥尔摩） |  `arn:aws:lambda:eu-north-1:580247275435:layer:LambdaInsightsExtension:42`  | 
|  欧洲（苏黎世） |  `arn:aws:lambda:eu-central-2:033019950311:layer:LambdaInsightsExtension:17`  | 
|  以色列（特拉维夫） |  `arn:aws:lambda:il-central-1:459530977127:layer:LambdaInsightsExtension:12`  | 
|  中东（巴林） |  `arn:aws:lambda:me-south-1:285320876703:layer:LambdaInsightsExtension:35`  | 
|  中东（阿联酋）： |  `arn:aws:lambda:me-central-1:732604637566:layer:LambdaInsightsExtension:18`  | 
|  南美洲（圣保罗） |  `arn:aws:lambda:sa-east-1:580247275435:layer:LambdaInsightsExtension:44`  | 

## 1.0.229.0
<a name="Lambda-Insights-extension-1.0.229.0"></a>

版本 1.0.229.0 包含了对所有兼容运行时系统的重要错误修复，并增加了对以色列（特拉维夫）区域的支持。

**适用于版本 1.0.229.0 的 ARN**

下表列出了要在各个 AWS 区域中用于此版本扩展程序的适用 ARN。


| 区域 | ARN | 
| --- | --- | 
|  美国东部（弗吉尼亚州北部） |  `arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:38`  | 
|  美国东部（俄亥俄州） |  `arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension:38`  | 
|  美国西部（北加利福尼亚） |  `arn:aws:lambda:us-west-1:580247275435:layer:LambdaInsightsExtension:38`  | 
|  美国西部（俄勒冈州） |  `arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension:38`  | 
|  非洲（开普敦） |  `arn:aws:lambda:af-south-1:012438385374:layer:LambdaInsightsExtension:28`  | 
|  亚太地区（香港） |  `arn:aws:lambda:ap-east-1:519774774795:layer:LambdaInsightsExtension:28`  | 
|  亚太地区（海得拉巴） |  `arn:aws:lambda:ap-south-2:891564319516:layer:LambdaInsightsExtension:10`  | 
|  亚太地区（雅加达） |  `arn:aws:lambda:ap-southeast-3:439286490199:layer:LambdaInsightsExtension:14`  | 
|  亚太地区（墨尔本） |  `arn:aws:lambda:ap-southeast-4:158895979263:layer:LambdaInsightsExtension:5`  | 
|  亚太地区（孟买） |  `arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension:36`  | 
|  亚太地区（大阪） |  `arn:aws:lambda:ap-northeast-3:194566237122:layer:LambdaInsightsExtension:19`  | 
|  亚太地区（首尔） |  `arn:aws:lambda:ap-northeast-2:580247275435:layer:LambdaInsightsExtension:37`  | 
|  亚太地区（新加坡） |  `arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension:38`  | 
|  亚太地区（悉尼） |  `arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension:38`  | 
|  亚太地区（东京） |  `arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension:60`  | 
|  加拿大（中部） |  `arn:aws:lambda:ca-central-1:580247275435:layer:LambdaInsightsExtension:37`  | 
|  中国（北京） |  `arn:aws-cn:lambda:cn-north-1:488211338238:layer:LambdaInsightsExtension:29`  | 
|  中国（宁夏）； |  `arn:aws-cn:lambda:cn-northwest-1:488211338238:layer:LambdaInsightsExtension:29`  | 
|  欧洲地区（法兰克福） |  `arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension:38`  | 
|  欧洲地区（爱尔兰） |  `arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension:38`  | 
|  欧洲地区（伦敦） |  `arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension:38`  | 
|  欧洲地区（米兰） |  `arn:aws:lambda:eu-south-1:339249233099:layer:LambdaInsightsExtension:28`  | 
|  欧洲地区（巴黎） |  `arn:aws:lambda:eu-west-3:580247275435:layer:LambdaInsightsExtension:37`  | 
|  欧洲（西班牙） |  `arn:aws:lambda:eu-south-2:352183217350:layer:LambdaInsightsExtension:12`  | 
|  欧洲地区（斯德哥尔摩） |  `arn:aws:lambda:eu-north-1:580247275435:layer:LambdaInsightsExtension:35`  | 
|  欧洲（苏黎世） |  `arn:aws:lambda:eu-central-2:033019950311:layer:LambdaInsightsExtension:11`  | 
|  以色列（特拉维夫） |  `arn:aws:lambda:il-central-1:459530977127:layer:LambdaInsightsExtension:5`  | 
|  中东（巴林） |  `arn:aws:lambda:me-south-1:285320876703:layer:LambdaInsightsExtension:28`  | 
|  中东（阿联酋）： |  `arn:aws:lambda:me-central-1:732604637566:layer:LambdaInsightsExtension:11`  | 
|  南美洲（圣保罗） |  `arn:aws:lambda:sa-east-1:580247275435:layer:LambdaInsightsExtension:37`  | 

## 1.0.178.0
<a name="Lambda-Insights-extension-1.0.178.0"></a>

版本 1.0.178.0 增加了对以下 AWS 区域的支持。
+ 亚太地区（海得拉巴）
+ 亚太地区（雅加达）
+ 欧洲（西班牙）
+ 欧洲（苏黎世）
+ 中东（阿联酋）：

**适用于版本 1.0.178.0 的 ARN**

下表列出了要在各个 AWS 区域中用于此版本扩展程序的适用 ARN。


| 区域 | ARN | 
| --- | --- | 
|  美国东部（弗吉尼亚州北部） |  `arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:35`  | 
|  美国东部（俄亥俄州） |  `arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension:33`  | 
|  美国西部（北加利福尼亚） |  `arn:aws:lambda:us-west-1:580247275435:layer:LambdaInsightsExtension:33`  | 
|  美国西部（俄勒冈州） |  `arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension:33`  | 
|  非洲（开普敦） |  `arn:aws:lambda:af-south-1:012438385374:layer:LambdaInsightsExtension:25`  | 
|  亚太地区（香港） |  `arn:aws:lambda:ap-east-1:519774774795:layer:LambdaInsightsExtension:25`  | 
|  亚太地区（海得拉巴） |  `arn:aws:lambda:ap-south-2:891564319516:layer:LambdaInsightsExtension:8`  | 
|  亚太地区（雅加达） |  `arn:aws:lambda:ap-southeast-3:439286490199:layer:LambdaInsightsExtension:11`  | 
|  亚太地区（孟买） |  `arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension:31`  | 
|  亚太地区（大阪） |  `arn:aws:lambda:ap-northeast-3:194566237122:layer:LambdaInsightsExtension:2`  | 
|  亚太地区（首尔） |  `arn:aws:lambda:ap-northeast-2:580247275435:layer:LambdaInsightsExtension:32`  | 
|  亚太地区（新加坡） |  `arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension:33`  | 
|  亚太地区（悉尼） |  `arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension:33`  | 
|  亚太地区（东京） |  `arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension:50`  | 
|  加拿大（中部） |  `arn:aws:lambda:ca-central-1:580247275435:layer:LambdaInsightsExtension:32`  | 
|  中国（北京） |  `arn:aws-cn:lambda:cn-north-1:488211338238:layer:LambdaInsightsExtension:26`  | 
|  中国（宁夏）； |  `arn:aws-cn:lambda:cn-northwest-1:488211338238:layer:LambdaInsightsExtension:26`  | 
|  欧洲地区（法兰克福） |  `arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension:35`  | 
|  欧洲地区（爱尔兰） |  `arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension:33`  | 
|  欧洲地区（伦敦） |  `arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension:33`  | 
|  欧洲地区（米兰） |  `arn:aws:lambda:eu-south-1:339249233099:layer:LambdaInsightsExtension:25`  | 
|  欧洲地区（巴黎） |  `arn:aws:lambda:eu-west-3:580247275435:layer:LambdaInsightsExtension:32`  | 
|  欧洲（西班牙） |  `arn:aws:lambda:eu-south-2:352183217350:layer:LambdaInsightsExtension:10`  | 
|  欧洲地区（斯德哥尔摩） |  `arn:aws:lambda:eu-north-1:580247275435:layer:LambdaInsightsExtension:30`  | 
|  欧洲（苏黎世） |  `arn:aws:lambda:eu-central-2:033019950311:layer:LambdaInsightsExtension:7`  | 
|  中东（巴林） |  `arn:aws:lambda:me-south-1:285320876703:layer:LambdaInsightsExtension:25`  | 
|  中东（阿联酋）： |  `arn:aws:lambda:me-central-1:732604637566:layer:LambdaInsightsExtension:9`  | 
|  南美洲（圣保罗） |  `arn:aws:lambda:sa-east-1:580247275435:layer:LambdaInsightsExtension:32`  | 

## 1.0.143.0
<a name="Lambda-Insights-extension-1.0.143.0"></a>

版本 1.0.143.0 包括与 Python 3.7 和 Go 1.x 兼容性方面的错误修复。Python 3.6 Lambda 运行时已被弃用。有关更多信息，请参阅 [Lambda 运行时](https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html)。

**适用于版本 1.0.143.0 的 ARN**

下表列出了要在各个 AWS 区域中用于此版本扩展程序的适用 ARN。


| 区域 | ARN | 
| --- | --- | 
|  美国东部（弗吉尼亚州北部） |  `arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:21`  | 
|  美国东部（俄亥俄州） |  `arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension:21`  | 
|  美国西部（北加利福尼亚） |  `arn:aws:lambda:us-west-1:580247275435:layer:LambdaInsightsExtension:20`  | 
|  美国西部（俄勒冈州） |  `arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension:21`  | 
|  非洲（开普敦） |  `arn:aws:lambda:af-south-1:012438385374:layer:LambdaInsightsExtension:13`  | 
|  亚太地区（香港） |  `arn:aws:lambda:ap-east-1:519774774795:layer:LambdaInsightsExtension:13`  | 
|  Asia Pacific (Mumbai) |  `arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension:21`  | 
|  亚太地区（大阪） |  `arn:aws:lambda:ap-northeast-3:194566237122:layer:LambdaInsightsExtension:2`  | 
|  亚太地区（首尔） |  `arn:aws:lambda:ap-northeast-2:580247275435:layer:LambdaInsightsExtension:20`  | 
|  亚太地区（新加坡） |  `arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension:21`  | 
|  亚太地区（悉尼） |  `arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension:21`  | 
|  亚太地区（东京） |  `arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension:32`  | 
|  加拿大（中部） |  `arn:aws:lambda:ca-central-1:580247275435:layer:LambdaInsightsExtension:20`  | 
|  中国（北京） |  `arn:aws-cn:lambda:cn-north-1:488211338238:layer:LambdaInsightsExtension:14`  | 
|  中国（宁夏）； |  `arn:aws-cn:lambda:cn-northwest-1:488211338238:layer:LambdaInsightsExtension:14`  | 
|  欧洲地区（法兰克福） |  `arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension:21`  | 
|  欧洲地区（爱尔兰） |  `arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension:21`  | 
|  欧洲地区（伦敦） |  `arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension:21`  | 
|  欧洲地区（米兰） |  `arn:aws:lambda:eu-south-1:339249233099:layer:LambdaInsightsExtension:13`  | 
|  欧洲地区（巴黎） |  `arn:aws:lambda:eu-west-3:580247275435:layer:LambdaInsightsExtension:20`  | 
|  欧洲地区（斯德哥尔摩） |  `arn:aws:lambda:eu-north-1:580247275435:layer:LambdaInsightsExtension:20`  | 
|  中东（巴林） |  `arn:aws:lambda:me-south-1:285320876703:layer:LambdaInsightsExtension:13`  | 
|  南美洲（圣保罗） |  `arn:aws:lambda:sa-east-1:580247275435:layer:LambdaInsightsExtension:20`  | 

## 1.0.135.0
<a name="Lambda-Insights-extension-1.0.135.0"></a>

版本 1.0.135.0 包含针对 Lambda Insights 如何收集以及报告磁盘和文件描述符使用情况的错误修复。在此扩展程序的早期版本中，`tmp_free` 指标报告了函数运行时 `/tmp` 目录中的最大可用空间。此版本将指标更改为报告最小值，从而使其在评估磁盘使用情况时更有实用意义。有关 `tmp` 目录存储配额的更多信息，请参阅 [Lambda 配额](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-limits.html)。

版本 1.0.135.0 现在还报告文件描述符使用情况（`fd_use` 和 `fd_max`）作为进程范围内的最大值，而不是报告操作系统级别。

**适用于版本 1.0.135.0 的 ARN**

下表列出了要在各个 AWS 区域中用于此版本扩展程序的适用 ARN。


| 区域 | ARN | 
| --- | --- | 
|  美国东部（弗吉尼亚州北部） |  `arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:18`  | 
|  美国东部（俄亥俄州） |  `arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension:18`  | 
|  美国西部（北加利福尼亚） |  `arn:aws:lambda:us-west-1:580247275435:layer:LambdaInsightsExtension:18`  | 
|  美国西部（俄勒冈州） |  `arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension:18`  | 
|  非洲（开普敦） |  `arn:aws:lambda:af-south-1:012438385374:layer:LambdaInsightsExtension:11`  | 
|  亚太地区（香港） |  `arn:aws:lambda:ap-east-1:519774774795:layer:LambdaInsightsExtension:11`  | 
|  Asia Pacific (Mumbai) |  `arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension:18`  | 
|  亚太地区（大阪） |  `arn:aws:lambda:ap-northeast-3:194566237122:layer:LambdaInsightsExtension:1`  | 
|  亚太地区（首尔） |  `arn:aws:lambda:ap-northeast-2:580247275435:layer:LambdaInsightsExtension:18`  | 
|  亚太地区（新加坡） |  `arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension:18`  | 
|  亚太地区（悉尼） |  `arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension:18`  | 
|  亚太地区（东京） |  `arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension:25`  | 
|  加拿大（中部） |  `arn:aws:lambda:ca-central-1:580247275435:layer:LambdaInsightsExtension:18`  | 
|  中国（北京） |  `arn:aws-cn:lambda:cn-north-1:488211338238:layer:LambdaInsightsExtension:11`  | 
|  中国（宁夏）； |  `arn:aws-cn:lambda:cn-northwest-1:488211338238:layer:LambdaInsightsExtension:11`  | 
|  欧洲地区（法兰克福） |  `arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension:18`  | 
|  欧洲地区（爱尔兰） |  `arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension:18`  | 
|  欧洲地区（伦敦） |  `arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension:18`  | 
|  欧洲地区（米兰） |  `arn:aws:lambda:eu-south-1:339249233099:layer:LambdaInsightsExtension:11`  | 
|  欧洲地区（巴黎） |  `arn:aws:lambda:eu-west-3:580247275435:layer:LambdaInsightsExtension:18`  | 
|  欧洲地区（斯德哥尔摩） |  `arn:aws:lambda:eu-north-1:580247275435:layer:LambdaInsightsExtension:18`  | 
|  中东（巴林） |  `arn:aws:lambda:me-south-1:285320876703:layer:LambdaInsightsExtension:11`  | 
|  南美洲（圣保罗） |  `arn:aws:lambda:sa-east-1:580247275435:layer:LambdaInsightsExtension:18`  | 

## 1.0.119.0
<a name="Lambda-Insights-extension-1.0.119.0"></a>

**适用于 1.0.119.0 版本的 ARN**

下表列出了要在各个 AWS 区域中用于此版本扩展程序的适用 ARN。


| 区域 | ARN | 
| --- | --- | 
|  美国东部（弗吉尼亚州北部） |  `arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:16`  | 
|  美国东部（俄亥俄州） |  `arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension:16`  | 
|  美国西部（北加利福尼亚） |  `arn:aws:lambda:us-west-1:580247275435:layer:LambdaInsightsExtension:16`  | 
|  美国西部（俄勒冈州） |  `arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension:16`  | 
|  非洲（开普敦） |  `arn:aws:lambda:af-south-1:012438385374:layer:LambdaInsightsExtension:9`  | 
|  亚太地区（香港） |  `arn:aws:lambda:ap-east-1:519774774795:layer:LambdaInsightsExtension:9`  | 
|  亚太地区（孟买） |  `arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension:16`  | 
|  亚太地区（首尔） |  `arn:aws:lambda:ap-northeast-2:580247275435:layer:LambdaInsightsExtension:16`  | 
|  亚太地区（新加坡） |  `arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension:16`  | 
|  亚太地区（悉尼） |  `arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension:16`  | 
|  亚太地区（东京） |  `arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension:23`  | 
|  加拿大（中部） |  `arn:aws:lambda:ca-central-1:580247275435:layer:LambdaInsightsExtension:16`  | 
|  中国（北京） |  `arn:aws-cn:lambda:cn-north-1:488211338238:layer:LambdaInsightsExtension:9`  | 
|  中国（宁夏）； |  `arn:aws-cn:lambda:cn-northwest-1:488211338238:layer:LambdaInsightsExtension:9`  | 
|  欧洲地区（法兰克福） |  `arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension:16`  | 
|  欧洲地区（爱尔兰） |  `arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension:16`  | 
|  欧洲地区（伦敦） |  `arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension:16`  | 
|  欧洲地区（米兰） |  `arn:aws:lambda:eu-south-1:339249233099:layer:LambdaInsightsExtension:9`  | 
|  欧洲地区（巴黎） |  `arn:aws:lambda:eu-west-3:580247275435:layer:LambdaInsightsExtension:16`  | 
|  欧洲地区（斯德哥尔摩） |  `arn:aws:lambda:eu-north-1:580247275435:layer:LambdaInsightsExtension:16`  | 
|  中东（巴林） |  `arn:aws:lambda:me-south-1:285320876703:layer:LambdaInsightsExtension:9`  | 
|  南美洲（圣保罗） |  `arn:aws:lambda:sa-east-1:580247275435:layer:LambdaInsightsExtension:16`  | 

## 1.0.98.0
<a name="Lambda-Insights-extension-1.0.98.0"></a>

此版本删除了不必要的日志记录功能，并解决了 AWS Serverless Application Model CLI 本地调用的一个问题。有关此问题的更多信息，请参阅[在具有“sam 本地调用”的超时中添加 LambdaInsightsExtension 结果](https://github.com/aws/aws-sam-cli/issues/2469)。

**适用于版本 1.0.98.0 的 ARN**

下表列出了要在各个 AWS 区域中用于此版本扩展程序的适用 ARN。


| 区域 | ARN | 
| --- | --- | 
|  美国东部（弗吉尼亚州北部） |  `arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:14`  | 
|  美国东部（俄亥俄州） |  `arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension:14`  | 
|  美国西部（北加利福尼亚） |  `arn:aws:lambda:us-west-1:580247275435:layer:LambdaInsightsExtension:14`  | 
|  美国西部（俄勒冈州） |  `arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension:14`  | 
|  非洲（开普敦） |  `arn:aws:lambda:af-south-1:012438385374:layer:LambdaInsightsExtension:8`  | 
|  亚太地区（香港） |  `arn:aws:lambda:ap-east-1:519774774795:layer:LambdaInsightsExtension:8`  | 
|  亚太地区（孟买） |  `arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension:14`  | 
|  亚太地区（首尔） |  `arn:aws:lambda:ap-northeast-2:580247275435:layer:LambdaInsightsExtension:14`  | 
|  亚太地区（新加坡） |  `arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension:14`  | 
|  亚太地区（悉尼） |  `arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension:14`  | 
|  亚太地区（东京） |  `arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension:14`  | 
|  加拿大（中部） |  `arn:aws:lambda:ca-central-1:580247275435:layer:LambdaInsightsExtension:14`  | 
|  中国（北京） |  `arn:aws-cn:lambda:cn-north-1:488211338238:layer:LambdaInsightsExtension:8`  | 
|  中国（宁夏）； |  `arn:aws-cn:lambda:cn-northwest-1:488211338238:layer:LambdaInsightsExtension:8`  | 
|  欧洲地区（法兰克福） |  `arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension:14`  | 
|  欧洲地区（爱尔兰） |  `arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension:14`  | 
|  欧洲地区（伦敦） |  `arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension:14`  | 
|  欧洲地区（米兰） |  `arn:aws:lambda:eu-south-1:339249233099:layer:LambdaInsightsExtension:8`  | 
|  欧洲地区（巴黎） |  `arn:aws:lambda:eu-west-3:580247275435:layer:LambdaInsightsExtension:14`  | 
|  欧洲地区（斯德哥尔摩） |  `arn:aws:lambda:eu-north-1:580247275435:layer:LambdaInsightsExtension:14`  | 
|  中东（巴林） |  `arn:aws:lambda:me-south-1:285320876703:layer:LambdaInsightsExtension:8`  | 
|  南美洲（圣保罗） |  `arn:aws:lambda:sa-east-1:580247275435:layer:LambdaInsightsExtension:14`  | 

## 1.0.89.0
<a name="Lambda-Insights-extension-1.0.89.0"></a>

此版本将性能事件时间戳更正为始终表示函数调用的开始。

**适用于版本 1.0.89.0 的 ARN**

下表列出了要在各个 AWS 区域中用于此版本扩展程序的适用 ARN。


| 区域 | ARN | 
| --- | --- | 
|  美国东部（弗吉尼亚州北部） |  `arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:12`  | 
|  美国东部（俄亥俄州） |  `arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension:12`  | 
|  美国西部（北加利福尼亚） |  `arn:aws:lambda:us-west-1:580247275435:layer:LambdaInsightsExtension:12`  | 
|  美国西部（俄勒冈州） |  `arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension:12`  | 
|  亚太地区（孟买） |  `arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension:12`  | 
|  亚太地区（首尔） |  `arn:aws:lambda:ap-northeast-2:580247275435:layer:LambdaInsightsExtension:12`  | 
|  亚太地区（新加坡） |  `arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension:12`  | 
|  亚太地区（悉尼） |  `arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension:12`  | 
|  亚太地区（东京） |  `arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension:12`  | 
|  加拿大（中部） |  `arn:aws:lambda:ca-central-1:580247275435:layer:LambdaInsightsExtension:12`  | 
|  欧洲地区（法兰克福） |  `arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension:12`  | 
|  欧洲地区（爱尔兰） |  `arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension:12`  | 
|  欧洲地区（伦敦） |  `arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension:12`  | 
|  欧洲地区（巴黎） |  `arn:aws:lambda:eu-west-3:580247275435:layer:LambdaInsightsExtension:12`  | 
|  欧洲地区（斯德哥尔摩） |  `arn:aws:lambda:eu-north-1:580247275435:layer:LambdaInsightsExtension:12`  | 
|  南美洲（圣保罗） |  `arn:aws:lambda:sa-east-1:580247275435:layer:LambdaInsightsExtension:12`  | 

## 1.0.86.0
<a name="Lambda-Insights-extension-1.0.86.0"></a>

此扩展程序的 1.0.54.0 版本有时会误报内存指标，有时这些指标会高于 100%。1.0.86.0 版本使用与 Lambda 平台指标相同的事件数据，纠正了内存度量问题。也就是说，您可能会发现所记录的内存指标值发生了巨大变化。这是通过使用新的 Lambda Logs API 来实现的。它可以更准确地度量 Lambda 沙盒内存使用情况。但需要注意的是，如果函数沙盒超时并随后崩溃，Lambda Logs API 将无法提供平台报告事件。在本例中，Lambda Insights 无法记录调用指标。有关 Lambda Logs API 的更多信息，请参阅 [AWS Lambda Logs API](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-logs-api.html)。

**版本 1.0.86.0 中的新功能**
+ 使用 Lambda Logs API 更正内存指标。此功能解决了上一个内存统计数据大于 100% 的问题。
+ 引入新的 CloudWatch 指标：`Init Duration`。
+ 使用调用 ARN 为别名和调用的版本添加**版本**维度。如果您使用 Lambda 别名或版本来实现递增部署（如蓝-绿部署），则可以根据调用的别名查看指标。如果函数不使用别名或版本，则**版本**维度不适用。有关更多信息，请参阅 [Lambda 函数别名](https://docs.aws.amazon.com/lambda/latest/dg/configuration-aliases.html)。
+ 向性能事件添加 `billed_mb_ms field` 以显示每次调用的成本。这些成本中未考虑与预置并发相关的任何成本。
+ 向性能事件添加 `billed_duration` 和 `duration` 字段。

**适用于版本 1.0.86.0 的 ARN**

下表列出了要在各个 AWS 区域中用于此版本扩展程序的适用 ARN。


| 区域 | ARN | 
| --- | --- | 
|  美国东部（弗吉尼亚州北部） |  `arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:11`  | 
|  美国东部（俄亥俄州） |  `arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension:11`  | 
|  美国西部（北加利福尼亚） |  `arn:aws:lambda:us-west-1:580247275435:layer:LambdaInsightsExtension:11`  | 
|  美国西部（俄勒冈州） |  `arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension:11`  | 
|  亚太地区（孟买） |  `arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension:11`  | 
|  亚太地区（首尔） |  `arn:aws:lambda:ap-northeast-2:580247275435:layer:LambdaInsightsExtension:11`  | 
|  亚太地区（新加坡） |  `arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension:11`  | 
|  亚太地区（悉尼） |  `arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension:11`  | 
|  亚太地区（东京） |  `arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension:11`  | 
|  加拿大（中部） |  `arn:aws:lambda:ca-central-1:580247275435:layer:LambdaInsightsExtension:11`  | 
|  欧洲地区（法兰克福） |  `arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension:11`  | 
|  欧洲地区（爱尔兰） |  `arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension:11`  | 
|  欧洲地区（伦敦） |  `arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension:11`  | 
|  欧洲地区（巴黎） |  `arn:aws:lambda:eu-west-3:580247275435:layer:LambdaInsightsExtension:11`  | 
|  欧洲地区（斯德哥尔摩） |  `arn:aws:lambda:eu-north-1:580247275435:layer:LambdaInsightsExtension:11`  | 
|  南美洲（圣保罗） |  `arn:aws:lambda:sa-east-1:580247275435:layer:LambdaInsightsExtension:11`  | 

## 1.0.54.0
<a name="Lambda-Insights-extension-1.0.54.0"></a>

1.0.54.0 版本是 Lambda Insights 扩展程序的初始版本。

**适用于版本 1.0.54.0 的 ARN**

下表列出了要在各个 AWS 区域中用于此版本扩展程序的适用 ARN。


| 区域 | ARN | 
| --- | --- | 
|  美国东部（弗吉尼亚州北部） |  `arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:2`  | 
|  美国东部（俄亥俄州） |  `arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension:2`  | 
|  美国西部（北加利福尼亚） |  `arn:aws:lambda:us-west-1:580247275435:layer:LambdaInsightsExtension:2`  | 
|  美国西部（俄勒冈州） |  `arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension:2`  | 
|  亚太地区（孟买） |  `arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension:2`  | 
|  亚太地区（首尔） |  `arn:aws:lambda:ap-northeast-2:580247275435:layer:LambdaInsightsExtension:2`  | 
|  亚太地区（新加坡） |  `arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension:2`  | 
|  亚太地区（悉尼） |  `arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension:2`  | 
|  亚太地区（东京） |  `arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension:2`  | 
|  加拿大（中部） |  `arn:aws:lambda:ca-central-1:580247275435:layer:LambdaInsightsExtension:2`  | 
|  欧洲地区（法兰克福） |  `arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension:2`  | 
|  欧洲地区（爱尔兰） |  `arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension:2`  | 
|  欧洲地区（伦敦） |  `arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension:2`  | 
|  欧洲地区（巴黎） |  `arn:aws:lambda:eu-west-3:580247275435:layer:LambdaInsightsExtension:2`  | 
|  欧洲地区（斯德哥尔摩） |  `arn:aws:lambda:eu-north-1:580247275435:layer:LambdaInsightsExtension:2`  | 
|  南美洲（圣保罗） |  `arn:aws:lambda:sa-east-1:580247275435:layer:LambdaInsightsExtension:2`  | 

# ARM64 平台
<a name="Lambda-Insights-extension-versionsARM"></a>

本节列出了适用于 ARM64 平台的 Lambda Insights 扩展程序版本，以及要在每个 AWS 区域用于这些扩展程序的 ARN。

**重要**  
Lambda Insights 扩展版 1.0.317.0 和更高版本不支持 Amazon Linux 1。

## 1.0.660.0
<a name="Lambda-Insights-extension-ARM-1.0.660.0"></a>

1.0.660.0 版本为运行于 Lambda 托管实例的 Lambda 函数新增 Lambda 洞察扩展支持。对于运行在 Lambda 托管实例上的函数，该扩展程序将每分钟发送一次 EMF 日志事件，以 1 分钟粒度生成 12 项 CloudWatch Metrics 指标。


| 区域 | ARN | 
| --- | --- | 
|  美国东部（弗吉尼亚州北部） |  `arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension-Arm64:31`  | 
|  美国东部（俄亥俄州） |  `arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension-Arm64:33`  | 
|  美国西部（北加利福尼亚） |  `arn:aws:lambda:us-west-1:580247275435:layer:LambdaInsightsExtension-Arm64:29`  | 
|  美国西部（俄勒冈州） |  `arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension-Arm64:31`  | 
|  非洲（开普敦） |  `arn:aws:lambda:af-south-1:012438385374:layer:LambdaInsightsExtension-Arm64:30`  | 
|  亚太地区（香港） |  `arn:aws:lambda:ap-east-1:519774774795:layer:LambdaInsightsExtension-Arm64:30`  | 
|  亚太地区（海得拉巴） |  `arn:aws:lambda:ap-south-2:891564319516:layer:LambdaInsightsExtension-Arm64:18`  | 
|  亚太地区（雅加达） |  `arn:aws:lambda:ap-southeast-3:439286490199:layer:LambdaInsightsExtension-Arm64:30`  | 
|  亚太地区（马来西亚） |  `arn:aws:lambda:ap-southeast-5:590183865173:layer:LambdaInsightsExtension-Arm64:7`  | 
|  亚太地区（墨尔本） |  `arn:aws:lambda:ap-southeast-4:158895979263:layer:LambdaInsightsExtension-Arm64:7`  | 
|  亚太地区（孟买） |  `arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension-Arm64:33`  | 
|  亚太地区（新西兰） |  `arn:aws:lambda:ap-southeast-6:727646510379:layer:LambdaInsightsExtension-Arm64:165`  | 
|  亚太地区（大阪） |  `arn:aws:lambda:ap-northeast-3:194566237122:layer:LambdaInsightsExtension-Arm64:28`  | 
|  亚太地区（首尔） |  `arn:aws:lambda:ap-northeast-2:580247275435:layer:LambdaInsightsExtension-Arm64:30`  | 
|  亚太地区（新加坡） |  `arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension-Arm64:31`  | 
|  亚太地区（悉尼） |  `arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension-Arm64:31`  | 
|  亚太地区（台北） |  `arn:aws:lambda:ap-east-2:145023102084:layer:LambdaInsightsExtension-Arm64:7`  | 
|  亚太地区（泰国） |  `arn:aws:lambda:ap-southeast-7:761018874580:layer:LambdaInsightsExtension-Arm64:7`  | 
|  亚太地区（东京） |  `arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension-Arm64:42`  | 
|  加拿大（中部） |  `arn:aws:lambda:ca-central-1:580247275435:layer:LambdaInsightsExtension-Arm64:29`  | 
|  加拿大西部（卡尔加里） |  `arn:aws:lambda:ca-west-1:946466191631:layer:LambdaInsightsExtension-Arm64:7`  | 
|  中国（北京） |  `arn:aws-cn:lambda:cn-north-1:488211338238:layer:LambdaInsightsExtension-Arm64:4`  | 
|  中国（宁夏） |  `arn:aws-cn:lambda:cn-northwest-1:488211338238:layer:LambdaInsightsExtension-Arm64:4`  | 
|  欧洲地区（法兰克福） |  `arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension-Arm64:31`  | 
|  欧洲地区（爱尔兰） |  `arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension-Arm64:31`  | 
|  欧洲地区（伦敦） |  `arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension-Arm64:31`  | 
|  欧洲地区（米兰） |  `arn:aws:lambda:eu-south-1:339249233099:layer:LambdaInsightsExtension-Arm64:30`  | 
|  欧洲地区（巴黎） |  `arn:aws:lambda:eu-west-3:580247275435:layer:LambdaInsightsExtension-Arm64:29`  | 
|  欧洲（西班牙） |  `arn:aws:lambda:eu-south-2:352183217350:layer:LambdaInsightsExtension-Arm64:18`  | 
|  欧洲地区（斯德哥尔摩） |  `arn:aws:lambda:eu-north-1:580247275435:layer:LambdaInsightsExtension-Arm64:29`  | 
|  欧洲（苏黎世） |  `arn:aws:lambda:eu-central-2:033019950311:layer:LambdaInsightsExtension-Arm64:7`  | 
|  以色列（特拉维夫） |  `arn:aws:lambda:il-central-1:459530977127:layer:LambdaInsightsExtension-Arm64:7`  | 
|  墨西哥（中部） |  `arn:aws:lambda:mx-central-1:879381266642:layer:LambdaInsightsExtension-Arm64:7`  | 
|  中东（巴林） |  `arn:aws:lambda:me-south-1:285320876703:layer:LambdaInsightsExtension-Arm64:30`  | 
|  中东（阿联酋）： |  `arn:aws:lambda:me-central-1:732604637566:layer:LambdaInsightsExtension-Arm64:7`  | 
|  南美洲（圣保罗） |  `arn:aws:lambda:sa-east-1:580247275435:layer:LambdaInsightsExtension-Arm64:29`  | 
|  AWS GovCloud（美国东部） |  `arn:aws-us-gov:lambda:us-gov-east-1:122132214140:layer:LambdaInsightsExtension-Arm64:6`  | 
|  AWS GovCloud（美国西部） |  `arn:aws-us-gov:lambda:us-gov-west-1:751350123760:layer:LambdaInsightsExtension-Arm64:6`  | 

## 1.0.498.0
<a name="Lambda-Insights-extension-ARM-1.0.498.0"></a>

1.0.498.0 版本包含错误修复与性能改进。


| 区域 | ARN | 
| --- | --- | 
|  美国东部（弗吉尼亚州北部） |  `arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension-Arm64:27`  | 
|  美国东部（俄亥俄州） |  `arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension-Arm64:29`  | 
|  美国西部（北加利福尼亚） |  `arn:aws:lambda:us-west-1:580247275435:layer:LambdaInsightsExtension-Arm64:25`  | 
|  美国西部（俄勒冈州） |  `arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension-Arm64:27`  | 
|  非洲（开普敦） |  `arn:aws:lambda:af-south-1:012438385374:layer:LambdaInsightsExtension-Arm64:26`  | 
|  亚太地区（香港） |  `arn:aws:lambda:ap-east-1:519774774795:layer:LambdaInsightsExtension-Arm64:26`  | 
|  Asia Pacific (Mumbai) |  `arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension-Arm64:29`  | 
|  亚太地区（海得拉巴） |  `arn:aws:lambda:ap-south-2:891564319516:layer:LambdaInsightsExtension-Arm64:14`  | 
|  亚太地区（新加坡） |  `arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension-Arm64:27`  | 
|  亚太地区（悉尼） |  `arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension-Arm64:27`  | 
|  亚太地区（雅加达） |  `arn:aws:lambda:ap-southeast-3:439286490199:layer:LambdaInsightsExtension-Arm64:26`  | 
|  亚太地区（墨尔本） |  `arn:aws:lambda:ap-southeast-4:158895979263:layer:LambdaInsightsExtension-Arm64:3`  | 
|  亚太地区（马来西亚） |  `arn:aws:lambda:ap-southeast-5:590183865173:layer:LambdaInsightsExtension-Arm64:3`  | 
|  亚太地区（泰国） |  `arn:aws:lambda:ap-southeast-7:761018874580:layer:LambdaInsightsExtension-Arm64:2`  | 
|  亚太地区（东京） |  `arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension-Arm64:38`  | 
|  亚太地区（首尔） |  `arn:aws:lambda:ap-northeast-2:580247275435:layer:LambdaInsightsExtension-Arm64:26`  | 
|  亚太地区（大阪） |  `arn:aws:lambda:ap-northeast-3:194566237122:layer:LambdaInsightsExtension-Arm64:24`  | 
|  加拿大（中部） |  `arn:aws:lambda:ca-central-1:580247275435:layer:LambdaInsightsExtension-Arm64:25`  | 
|  加拿大西部（卡尔加里） |  `arn:aws:lambda:ca-west-1:946466191631:layer:LambdaInsightsExtension-Arm64:3`  | 
|  欧洲地区（法兰克福） |  `arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension-Arm64:27`  | 
|  欧洲（苏黎世） |  `arn:aws:lambda:eu-central-2:033019950311:layer:LambdaInsightsExtension-Arm64:3`  | 
|  欧洲地区（爱尔兰） |  `arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension-Arm64:27`  | 
|  欧洲地区（伦敦） |  `arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension-Arm64:27`  | 
|  欧洲地区（巴黎） |  `arn:aws:lambda:eu-west-3:580247275435:layer:LambdaInsightsExtension-Arm64:25`  | 
|  欧洲地区（斯德哥尔摩） |  `arn:aws:lambda:eu-north-1:580247275435:layer:LambdaInsightsExtension-Arm64:25`  | 
|  欧洲地区（米兰） |  `arn:aws:lambda:eu-south-1:339249233099:layer:LambdaInsightsExtension-Arm64:26`  | 
|  欧洲（西班牙） |  `arn:aws:lambda:eu-south-2:352183217350:layer:LambdaInsightsExtension-Arm64:14`  | 
|  以色列（特拉维夫） |  `arn:aws:lambda:il-central-1:459530977127:layer:LambdaInsightsExtension-Arm64:3`  | 
|  墨西哥（中部） |  `arn:aws:lambda:mx-central-1:879381266642:layer:LambdaInsightsExtension-Arm64:2`  | 
|  中东（巴林） |  `arn:aws:lambda:me-south-1:285320876703:layer:LambdaInsightsExtension-Arm64:26`  | 
|  中东（阿联酋）： |  `arn:aws:lambda:me-central-1:732604637566:layer:LambdaInsightsExtension-Arm64:3`  | 
|  南美洲（圣保罗） |  `arn:aws:lambda:sa-east-1:580247275435:layer:LambdaInsightsExtension-Arm64:25`  | 
|  China (Beijing) |  `arn:aws-cn:lambda:cn-north-1:488211338238:layer:LambdaInsightsExtension-Arm64:1`  | 
|  China (Ningxia) |  `arn:aws-cn:lambda:cn-northwest-1:488211338238:layer:LambdaInsightsExtension-Arm64:1`  | 
|  AWS GovCloud（美国东部） |  `arn:aws-us-gov:lambda:us-gov-east-1:122132214140:layer:LambdaInsightsExtension-Arm64:6`  | 
|  AWS GovCloud（美国西部） |  `arn:aws-us-gov:lambda:us-gov-west-1:751350123760:layer:LambdaInsightsExtension-Arm64:6`  | 

## 1.0.404.0
<a name="Lambda-Insights-extension-ARM-1.0.404.0"></a>

版本 1.0.404.0 将 Lambda Insights 扩展程序的二进制大小从约 9MB 减少到约 5MB，随后将 Lambda Insights 扩展层的 zip 大小从约 3.7MB 减少到约 2.5MB。还可以将代理的总体内存消耗量从约 11MB 减少到约 7MB。


| 区域 | ARN | 
| --- | --- | 
|  美国东部（弗吉尼亚州北部） |  `arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension-Arm64:23`  | 
|  美国东部（俄亥俄州） |  `arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension-Arm64:25`  | 
|  美国西部（北加利福尼亚） |  `arn:aws:lambda:us-west-1:580247275435:layer:LambdaInsightsExtension-Arm64:21`  | 
|  美国西部（俄勒冈州） |  `arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension-Arm64:23`  | 
|  非洲（开普敦） |  `arn:aws:lambda:af-south-1:012438385374:layer:LambdaInsightsExtension-Arm64:21`  | 
|  亚太地区（香港） |  `arn:aws:lambda:ap-east-1:519774774795:layer:LambdaInsightsExtension-Arm64:21`  | 
|  亚太地区（海得拉巴） |  `arn:aws:lambda:ap-south-2:891564319516:layer:LambdaInsightsExtension-Arm64:9`  | 
|  亚太地区（雅加达） |  `arn:aws:lambda:ap-southeast-3:439286490199:layer:LambdaInsightsExtension-Arm64:21`  | 
|  亚太地区（孟买） |  `arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension-Arm64:25`  | 
|  亚太地区（大阪） |  `arn:aws:lambda:ap-northeast-3:194566237122:layer:LambdaInsightsExtension-Arm64:20`  | 
|  亚太地区（首尔） |  `arn:aws:lambda:ap-northeast-2:580247275435:layer:LambdaInsightsExtension-Arm64:22`  | 
|  亚太地区（新加坡） |  `arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension-Arm64:23`  | 
|  亚太地区（悉尼） |  `arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension-Arm64:23`  | 
|  亚太地区（东京） |  `arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension-Arm64:34`  | 
|  加拿大（中部） |  `arn:aws:lambda:ca-central-1:580247275435:layer:LambdaInsightsExtension-Arm64:21`  | 
|  欧洲地区（法兰克福） |  `arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension-Arm64:23`  | 
|  欧洲地区（爱尔兰） |  `arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension-Arm64:23`  | 
|  欧洲地区（伦敦） |  `arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension-Arm64:23`  | 
|  欧洲地区（米兰） |  `arn:aws:lambda:eu-south-1:339249233099:layer:LambdaInsightsExtension-Arm64:21`  | 
|  欧洲地区（巴黎） |  `arn:aws:lambda:eu-west-3:580247275435:layer:LambdaInsightsExtension-Arm64:21`  | 
|  欧洲（西班牙） |  `arn:aws:lambda:eu-south-2:352183217350:layer:LambdaInsightsExtension-Arm64:9`  | 
|  欧洲地区（斯德哥尔摩） |  `arn:aws:lambda:eu-north-1:580247275435:layer:LambdaInsightsExtension-Arm64:21`  | 
|  中东（巴林） |  `arn:aws:lambda:me-south-1:285320876703:layer:LambdaInsightsExtension-Arm64:21`  | 
|  南美洲（圣保罗） |  `arn:aws:lambda:sa-east-1:580247275435:layer:LambdaInsightsExtension-Arm64:21`  | 
|  AWS GovCloud（美国东部） |  `arn:aws-us-gov:lambda:us-gov-east-1:122132214140:layer:LambdaInsightsExtension-Arm64:6`  | 
|  AWS GovCloud（美国西部） |  `arn:aws-us-gov:lambda:us-gov-west-1:751350123760:layer:LambdaInsightsExtension-Arm64:6`  | 

## 1.0.391.0
<a name="Lambda-Insights-extension-ARM-1.0.391.0"></a>

**重要**  
版本 1.0.391.0 更改了 Lambda Insights 收集和报告线程使用情况的方式。在此扩展程序的早期版本中，`threads_max` 指标报告的是进程 ID 为 1 的进程中运行的最大线程数。从版本 1.0.391.0 开始，此指标将报告在函数执行期间任何时间点执行环境中所有进程中运行的最大线程数。这包括 Lambda 函数的进程、扩展程序的进程、特定于系统/运行时的进程等。这样，`threads_max` 指标在评估可供您使用的剩余线程时更加全面。有关线程和进程配额的更多信息，请参阅 [Lambda 配额](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-limits.html)。


| 区域 | ARN | 
| --- | --- | 
|  美国东部（弗吉尼亚州北部） |  `arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension-Arm64:22`  | 
|  美国东部（俄亥俄州） |  `arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension-Arm64:24`  | 
|  美国西部（北加利福尼亚） |  `arn:aws:lambda:us-west-1:580247275435:layer:LambdaInsightsExtension-Arm64:20`  | 
|  美国西部（俄勒冈州） |  `arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension-Arm64:22`  | 
|  非洲（开普敦） |  `arn:aws:lambda:af-south-1:012438385374:layer:LambdaInsightsExtension-Arm64:20`  | 
|  亚太地区（香港） |  `arn:aws:lambda:ap-east-1:519774774795:layer:LambdaInsightsExtension-Arm64:20`  | 
|  亚太地区（海得拉巴） |  `arn:aws:lambda:ap-south-2:891564319516:layer:LambdaInsightsExtension-Arm64:8`  | 
|  亚太地区（雅加达） |  `arn:aws:lambda:ap-southeast-3:439286490199:layer:LambdaInsightsExtension-Arm64:20`  | 
|  亚太地区（孟买） |  `arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension-Arm64:24`  | 
|  亚太地区（大阪） |  `arn:aws:lambda:ap-northeast-3:194566237122:layer:LambdaInsightsExtension-Arm64:19`  | 
|  亚太地区（首尔） |  `arn:aws:lambda:ap-northeast-2:580247275435:layer:LambdaInsightsExtension-Arm64:21`  | 
|  亚太地区（新加坡） |  `arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension-Arm64:22`  | 
|  亚太地区（悉尼） |  `arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension-Arm64:22`  | 
|  亚太地区（东京） |  `arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension-Arm64:33`  | 
|  加拿大（中部） |  `arn:aws:lambda:ca-central-1:580247275435:layer:LambdaInsightsExtension-Arm64:20`  | 
|  欧洲地区（法兰克福） |  `arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension-Arm64:22`  | 
|  欧洲地区（爱尔兰） |  `arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension-Arm64:22`  | 
|  欧洲地区（伦敦） |  `arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension-Arm64:22`  | 
|  欧洲地区（米兰） |  `arn:aws:lambda:eu-south-1:339249233099:layer:LambdaInsightsExtension-Arm64:20`  | 
|  欧洲地区（巴黎） |  `arn:aws:lambda:eu-west-3:580247275435:layer:LambdaInsightsExtension-Arm64:20`  | 
|  欧洲（西班牙） |  `arn:aws:lambda:eu-south-2:352183217350:layer:LambdaInsightsExtension-Arm64:8`  | 
|  欧洲地区（斯德哥尔摩） |  `arn:aws:lambda:eu-north-1:580247275435:layer:LambdaInsightsExtension-Arm64:20`  | 
|  中东（巴林） |  `arn:aws:lambda:me-south-1:285320876703:layer:LambdaInsightsExtension-Arm64:20`  | 
|  南美洲（圣保罗） |  `arn:aws:lambda:sa-east-1:580247275435:layer:LambdaInsightsExtension-Arm64:20`  | 
|  AWS GovCloud（美国东部） |  `arn:aws-us-gov:lambda:us-gov-east-1:122132214140:layer:LambdaInsightsExtension-Arm64:5`  | 
|  AWS GovCloud（美国西部） |  `arn:aws-us-gov:lambda:us-gov-west-1:751350123760:layer:LambdaInsightsExtension-Arm64:5`  | 

## 1.0.333.0
<a name="Lambda-Insights-extension-ARM-1.0.333.0"></a>

版本 1.0.333.0 包括错误修复。


| 区域 | ARN | 
| --- | --- | 
|  美国东部（弗吉尼亚州北部） |  `arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension-Arm64:20`  | 
|  美国东部（俄亥俄州） |  `arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension-Arm64:22`  | 
|  美国西部（北加利福尼亚） |  `arn:aws:lambda:us-west-1:580247275435:layer:LambdaInsightsExtension-Arm64:18`  | 
|  美国西部（俄勒冈州） |  `arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension-Arm64:20`  | 
|  非洲（开普敦） |  `arn:aws:lambda:af-south-1:012438385374:layer:LambdaInsightsExtension-Arm64:18`  | 
|  亚太地区（香港） |  `arn:aws:lambda:ap-east-1:519774774795:layer:LambdaInsightsExtension-Arm64:18`  | 
|  亚太地区（海得拉巴） |  `arn:aws:lambda:ap-south-2:891564319516:layer:LambdaInsightsExtension-Arm64:6`  | 
|  亚太地区（雅加达） |  `arn:aws:lambda:ap-southeast-3:439286490199:layer:LambdaInsightsExtension-Arm64:18`  | 
|  亚太地区（孟买） |  `arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension-Arm64:22`  | 
|  亚太地区（大阪） |  `arn:aws:lambda:ap-northeast-3:194566237122:layer:LambdaInsightsExtension-Arm64:17`  | 
|  亚太地区（首尔） |  `arn:aws:lambda:ap-northeast-2:580247275435:layer:LambdaInsightsExtension-Arm64:19`  | 
|  亚太地区（新加坡） |  `arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension-Arm64:20`  | 
|  亚太地区（悉尼） |  `arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension-Arm64:20`  | 
|  亚太地区（东京） |  `arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension-Arm64:31`  | 
|  加拿大（中部） |  `arn:aws:lambda:ca-central-1:580247275435:layer:LambdaInsightsExtension-Arm64:18`  | 
|  欧洲地区（法兰克福） |  `arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension-Arm64:20`  | 
|  欧洲地区（爱尔兰） |  `arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension-Arm64:20`  | 
|  欧洲地区（伦敦） |  `arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension-Arm64:20`  | 
|  欧洲地区（米兰） |  `arn:aws:lambda:eu-south-1:339249233099:layer:LambdaInsightsExtension-Arm64:18`  | 
|  欧洲地区（巴黎） |  `arn:aws:lambda:eu-west-3:580247275435:layer:LambdaInsightsExtension-Arm64:18`  | 
|  欧洲（西班牙） |  `arn:aws:lambda:eu-south-2:352183217350:layer:LambdaInsightsExtension-Arm64:6`  | 
|  欧洲地区（斯德哥尔摩） |  `arn:aws:lambda:eu-north-1:580247275435:layer:LambdaInsightsExtension-Arm64:18`  | 
|  中东（巴林） |  `arn:aws:lambda:me-south-1:285320876703:layer:LambdaInsightsExtension-Arm64:18`  | 
|  南美洲（圣保罗） |  `arn:aws:lambda:sa-east-1:580247275435:layer:LambdaInsightsExtension-Arm64:18`  | 
|  AWS GovCloud（美国东部） |  `arn:aws-us-gov:lambda:us-gov-east-1:122132214140:layer:LambdaInsightsExtension-Arm64:3`  | 
|  AWS GovCloud（美国西部） |  `arn:aws-us-gov:lambda:us-gov-west-1:751350123760:layer:LambdaInsightsExtension-Arm64:3`  | 

## 1.0.317.0
<a name="Lambda-Insights-extension-ARM-1.0.317.0"></a>

版本 1.0.317.0 包括取消对 Amazon Linux 1 平台的支持和错误修复。它还包括对 AWS GovCloud (US) 区域的支持。


| 区域 | ARN | 
| --- | --- | 
|  美国东部（弗吉尼亚州北部） |  `arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension-Arm64:19`  | 
|  美国东部（俄亥俄州） |  `arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension-Arm64:21`  | 
|  美国西部（北加利福尼亚） |  `arn:aws:lambda:us-west-1:580247275435:layer:LambdaInsightsExtension-Arm64:17`  | 
|  美国西部（俄勒冈州） |  `arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension-Arm64:19`  | 
|  非洲（开普敦） |  `arn:aws:lambda:af-south-1:012438385374:layer:LambdaInsightsExtension-Arm64:17`  | 
|  亚太地区（香港） |  `arn:aws:lambda:ap-east-1:519774774795:layer:LambdaInsightsExtension-Arm64:17`  | 
|  亚太地区（海得拉巴） |  `arn:aws:lambda:ap-south-2:891564319516:layer:LambdaInsightsExtension-Arm64:5`  | 
|  亚太地区（雅加达） |  `arn:aws:lambda:ap-southeast-3:439286490199:layer:LambdaInsightsExtension-Arm64:17`  | 
|  亚太地区（孟买） |  `arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension-Arm64:21`  | 
|  亚太地区（大阪） |  `arn:aws:lambda:ap-northeast-3:194566237122:layer:LambdaInsightsExtension-Arm64:16`  | 
|  亚太地区（首尔） |  `arn:aws:lambda:ap-northeast-2:580247275435:layer:LambdaInsightsExtension-Arm64:18`  | 
|  亚太地区（新加坡） |  `arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension-Arm64:19`  | 
|  亚太地区（悉尼） |  `arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension-Arm64:19`  | 
|  亚太地区（东京） |  `arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension-Arm64:30`  | 
|  加拿大（中部） |  `arn:aws:lambda:ca-central-1:580247275435:layer:LambdaInsightsExtension-Arm64:17`  | 
|  欧洲地区（法兰克福） |  `arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension-Arm64:19`  | 
|  欧洲地区（爱尔兰） |  `arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension-Arm64:19`  | 
|  欧洲地区（伦敦） |  `arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension-Arm64:19`  | 
|  欧洲地区（米兰） |  `arn:aws:lambda:eu-south-1:339249233099:layer:LambdaInsightsExtension-Arm64:17`  | 
|  欧洲地区（巴黎） |  `arn:aws:lambda:eu-west-3:580247275435:layer:LambdaInsightsExtension-Arm64:17`  | 
|  欧洲（西班牙） |  `arn:aws:lambda:eu-south-2:352183217350:layer:LambdaInsightsExtension-Arm64:5`  | 
|  欧洲地区（斯德哥尔摩） |  `arn:aws:lambda:eu-north-1:580247275435:layer:LambdaInsightsExtension-Arm64:17`  | 
|  中东（巴林） |  `arn:aws:lambda:me-south-1:285320876703:layer:LambdaInsightsExtension-Arm64:17`  | 
|  南美洲（圣保罗） |  `arn:aws:lambda:sa-east-1:580247275435:layer:LambdaInsightsExtension-Arm64:17`  | 
|  AWS GovCloud（美国东部） |  `arn:aws-us-gov:lambda:us-gov-east-1:122132214140:layer:LambdaInsightsExtension-Arm64:1`  | 
|  AWS GovCloud（美国西部） |  `arn:aws-us-gov:lambda:us-gov-west-1:751350123760:layer:LambdaInsightsExtension-Arm64:1`  | 

## 1.0.295.0
<a name="Lambda-Insights-extension-ARM-1.0.295.0"></a>

版本 1.0.295.0 包含对所有兼容的运行时系统的依赖项更新。


| 区域 | ARN | 
| --- | --- | 
|  美国东部（弗吉尼亚州北部） |  `arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension-Arm64:18`  | 
|  美国东部（俄亥俄州） |  `arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension-Arm64:20`  | 
|  美国西部（北加利福尼亚） |  `arn:aws:lambda:us-west-1:580247275435:layer:LambdaInsightsExtension-Arm64:16`  | 
|  美国西部（俄勒冈州） |  `arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension-Arm64:18`  | 
|  非洲（开普敦） |  `arn:aws:lambda:af-south-1:012438385374:layer:LambdaInsightsExtension-Arm64:16`  | 
|  亚太地区（香港） |  `arn:aws:lambda:ap-east-1:519774774795:layer:LambdaInsightsExtension-Arm64:16`  | 
|  亚太地区（海得拉巴） |  `arn:aws:lambda:ap-south-2:891564319516:layer:LambdaInsightsExtension-Arm64:4`  | 
|  亚太地区（雅加达） |  `arn:aws:lambda:ap-southeast-3:439286490199:layer:LambdaInsightsExtension-Arm64:16`  | 
|  亚太地区（孟买） |  `arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension-Arm64:20`  | 
|  亚太地区（大阪） |  `arn:aws:lambda:ap-northeast-3:194566237122:layer:LambdaInsightsExtension-Arm64:15`  | 
|  亚太地区（首尔） |  `arn:aws:lambda:ap-northeast-2:580247275435:layer:LambdaInsightsExtension-Arm64:17`  | 
|  亚太地区（新加坡） |  `arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension-Arm64:18`  | 
|  亚太地区（悉尼） |  `arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension-Arm64:18`  | 
|  亚太地区（东京） |  `arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension-Arm64:29`  | 
|  加拿大（中部） |  `arn:aws:lambda:ca-central-1:580247275435:layer:LambdaInsightsExtension-Arm64:16`  | 
|  欧洲地区（法兰克福） |  `arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension-Arm64:18`  | 
|  欧洲地区（爱尔兰） |  `arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension-Arm64:18`  | 
|  欧洲地区（伦敦） |  `arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension-Arm64:18`  | 
|  欧洲地区（米兰） |  `arn:aws:lambda:eu-south-1:339249233099:layer:LambdaInsightsExtension-Arm64:16`  | 
|  欧洲地区（巴黎） |  `arn:aws:lambda:eu-west-3:580247275435:layer:LambdaInsightsExtension-Arm64:16`  | 
|  欧洲（西班牙） |  `arn:aws:lambda:eu-south-2:352183217350:layer:LambdaInsightsExtension-Arm64:4`  | 
|  欧洲地区（斯德哥尔摩） |  `arn:aws:lambda:eu-north-1:580247275435:layer:LambdaInsightsExtension-Arm64:16`  | 
|  中东（巴林） |  `arn:aws:lambda:me-south-1:285320876703:layer:LambdaInsightsExtension-Arm64:16`  | 
|  南美洲（圣保罗） |  `arn:aws:lambda:sa-east-1:580247275435:layer:LambdaInsightsExtension-Arm64:16`  | 

## 1.0.275.0
<a name="Lambda-Insights-extension-ARM-1.0.275.0"></a>

版本 1.0.275.0 包含了对所有兼容的运行时的错误修复，以及对欧洲（西班牙）和亚太地区（海得拉巴）区域的支持。


| 区域 | ARN | 
| --- | --- | 
|  美国东部（弗吉尼亚州北部） |  `arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension-Arm64:16`  | 
|  美国东部（俄亥俄州） |  `arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension-Arm64:18`  | 
|  美国西部（北加利福尼亚） |  `arn:aws:lambda:us-west-1:580247275435:layer:LambdaInsightsExtension-Arm64:14`  | 
|  美国西部（俄勒冈州） |  `arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension-Arm64:16`  | 
|  非洲（开普敦） |  `arn:aws:lambda:af-south-1:012438385374:layer:LambdaInsightsExtension-Arm64:14`  | 
|  亚太地区（香港） |  `arn:aws:lambda:ap-east-1:519774774795:layer:LambdaInsightsExtension-Arm64:14`  | 
|  亚太地区（海得拉巴） |  `arn:aws:lambda:ap-south-2:891564319516:layer:LambdaInsightsExtension-Arm64:2`  | 
|  亚太地区（雅加达） |  `arn:aws:lambda:ap-southeast-3:439286490199:layer:LambdaInsightsExtension-Arm64:14`  | 
|  亚太地区（孟买） |  `arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension-Arm64:18`  | 
|  亚太地区（大阪） |  `arn:aws:lambda:ap-northeast-3:194566237122:layer:LambdaInsightsExtension-Arm64:13`  | 
|  亚太地区（首尔） |  `arn:aws:lambda:ap-northeast-2:580247275435:layer:LambdaInsightsExtension-Arm64:15`  | 
|  亚太地区（新加坡） |  `arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension-Arm64:16`  | 
|  亚太地区（悉尼） |  `arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension-Arm64:16`  | 
|  亚太地区（东京） |  `arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension-Arm64:27`  | 
|  加拿大（中部） |  `arn:aws:lambda:ca-central-1:580247275435:layer:LambdaInsightsExtension-Arm64:14`  | 
|  欧洲地区（法兰克福） |  `arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension-Arm64:16`  | 
|  欧洲地区（爱尔兰） |  `arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension-Arm64:16`  | 
|  欧洲地区（伦敦） |  `arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension-Arm64:16`  | 
|  欧洲地区（米兰） |  `arn:aws:lambda:eu-south-1:339249233099:layer:LambdaInsightsExtension-Arm64:14`  | 
|  欧洲地区（巴黎） |  `arn:aws:lambda:eu-west-3:580247275435:layer:LambdaInsightsExtension-Arm64:14`  | 
|  欧洲（西班牙） |  `arn:aws:lambda:eu-south-2:352183217350:layer:LambdaInsightsExtension-Arm64:2`  | 
|  欧洲地区（斯德哥尔摩） |  `arn:aws:lambda:eu-north-1:580247275435:layer:LambdaInsightsExtension-Arm64:14`  | 
|  中东（巴林） |  `arn:aws:lambda:me-south-1:285320876703:layer:LambdaInsightsExtension-Arm64:14`  | 
|  南美洲（圣保罗） |  `arn:aws:lambda:sa-east-1:580247275435:layer:LambdaInsightsExtension-Arm64:14`  | 

## 1.0.273.0
<a name="Lambda-Insights-extension-ARM-1.0.273.0"></a>

版本 1.0.273.0 包含了对所有兼容运行时系统的错误修复。


| 区域 | ARN | 
| --- | --- | 
|  美国东部（弗吉尼亚州北部） |  `arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension-Arm64:12`  | 
|  美国东部（俄亥俄州） |  `arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension-Arm64:14`  | 
|  美国西部（北加利福尼亚） |  `arn:aws:lambda:us-west-1:580247275435:layer:LambdaInsightsExtension-Arm64:9`  | 
|  美国西部（俄勒冈州） |  `arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension-Arm64:12`  | 
|  非洲（开普敦） |  `arn:aws:lambda:af-south-1:012438385374:layer:LambdaInsightsExtension-Arm64:9`  | 
|  亚太地区（香港） |  `arn:aws:lambda:ap-east-1:519774774795:layer:LambdaInsightsExtension-Arm64:9`  | 
|  亚太地区（雅加达） |  `arn:aws:lambda:ap-southeast-3:439286490199:layer:LambdaInsightsExtension-Arm64:9`  | 
|  亚太地区（孟买） |  `arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension-Arm64:14`  | 
|  亚太地区（大阪） |  `arn:aws:lambda:ap-northeast-3:194566237122:layer:LambdaInsightsExtension-Arm64:9`  | 
|  亚太地区（首尔） |  `arn:aws:lambda:ap-northeast-2:580247275435:layer:LambdaInsightsExtension-Arm64:11`  | 
|  亚太地区（新加坡） |  `arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension-Arm64:12`  | 
|  亚太地区（悉尼） |  `arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension-Arm64:12`  | 
|  亚太地区（东京） |  `arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension-Arm64:23`  | 
|  加拿大（中部） |  `arn:aws:lambda:ca-central-1:580247275435:layer:LambdaInsightsExtension-Arm64:10`  | 
|  欧洲地区（法兰克福） |  `arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension-Arm64:12`  | 
|  欧洲地区（爱尔兰） |  `arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension-Arm64:12`  | 
|  欧洲地区（伦敦） |  `arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension-Arm64:12`  | 
|  欧洲地区（米兰） |  `arn:aws:lambda:eu-south-1:339249233099:layer:LambdaInsightsExtension-Arm64:9`  | 
|  欧洲地区（巴黎） |  `arn:aws:lambda:eu-west-3:580247275435:layer:LambdaInsightsExtension-Arm64:10`  | 
|  欧洲地区（斯德哥尔摩） |  `arn:aws:lambda:eu-north-1:580247275435:layer:LambdaInsightsExtension-Arm64:10`  | 
|  中东（巴林） |  `arn:aws:lambda:me-south-1:285320876703:layer:LambdaInsightsExtension-Arm64:9`  | 
|  南美洲（圣保罗） |  `arn:aws:lambda:sa-east-1:580247275435:layer:LambdaInsightsExtension-Arm64:10`  | 

## 1.0.229.0
<a name="Lambda-Insights-extension-ARM-1.0.229.0"></a>

版本 1.0.229.0 包含了对所有兼容运行时系统的错误修复。此外还增加了对以下区域的支持：
+ 美国西部（北加利福尼亚）
+ 非洲（开普敦）
+ 亚太地区（香港）
+ 亚太地区（雅加达）
+ 亚太地区（大阪）
+ 亚太地区（首尔）
+ 加拿大（中部）
+ 欧洲地区（米兰）
+ 欧洲地区（巴黎）
+ 欧洲地区（斯德哥尔摩）
+ 中东（巴林）
+ 南美洲（圣保罗）


| 区域 | ARN | 
| --- | --- | 
|  美国东部（弗吉尼亚州北部） |  `arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension-Arm64:5`  | 
|  美国东部（俄亥俄州） |  `arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension-Arm64:7`  | 
|  美国西部（北加利福尼亚） |  `arn:aws:lambda:us-west-1:580247275435:layer:LambdaInsightsExtension-Arm64:3`  | 
|  美国西部（俄勒冈州） |  `arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension-Arm64:5`  | 
|  非洲（开普敦） |  `arn:aws:lambda:af-south-1:012438385374:layer:LambdaInsightsExtension-Arm64:2`  | 
|  亚太地区（香港） |  `arn:aws:lambda:ap-east-1:519774774795:layer:LambdaInsightsExtension-Arm64:2`  | 
|  亚太地区（雅加达） |  `arn:aws:lambda:ap-southeast-3:439286490199:layer:LambdaInsightsExtension-Arm64:2`  | 
|  亚太地区（孟买） |  `arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension-Arm64:7`  | 
|  亚太地区（大阪） |  `arn:aws:lambda:ap-northeast-3:194566237122:layer:LambdaInsightsExtension-Arm64:2`  | 
|  亚太地区（首尔） |  `arn:aws:lambda:ap-northeast-2:580247275435:layer:LambdaInsightsExtension-Arm64:4`  | 
|  亚太地区（新加坡） |  `arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension-Arm64:5`  | 
|  亚太地区（悉尼） |  `arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension-Arm64:5`  | 
|  亚太地区（东京） |  `arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension-Arm64:11`  | 
|  加拿大（中部） |  `arn:aws:lambda:ca-central-1:580247275435:layer:LambdaInsightsExtension-Arm64:3`  | 
|  欧洲地区（法兰克福） |  `arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension-Arm64:5`  | 
|  欧洲地区（爱尔兰） |  `arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension-Arm64:5`  | 
|  欧洲地区（伦敦） |  `arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension-Arm64:5`  | 
|  欧洲（西班牙） |  `arn:aws:lambda:eu-south-1:339249233099:layer:LambdaInsightsExtension-Arm64:2`  | 
|  欧洲地区（巴黎） |  `arn:aws:lambda:eu-west-3:580247275435:layer:LambdaInsightsExtension-Arm64:3`  | 
|  欧洲地区（斯德哥尔摩） |  `arn:aws:lambda:eu-north-1:580247275435:layer:LambdaInsightsExtension-Arm64:3`  | 
|  中东（巴林） |  `arn:aws:lambda:me-south-1:285320876703:layer:LambdaInsightsExtension-Arm64:2`  | 
|  南美洲（圣保罗） |  `arn:aws:lambda:sa-east-1:580247275435:layer:LambdaInsightsExtension-Arm64:3`  | 

## 1.0.135.0
<a name="Lambda-Insights-extension-ARM-1.0.135.0"></a>

版本 1.0.135.0 包含针对 Lambda Insights 如何收集以及报告磁盘和文件描述符使用情况的错误修复。在此扩展程序的早期版本中，`tmp_free` 指标报告了函数运行时 `/tmp` 目录中的最大可用空间。此版本将指标更改为报告最小值，从而使其在评估磁盘使用情况时更有实用意义。有关 `tmp` 目录存储配额的更多信息，请参阅 [Lambda 配额](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-limits.html)。

版本 1.0.135.0 现在还报告文件描述符使用情况（`fd_use` 和 `fd_max`）作为进程范围内的最大值，而不是报告操作系统级别。


| 区域 | ARN | 
| --- | --- | 
|  美国东部（弗吉尼亚州北部） |  `arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension-Arm64:2`  | 
|  美国东部（俄亥俄州） |  `arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension-Arm64:2`  | 
|  美国西部（俄勒冈州） |  `arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension-Arm64:2`  | 
|  亚太地区（孟买） |  `arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension-Arm64:2`  | 
|  亚太地区（新加坡） |  `arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension-Arm64:2`  | 
|  亚太地区（悉尼） |  `arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension-Arm64:2`  | 
|  亚太地区（东京） |  `arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension-Arm64:2`  | 
|  欧洲地区（法兰克福） |  `arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension-Arm64:2`  | 
|  欧洲地区（爱尔兰） |  `arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension-Arm64:2`  | 
|  欧洲地区（伦敦） |  `arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension-Arm64:2`  | 

## 1.0.119.0
<a name="Lambda-Insights-extension-ARM-1.0.119.0"></a>


| 区域 | ARN | 
| --- | --- | 
|  美国东部（弗吉尼亚州北部） |  `arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension-Arm64:1`  | 
|  美国东部（俄亥俄州） |  `arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension-Arm64:1`  | 
|  美国西部（俄勒冈州） |  `arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension-Arm64:1`  | 
|  亚太地区（孟买） |  `arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension-Arm64:1`  | 
|  亚太地区（新加坡） |  `arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension-Arm64:1`  | 
|  亚太地区（悉尼） |  `arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension-Arm64:1`  | 
|  亚太地区（东京） |  `arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension-Arm64:1`  | 
|  欧洲地区（法兰克福） |  `arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension-Arm64:1`  | 
|  欧洲地区（爱尔兰） |  `arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension-Arm64:1`  | 
|  欧洲地区（伦敦） |  `arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension-Arm64:1`  | 

# 使用控制台对现有 Lambda 函数启用 Lambda Insights
<a name="Lambda-Insights-Getting-Started-console"></a>

 按照以下步骤，在 Lambda 控制台中对现有 Lambda 函数启用 Lambda Insights。

**对 Lambda 函数启用 Lambda Insights**

1. 通过 [https://console.aws.amazon.com/lambda/](https://console.aws.amazon.com/lambda/) 打开 AWS Lambda 控制台。

1.  选择函数名称，然后选择以下屏幕中的 **Configuration**（配置）选项卡。

1.  在**配置**选项卡下，选择左侧导航菜单中的**监控和操作工具**，然后选择**编辑**。

    会将您定向到可以编辑监控工具的屏幕。

1. 在 **Lambda Insights 增强监控**旁，选择**编辑**。

1. 在 **CloudWatch Lambda Insights** 下，启用**增强监控**，然后选择**保存**。

# 使用 AWS CLI 对现有 Lambda 函数启用 Lambda Insights
<a name="Lambda-Insights-Getting-Started-cli"></a>

按照以下步骤操作，使用 AWS CLI 对现有 Lambda 函数启用 Lambda Insights。

**步骤 1：更新函数权限**

**更新函数权限**
+ 输入以下命令，将 **CloudWatchLambdaInsightsExecutionRolePolicy** 托管式 IAM 策略附加到函数的执行角色。

  ```
  aws iam attach-role-policy \
  --role-name function-execution-role \
  --policy-arn "arn:aws:iam::aws:policy/CloudWatchLambdaInsightsExecutionRolePolicy"
  ```

**步骤 2：安装 Lambda 扩展程序**

输入以下命令安装 Lambda 扩展程序。将 `layers` 参数的 ARN 值替换为与您的区域和您要使用的扩展程序版本匹配的 ARN。有关更多信息，请参阅 [Lambda Insights 扩展程序的可用版本](Lambda-Insights-extension-versions.md)。

```
aws lambda update-function-configuration \
   --function-name function-name \
   --layers "arn:aws:lambda:us-west-1:580247275435:layer:LambdaInsightsExtension:14"
```

**步骤 3：启用 CloudWatch Logs VPC 终端节点**

仅在函数运行于不具有 Internet 访问权限的私有子网中以及您尚未配置 CloudWatch Logs Virtual Private Cloud (VPC) 端点的情况下，才需要执行此步骤。

如果您需要执行此步骤，请输入以下命令，将占位符替换为 VPC 的信息。

有关更多信息，请参阅[将 CloudWatch Logs 与接口 VPC 终端节点结合使用](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/cloudwatch-logs-and-interface-VPC.html)。

```
aws ec2 create-vpc-endpoint \
--vpc-id vpcId \
--vpc-endpoint-type Interface \
--service-name com.amazonaws.region.logs \
--subnet-id subnetId 
--security-group-id securitygroupId
```

# 使用 AWS SAM CLI 对现有 Lambda 函数启用 Lambda Insights
<a name="Lambda-Insights-Getting-Started-SAM-CLI"></a>

按照以下步骤操作，使用 AWS SAM AWS CLI 对现有 Lambda 函数启用 Lambda Insights。

如果您尚未安装最新版本的 AWS SAM CLI，则必须先安装或升级到此版本。有关更多信息，请参阅[安装 AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)。

**步骤 1：安装层**

要使 Lambda Insights 扩展程序可用于所有 Lambda 函数，请使用 Lambda Insights 层的 ARN 向 SAM 模板的 `Globals` 部分添加一个 `Layers` 属性。下方示例所示为将该层用于 Lambda Insights 的初始版本。有关 Lambda Insights 扩展程序层的最新版本，请参阅 [Lambda Insights 扩展程序的可用版本](Lambda-Insights-extension-versions.md)。

```
Globals:
  Function:
    Layers:
      - !Sub "arn:aws:lambda:${AWS::Region}:580247275435:layer:LambdaInsightsExtension:14"
```

若要仅为单个函数启用此层，请向该函数添加 `Layers` 属性，如本示例所示。

```
Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      Layers:
        - !Sub "arn:aws:lambda:${AWS::Region}:580247275435:layer:LambdaInsightsExtension:14"
```

**步骤 2：添加托管式策略**

对每个函数均需添加 **CloudWatchLambdaInsightsExecutionRolePolicy** IAM 策略。

AWS SAM 不支持全局策略，因此您必须对每个函数单独启用这些策略，如本示例所示。有关全局策略的更多信息，请参阅[全局策略部分](https://github.com/aws/serverless-application-model/blob/master/docs/globals.rst)。

```
Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      Policies:
        - CloudWatchLambdaInsightsExecutionRolePolicy
```

**本地调用**

AWS SAM CLI 支持 Lambda 扩展程序。但每个在本地执行的调用都会重置运行时环境。由于运行时在未发生关闭事件的情况下重新启动，Lambda Insights 数据将无法从本地调用中获得。有关更多信息，请参阅[版本 1.6.0 - 添加对 AWS Lambda 扩展程序的本地测试支持](https://github.com/aws/aws-sam-cli/releases/tag/v1.6.0)。

**故障排除**

要排除 Lambda Insights 的安装问题，请将以下环境变量添加到 Lambda 函数中以启用调试日志记录。

```
Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      Environment:
        Variables:
          LAMBDA_INSIGHTS_LOG_LEVEL: info
```

# 使用 CloudFormation 对现有 Lambda 函数启用 Lambda Insights
<a name="Lambda-Insights-Getting-Started-cloudformation"></a>

按照以下步骤操作，使用 CloudFormation 对现有 Lambda 函数启用 Lambda Insights。

**步骤 1：安装层**

将 Lambda Insights 层添加到 Lambda Insights 层 ARN 中的 `Layers` 属性。下方示例所示为将该层用于 Lambda Insights 的初始版本。有关 Lambda Insights 扩展程序层的最新版本，请参阅 [Lambda Insights 扩展程序的可用版本](Lambda-Insights-extension-versions.md)。

```
Resources:
  MyFunction:
    Type: AWS::Lambda::Function
    Properties:
      Layers:
        - !Sub "arn:aws:lambda:${AWS::Region}:580247275435:layer:LambdaInsightsExtension:14"
```

**步骤 2：添加托管式策略**

将 **CloudWatchLambdaInsightsExecutionRolePolicy** IAM 策略添加到您的函数执行角色。

```
Resources:
  MyFunctionExecutionRole:
    Type: 'AWS::IAM::Role'
    Properties:
      ManagedPolicyArns:
        - 'arn:aws:iam::aws:policy/CloudWatchLambdaInsightsExecutionRolePolicy'
```

**步骤 3：（可选）添加 VPC 终端节点**

仅在函数运行于不具有 Internet 访问权限的私有子网中以及您尚未配置 CloudWatch Logs Virtual Private Cloud (VPC) 端点的情况下，才需要执行此步骤。有关更多信息，请参阅[将 CloudWatch Logs 与接口 VPC 终端节点结合使用](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/cloudwatch-logs-and-interface-VPC.html)。

```
Resources:
  CloudWatchLogsVpcPrivateEndpoint:
    Type: AWS::EC2::VPCEndpoint
    Properties:
      PrivateDnsEnabled: 'true'
      VpcEndpointType: Interface
      VpcId: !Ref: VPC
      ServiceName: !Sub com.amazonaws.${AWS::Region}.logs
      SecurityGroupIds:
        - !Ref InterfaceVpcEndpointSecurityGroup
      SubnetIds:
        - !Ref PublicSubnet01
        - !Ref PublicSubnet02
        - !Ref PublicSubnet03
```

# 使用 AWS CDK 对现有 Lambda 函数启用 Lambda Insights
<a name="Lambda-Insights-Getting-Started-clouddevelopmentkit"></a>

按照以下步骤操作，使用 AWS CDK 对现有 Lambda 函数启用 Lambda Insights。若要使用这些步骤，您必须已经使用 AWS CDK 来管理您的资源。

本部分的命令采用 TypeScript 语言。

首先，更新函数权限。

```
executionRole.addManagedPolicy(
 ManagedPolicy.fromAwsManagedPolicyName('CloudWatchLambdaInsightsExecutionRolePolicy')
);
```

接下来，在 Lambda 函数上安装扩展程序。将 `layerArn` 参数的 ARN 值替换为与您的区域和您要使用的扩展程序版本匹配的 ARN。有关更多信息，请参阅 [Lambda Insights 扩展程序的可用版本](Lambda-Insights-extension-versions.md)。

```
import lambda = require('@aws-cdk/aws-lambda');
const layerArn = 'arn:aws:lambda:us-west-1:580247275435:layer:LambdaInsightsExtension:14';
const layer = lambda.LayerVersion.fromLayerVersionArn(this, 'LayerFromArn', layerArn);
```

如有必要，请为 CloudWatch Logs 启用 Virtual Private Cloud (VPC) 端点。仅在函数运行于不具有 Internet 访问权限的私有子网中以及您尚未配置 CloudWatch Logs VPC 终端节点的情况下，才需要执行此步骤。

```
const cloudWatchLogsEndpoint = vpc.addInterfaceEndpoint('cwl-gateway', {
  service: InterfaceVpcEndpointAwsService.CLOUDWATCH_LOGS,
});

cloudWatchLogsEndpoint.connections.allowDefaultPortFromAnyIpv4();
```

# 使用无服务器框架对现有 Lambda 函数启用 Lambda Insights
<a name="Lambda-Insights-Getting-Started-serverless"></a>

按照以下步骤使用无服务器框架对现有 Lambda 函数启用 Lambda Insights。有关无服务器框架的更多信息，请访问 [serverless.com](https://www.serverless.com/)。

此启用方式是通过面向无服务器的 Lambda Insights 插件实现的。有关更多信息，请参阅 [serverless-plugin-lambda-insights](https://www.npmjs.com/package/serverless-plugin-lambda-insights)。

如果尚未安装最新版本的无服务器命令行界面，则必须先安装或升级到此版本。有关更多信息，请参阅[开始使用无服务器框架开源和 AWS](https://www.serverless.com/framework/docs/getting-started/)。

**使用无服务器框架对 Lambda 函数上启用 Lambda Insights**

1. 在无服务器目录中运行以下命令，为 Lambda Insights 安装无服务器插件：

   ```
   npm install --save-dev serverless-plugin-lambda-insights
   ```

1. 在 `serverless.yml` 文件中，将插件添加到 `plugins` 部分，如下所示：

   ```
   provider:
     name: aws
   plugins:
     - serverless-plugin-lambda-insights
   ```

1. 启用 Lambda Insights。
   + 您可以通过将以下属性添加到 serverless.yml 文件中，为每个函数单独启用 Lambda Insights

     ```
     functions:
       myLambdaFunction:
         handler: src/app/index.handler
         lambdaInsights: true #enables Lambda Insights for this function
     ```
   + 您可以通过在 `serverless.yml` 文件中添加以下自定义部分，为所有函数启用 Lambda Insights：

     ```
     custom:
       lambdaInsights:
         defaultLambdaInsights: true #enables Lambda Insights for all functions
     ```

1. 输入以下命令重新部署无服务器服务：

   ```
   serverless deploy
   ```

   此操作会重新部署所有函数，并为您指定的函数启用 Lambda Insights。它通过添加 Lambda Insights 层以及使用 `arn:aws:iam::aws:policy/CloudWatchLambdaInsightsExecutionRolePolicy` IAM 策略附加必要的权限来启用 Lambda Insights。

# 对 Lambda 容器映像部署启用 Lambda Insights
<a name="Lambda-Insights-Getting-Started-docker"></a>

要为部署为容器映像的 Lambda 函数启用 Lambda Insights，请在 Dockerfile 中添加相应的行。这些行会将 Lambda Insights 代理安装为容器镜像中的扩展程序。对于 x86-64 容器和 ARM64 容器，要添加的行是不同的。

**注意**  
Lambda 洞察代理仅在使用 Amazon Linux 2 和 Amazon Linux 2023 的 Lambda 运行时上受支持。

**Topics**
+ [x86-64 容器映像部署](#Lambda-Insights-Getting-Started-docker-x86-64)
+ [ARM64 容器映像部署](#Lambda-Insights-Getting-Started-docker-ARM64)

## x86-64 容器映像部署
<a name="Lambda-Insights-Getting-Started-docker-x86-64"></a>

对于在 x86-64 容器上运行并部署为容器映像的 Lambda 函数，要为其启用 Lambda Insights，请在 Dockerfile 中添加以下行。这些行会将 Lambda Insights 代理安装为容器镜像中的扩展程序。

```
RUN curl -O https://lambda-insights-extension.s3-ap-northeast-1.amazonaws.com/amazon_linux/lambda-insights-extension.rpm && \
    rpm -U lambda-insights-extension.rpm && \
    rm -f lambda-insights-extension.rpm
```

创建 Lambda 函数后，向函数的执行角色分配 **CloudWatchLambdaInsightsExecutionRolePolicy** IAM 策略，并对基于容器镜像的 Lambda 函数启用 Lambda Insights。

**注意**  
要使用较早版本的 Lambda Insights 扩展程序，请将先前命令中的 URL 替换为以下 URL：`https://lambda-insights-extension.s3-ap-northeast-1.amazonaws.com/amazon_linux/lambda-insights-extension.1.0.111.0.rpm`。有关更多信息，请参阅 [Lambda Insights 扩展程序的可用版本](Lambda-Insights-extension-versions.md)。

**验证 Linux 服务器上 Lambda Insights 代理软件包的签名**

1. 输入以下命令下载公有密钥。

   ```
   shell$ wget https://lambda-insights-extension.s3-ap-northeast-1.amazonaws.com/lambda-insights-extension.gpg
   ```

1. 输入以下命令将公有密钥导入到密钥环中。

   ```
   shell$ gpg --import lambda-insights-extension.gpg
   ```

   该输出值将类似于以下内容。记下 `key` 值，您将需要在下一步中使用该值。在此示例输出中，密钥值为 `848ABDC8`。

   ```
   gpg: key 848ABDC8: public key "Amazon Lambda Insights Extension" imported
   gpg: Total number processed: 1
   gpg: imported: 1  (RSA: 1)
   ```

1. 输入以下命令验证指纹。将 `key-value` 替换为上一步中的密钥值。

   ```
   shell$  gpg --fingerprint key-value
   ```

   此命令输出中的指纹字符串应为 `E0AF FA11 FFF3 5BD7 349E E222 479C 97A1 848A BDC8`。如果指纹字符串不匹配，请勿安装该代理，请联系 AWS。

1. 验证指纹后，您可以使用该指纹验证 Lambda Insights 代理软件包。输入以下命令下载软件包签名文件。

   ```
   shell$  wget https://lambda-insights-extension.s3-ap-northeast-1.amazonaws.com/amazon_linux/lambda-insights-extension.rpm.sig
   ```

1. 输入以下命令验证签名：

   ```
   shell$ gpg --verify lambda-insights-extension.rpm.sig lambda-insights-extension.rpm
   ```

   输出应与以下内容类似：

   ```
   gpg: Signature made Thu 08 Apr 2021 06:41:00 PM UTC using RSA key ID 848ABDC8
   gpg: Good signature from "Amazon Lambda Insights Extension"
   gpg: WARNING: This key is not certified with a trusted signature!
   gpg:          There is no indication that the signature belongs to the owner.
   Primary key fingerprint: E0AF FA11 FFF3 5BD7 349E  E222 479C 97A1 848A BDC8
   ```

   在预期输出中，可能会出现关于受信任签名的警告。只有当您或您信任的某个人对密钥进行了签名，密钥才是可信的。这并不意味着签名无效，只是您尚未验证公有密钥而已。

   如果输出中包含 `BAD signature`，请检查是否正确执行了以上步骤。如果您继续获得 `BAD signature` 响应，请与 AWS 联系，并避免使用所下载的文件。

### x86-64 示例
<a name="Lambda-Insights-Getting-Started-docker-example"></a>

本部分包括一个对基于容器镜像的 Python Lambda 函数启用 Lambda Insights 的示例。

**对 Lambda 容器镜像启用 Lambda Insights 的示例**

1. 创建一个类似于以下的 Dockerfile：

   ```
   FROM public.ecr.aws/lambda/python:3.8
   
   // extra lines to install the agent here
   RUN curl -O https://lambda-insights-extension.s3-ap-northeast-1.amazonaws.com/amazon_linux/lambda-insights-extension.rpm && \
       rpm -U lambda-insights-extension.rpm && \
       rm -f lambda-insights-extension.rpm
     
   COPY index.py ${LAMBDA_TASK_ROOT}
   CMD [ "index.handler" ]
   ```

1. 创建一个类似于以下内容的名为 `index.py` 的 Python 文件：

   ```
   def handler(event, context):
     return {
       'message': 'Hello World!'
     }
   ```

1. 将 Dockerfile 和 `index.py` 放在同一目录中。然后，在该目录中执行以下步骤来构建 Docker 镜像并将其上载到 Amazon ECR。

   ```
   // create an ECR repository
   aws ecr create-repository --repository-name test-repository
   // build the docker image
   docker build -t test-image .
   // sign in to AWS
   aws ecr get-login-password | docker login --username AWS --password-stdin "${ACCOUNT_ID}".dkr.ecr."${REGION}".amazonaws.com
   // tag the image
   docker tag test-image:latest "${ACCOUNT_ID}".dkr.ecr."${REGION}".amazonaws.com/test-repository:latest
   // push the image to ECR
   docker push "${ACCOUNT_ID}".dkr.ecr."${REGION}".amazonaws.com/test-repository:latest
   ```

1. 使用您刚刚创建的 Amazon ECR 镜像创建 Lambda 函数。

1.  将 **CloudWatchLambdaInsightsExecutionRolePolicy** IAM 策略分配给函数的执行角色。

## ARM64 容器映像部署
<a name="Lambda-Insights-Getting-Started-docker-ARM64"></a>

对于在 AL2\$1aarch64 容器（采用 ARM64 架构）上运行并部署为容器映像的 Lambda 函数，要为其启用 Lambda Insights，请在 Dockerfile 中添加以下行。这些行会将 Lambda Insights 代理安装为容器镜像中的扩展程序。

```
RUN curl -O https://lambda-insights-extension-arm64.s3-ap-northeast-1.amazonaws.com/amazon_linux/lambda-insights-extension-arm64.rpm && \
    rpm -U lambda-insights-extension-arm64.rpm && \
    rm -f lambda-insights-extension-arm64.rpm
```

创建 Lambda 函数后，向函数的执行角色分配 **CloudWatchLambdaInsightsExecutionRolePolicy** IAM 策略，并对基于容器镜像的 Lambda 函数启用 Lambda Insights。

**注意**  
要使用较早版本的 Lambda Insights 扩展程序，请将先前命令中的 URL 替换为以下 URL：`https://lambda-insights-extension-arm64.s3-ap-northeast-1.amazonaws.com/amazon_linux/lambda-insights-extension-arm64.1.0.229.0.rpm`。有关更多信息，请参阅 [Lambda Insights 扩展程序的可用版本](Lambda-Insights-extension-versions.md)。

**验证 Linux 服务器上 Lambda Insights 代理软件包的签名**

1. 输入以下命令下载公有密钥。

   ```
   shell$ wget https://lambda-insights-extension-arm64.s3-ap-northeast-1.amazonaws.com/lambda-insights-extension.gpg
   ```

1. 输入以下命令将公有密钥导入到密钥环中。

   ```
   shell$ gpg --import lambda-insights-extension.gpg
   ```

   该输出值将类似于以下内容。记下 `key` 值，您将需要在下一步中使用该值。在此示例输出中，密钥值为 `848ABDC8`。

   ```
   gpg: key 848ABDC8: public key "Amazon Lambda Insights Extension" imported
   gpg: Total number processed: 1
   gpg: imported: 1  (RSA: 1)
   ```

1. 输入以下命令验证指纹。将 `key-value` 替换为上一步中的密钥值。

   ```
   shell$  gpg --fingerprint key-value
   ```

   此命令输出中的指纹字符串应为 `E0AF FA11 FFF3 5BD7 349E E222 479C 97A1 848A BDC8`。如果指纹字符串不匹配，请勿安装该代理，请联系 AWS。

1. 验证指纹后，您可以使用该指纹验证 Lambda Insights 代理软件包。输入以下命令下载软件包签名文件。

   ```
   shell$  wget https://lambda-insights-extension-arm64.s3-ap-northeast-1.amazonaws.com/amazon_linux/lambda-insights-extension-arm64.rpm.sig
   ```

1. 输入以下命令验证签名：

   ```
   shell$ gpg --verify lambda-insights-extension-arm64.rpm.sig lambda-insights-extension-arm64.rpm
   ```

   输出应与以下内容类似：

   ```
   gpg: Signature made Thu 08 Apr 2021 06:41:00 PM UTC using RSA key ID 848ABDC8
   gpg: Good signature from "Amazon Lambda Insights Extension"
   gpg: WARNING: This key is not certified with a trusted signature!
   gpg:          There is no indication that the signature belongs to the owner.
   Primary key fingerprint: E0AF FA11 FFF3 5BD7 349E  E222 479C 97A1 848A BDC8
   ```

   在预期输出中，可能会出现关于受信任签名的警告。只有当您或您信任的某个人对密钥进行了签名，密钥才是可信的。这并不意味着签名无效，只是您尚未验证公有密钥而已。

   如果输出中包含 `BAD signature`，请检查是否正确执行了以上步骤。如果您继续获得 `BAD signature` 响应，请与 AWS 联系，并避免使用所下载的文件。

### ARM64 示例
<a name="Lambda-Insights-Getting-Started-docker-example-ARM64"></a>

本部分包括一个对基于容器镜像的 Python Lambda 函数启用 Lambda Insights 的示例。

**对 Lambda 容器镜像启用 Lambda Insights 的示例**

1. 创建一个类似于以下的 Dockerfile：

   ```
   FROM public.ecr.aws/lambda/python:3.8
   // extra lines to install the agent here
   RUN curl -O https://lambda-insights-extension-arm64.s3-ap-northeast-1.amazonaws.com/amazon_linux/lambda-insights-extension-arm64.rpm && \
       rpm -U lambda-insights-extension-arm64.rpm && \
       rm -f lambda-insights-extension-arm64.rpm
     
   COPY index.py ${LAMBDA_TASK_ROOT}
   CMD [ "index.handler" ]
   ```

1. 创建一个类似于以下内容的名为 `index.py` 的 Python 文件：

   ```
   def handler(event, context):
     return {
       'message': 'Hello World!'
     }
   ```

1. 将 Dockerfile 和 `index.py` 放在同一目录中。然后，在该目录中执行以下步骤来构建 Docker 镜像并将其上载到 Amazon ECR。

   ```
   // create an ECR repository
   aws ecr create-repository --repository-name test-repository
   // build the docker image
   docker build -t test-image .
   // sign in to AWS
   aws ecr get-login-password | docker login --username AWS --password-stdin "${ACCOUNT_ID}".dkr.ecr."${REGION}".amazonaws.com
   // tag the image
   docker tag test-image:latest "${ACCOUNT_ID}".dkr.ecr."${REGION}".amazonaws.com/test-repository:latest
   // push the image to ECR
   docker push "${ACCOUNT_ID}".dkr.ecr."${REGION}".amazonaws.com/test-repository:latest
   ```

1. 使用您刚刚创建的 Amazon ECR 镜像创建 Lambda 函数。

1.  将 **CloudWatchLambdaInsightsExecutionRolePolicy** IAM 策略分配给函数的执行角色。

# 更新函数的 Lambda Insights 扩展程序版本
<a name="Lambda-Insights-Update-Extension"></a>

作为最佳实践，建议您将 Lambda Insights 扩展程序更新到最新版本。本页中的主题说明如何操作。

**注意**  
本页说明如何更新已使用 Lambda Insights 的函数所使用的扩展程序版本。有关如何开始使用 Lambda Insights 的更多信息，请参阅 [开始使用 Lambda Insights](Lambda-Insights-Getting-Started.md)。

## 使用 Lambda 控制台更新 Lambda Insights 扩展程序版本
<a name="Lambda-Insights-Update-Extension-console"></a>

按照以下步骤，使用 Lambda 控制台更新 Lambda Insights 扩展程序版本。

**使用 Lambda 控制台更新**

1. 通过 [https://console.aws.amazon.com/lambda/](https://console.aws.amazon.com/lambda/) 打开 AWS Lambda 控制台。

1. 选择函数的名称。

1. 在**层**部分中，选择**编辑**。

1. 在层列表中，搜索 **LambdaInsightsExtension**，然后将层版本更改为 [Lambda Insights 扩展程序的可用版本](Lambda-Insights-extension-versions.md) 中列出的最新版本。

1. 选择**保存**。

## 使用 AWS CLI 更新 Lambda Insights 扩展程序版本
<a name="Lambda-Insights-Update-Extension-CLI"></a>

要使用 AWS CLI 更新 Lambda Insights 扩展程序版本，请输入以下命令。将 layers 参数的 ARN 值替换为与您的区域和您要使用的扩展程序版本匹配的 ARN。有关 Lambda Insights 扩展程序层最新版本的信息，请参阅 [Lambda Insights 扩展程序的可用版本](Lambda-Insights-extension-versions.md)。

```
aws lambda update-function-configuration \
--function-name function-name \
--layers "arn:aws:lambda:us-west-1:111122223333:layer:LambdaInsightsExtension:53"
```

## 使用 AWS SAM CLI 更新一个或多个函数的 Lambda Insights 扩展程序
<a name="Lambda-Insights-Update-Extension-SAM-CLI"></a>

要更新所有 Lambda 函数的 Lambda Insights 扩展程序版本，请使用 Lambda Insights 层的 ARN 更新 AWS Serverless Application Model（SAM）模板 `Globals` 部分中的 `Layers` 属性。有关 Lambda Insights 扩展程序层最新版本的信息，请参阅 [Lambda Insights 扩展程序的可用版本](Lambda-Insights-extension-versions.md)。

以下内容更新所有 Lambda 函数。

```
Globals:
  Function:
    Layers:
       - !Sub "arn:aws:lambda:${AWS::Region}:111122223333:layer:LambdaInsightsExtension:53"
```

以下内容仅更新一个函数。

```
Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      Layers:
        - !Sub "arn:aws:lambda:${AWS::Region}:111122223333:layer:LambdaInsightsExtension:53"
```

## 使用 CloudFormation 更新一个或多个函数的 Lambda Insights 扩展程序
<a name="Lambda-Insights-Update-Extension-CloudFormation"></a>

要使用 CloudFormation 更新 Lambda Insights 扩展程序版本，请更新函数 CloudFormation 资源内 `Layers` 属性中的扩展程序层，如以下示例所示。有关 Lambda Insights 扩展程序层最新版本的信息，请参阅 [Lambda Insights 扩展程序的可用版本](Lambda-Insights-extension-versions.md)。

```
Resources:
  MyFunction:
    Type: AWS::Lambda::Function
    Properties:
      Layers:
        - !Sub "arn:aws:lambda:${AWS::Region}:111122223333:layer:LambdaInsightsExtension:53"
```

## 使用 AWS CDK 更新一个或多个函数的 Lambda Insights 扩展程序
<a name="Lambda-Insights-Update-Extension-CDK"></a>

通过将 `layerArn` 参数的 ARN 值替换为与您的区域和您要使用的扩展程序版本匹配的 ARN，您可以更新 Lambda 函数的扩展程序版本。有关 Lambda Insights 扩展程序层最新版本的信息，请参阅 [Lambda Insights 扩展程序的可用版本](Lambda-Insights-extension-versions.md)。

```
import lambda = require('@aws-cdk/aws-lambda'); 
const layerArn = 'arn:aws:lambda:us-west-1:111122223333:layer:LambdaInsightsExtension:53'; 
const layer = lambda.LayerVersion.fromLayerVersionArn(this, 'LayerFromArn', layerArn);
```

## 使用无服务器框架更新一个或多个函数的 Lambda Insights 扩展程序
<a name="Lambda-Insights-Update-Extension-Serverless"></a>

按照以下步骤使用无服务器框架更新现有 Lambda 函数的 Lambda Insights 扩展程序版本。有关无服务器框架的更多信息，请参阅[无服务器框架文档](https://serverless.com)。

此方法使用无服务器的 Lambda Insights 插件。有关更多信息，请参阅 [serverless-plugin-lambda-insights](https://www.npmjs.com/package/serverless-plugin-lambda-insights)。

如果尚未安装最新版本的无服务器命令行界面，则必须先安装或升级到此版本。有关更多信息，请参阅 [Setting Up Serverless Framework With AWS](https://www.serverless.com/framework/docs/getting-started/)。

**使用 Lambda 控制台更新**

1. 更新 Lambda Insights。如果您尚未执行此操作，则请在文件末尾添加 `custom` 部分，并在 `lambdaInsightsVersion` 属性中指定 Lambda Insights 版本。

   ```
   custom:
       lambdaInsights:
           lambdaInsightsVersion: 53 #specify the Layer Version
   ```

1. 输入以下命令重新部署无服务器服务。

   ```
   serverless deploy
   ```

## 对 Lambda 容器映像部署更新 Lambda Insights 扩展程序版本
<a name="Lambda-Insights-Update-Extension-container"></a>

要更新 Lambda 容器映像的 Lambda Insights，请按照 [对 Lambda 容器映像部署启用 Lambda Insights](Lambda-Insights-Getting-Started-docker.md) 中的步骤使用最新版本的 Lambda Insights 重建映像。然后，使用 AWS CLI [更新函数代码](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/update-function-code.html)并提供容器映像 URI 作为 `--image-uri` 参数的值。

# 查看 Lambda Insights 指标
<a name="Lambda-Insights-view-metrics"></a>

在已调用的 Lambda 函数上安装 Lambda Insights 扩展程序后，您可以使用 CloudWatch 控制台查看您的指标。您可以查看关于多个函数的概览，或重点查看单个函数。您查看运行于托管实例的 Lambda 函数的指标。

有关 Lambda Insights 指标的列表，请参阅 [Lambda Insights 收集的指标](Lambda-Insights-metrics.md)。

**查看 Lambda Insights 指标的多个函数概览**

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 在导航窗格中，依次选择 **Insights**、**Lambda Insights**。

1. 在页面顶部的 **Lambda 洞察视图**下拉菜单中，选择**函数**选项。

1. 选择**多函数**。

   页面顶部显示的图形包含已启用 Lambda Insights 的区域中所有 Lambda 函数的汇总指标。页面下部是一个列出了函数的表格。

1. 要按函数名称进行筛选以减少所显示的函数数量，请在页面顶部附近的框中键入函数的部分名称。

1. 要将此视图作为小组件添加到控制面板，请选择 **Add to dashboard（添加到控制面板）**。

**查看单个函数的指标**

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 在导航窗格中，依次选择 **Insights**、**Lambda Insights**。

1. 在页面顶部的 **Lambda 洞察视图**下拉菜单中，选择**函数**选项。

1. 选择**单一函数**。

   页面顶部显示了图形和所选函数的指标。

1. 如果启用了 X-Ray，则可以选择单个跟踪 ID。此操作会打开该调用的“X-Ray 跟踪地图”页面，您可以在此处使用缩小操作，以查看分布式跟踪以及涉及处理该特定事务的其他服务。有关 X-Ray 跟踪地图的更多信息，请参阅 [Using the X-Ray Trace Map](https://docs.aws.amazon.com/xray/latest/devguide/xray-console-servicemap.html)。

1. 要打开 CloudWatch Logs Insights 并放大特定错误，请选择页面底部表格的 **View logs（查看日志）**。

1. 要将此视图作为小组件添加到控制面板，请选择 **Add to dashboard（添加到控制面板）**。

**查看在托管实例上运行的 Lambda 函数的指标**

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 在导航窗格中，依次选择 **Insights**、**Lambda Insights**。

1. 在页面顶部的 **Lambda 洞察视图**下拉菜单中，选择**托管实例函数**。

   页面将加载托管实例专属视图，并展示所有运行于托管实例的 Lambda 函数相关指标。

1. 在**视图**部分，为要查看的指标选择粒度：
   + **容量提供程序** – 展示容量提供程序层级的聚合指标。
   + **实例类型** – 展示实例类型层级的聚合指标。
   + **函数** – 展示单个函数层级的指标。页面顶部展示当前区域内所有启用 Lambda 洞察的 Lambda 函数的聚合指标图表。页面下部是一个列出了函数的表格。若需按函数名筛选，可在页面顶部的输入框中输入函数名的部分关键词。

1. 通过**筛选器**部分，按容量提供程序、实例类型或函数维度进行筛选。

1. 要将此视图作为小组件添加到控制面板，请选择 **Add to dashboard（添加到控制面板）**。

# 与 Application Insights 集成
<a name="lambda-insights-appinsights"></a>

Amazon CloudWatch Application Insights 可帮助您监控应用程序，并在应用程序资源和技术堆栈中指定和设置关键指标、日志和告警。有关更多信息，请参阅 [使用 CloudWatch Application Insights 检测常见应用程序问题](cloudwatch-application-insights.md)。

您可以启用 Application Insights，从 Lambda 函数中收集其他数据。如果您尚未启用此功能，可以通过在 Lambda Insights 控制面板中的性能视图下方，选择 **Application Insights** 中的 **Auto-configure Application Insights**（自动配置 Application Insights）来启用它。

如果您已设置 CloudWatch Application Insights 来监控 Lambda 函数，则 Application Insights 控制面板将显示在 **Application Insights** 选项卡中的 Lambda Insights 控制面板下方。

# Lambda Insights 收集的指标
<a name="Lambda-Insights-metrics"></a>

Lambda Insights 会从其安装位置的 Lambda 函数中收集多个指标。其中一些指标可作为 CloudWatch 指标中的时间序列聚合数据提供。其他指标不会聚合到时间序列数据中，但可以使用 CloudWatch Logs Insights 在嵌入式指标格式日志条目中找到。

**Topics**
+ [Lambda 函数](Lambda-Insights-metrics-lambda-functions.md)
+ [托管实例 Lambda 函数](Lambda-Insights-metrics-managed-instances.md)

# Lambda 函数
<a name="Lambda-Insights-metrics-lambda-functions"></a>

以下指标将以时间序列聚合数据的形式，在 CloudWatch Metrics 的 `LambdaInsights` 命名空间中向标准 Lambda 函数开放。


| 指标名称 | Dimensions | 说明 | 
| --- | --- | --- | 
|  `cpu_total_time` |  function\$1name function\$1name、版本  |  `cpu_system_time` 和 `cpu_user_time` 的总和。 单位：毫秒  | 
|  `init_duration` |  function\$1name function\$1name、版本  |  在 Lambda 执行环境生命周期的 `init` 阶段中花费的时间。 单位：毫秒  | 
|  `memory_utilization` |  function\$1name function\$1name、版本  |  最大内存（以分配给函数的内存的百分比表示）。 单位：百分比  | 
|  `used_memory_max` |  function\$1name function\$1name、版本  |  函数执行环境的测量内存。 单位：兆字节  | 
|  `rx_bytes` |  function\$1name function\$1name、版本  |  函数接收的字节数。 单位：字节  | 
|  `tmp_free` |  function\$1name function\$1name、版本  |  `/tmp` 目录中可用的空间量。 单位：字节  | 
|  `tmp_used` |  function\$1name function\$1name、版本  |  `/tmp` 目录中已使用的空间量。 单位：字节  | 
|  `tx_bytes` |  function\$1name function\$1name、版本  |  函数发送的字节数。 单位：字节  | 
|  `total_memory` |  function\$1name function\$1name、版本  |  分配给您的 Lambda 函数的内存量。此内存量与函数的内存大小相同。 单位：兆字节  | 
|  `total_network` |  function\$1name function\$1name、版本  |  `rx_bytes` 和 `tx_bytes` 的总和。由于 Lambda 运行时做出了网络调用，即使对于不执行输入/输出任务的函数，此值通常也大于零。 单位：字节  | 
|  `used_memory_max` |  function\$1name function\$1name、版本  |  函数沙盒的测量内存。 单位：兆字节  | 

以下指标可以使用 CloudWatch Logs Insights 在嵌入式指标格式日志条目中找到。有关 CloudWatch Logs Insights 的更多信息，请参阅[使用 CloudWatch Logs Insights 分析日志数据](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AnalyzingLogData.html)。

有关嵌入式指标格式的更多信息，请参阅[在日志中嵌入指标](CloudWatch_Embedded_Metric_Format.md)。


| 指标名称 | 说明 | 
| --- | --- | 
|  `agent_version` |  Lambda 函数上运行的 Lambda 洞察扩展代理当前版本。 单位：字符串  | 
|  `cpu_user_time` |  CPU 执行用户代码所花费的时间。 单位：毫秒  | 
|  `cpu_system_time` |  CPU 执行内核代码所花费的时间。 单位：毫秒  | 
|  `cpu_total_time` |  `cpu_system_time` 和 `cpu_user_time` 的总和。 单位：毫秒  | 
|  `fd_use` |  当前已使用的文件描述符数量。 单位：个  | 
|  `fd_max` |  可用的文件描述符最大数量。 单位：个  | 
|  `version` |  收集其他指标时对应的 Lambda 函数版本。 单位：个  | 
|  `agent_memory_max` |  Lambda 洞察扩展代理占用的最大内存。 单位：字节  | 
|  `agent_memory_avg` |  Lambda 洞察扩展代理占用的平均内存。 单位：字节  | 
|  `memory_utilization` |  以执行环境分配内存占比表示的平均内存利用率。 单位：百分比  | 
|  `used_memory_max` |  函数执行环境的测量内存。 单位：兆字节  | 
|  `rx_bytes` |  函数接收的字节数。 单位：字节  | 
|  `tx_bytes` |  函数发送的字节数。 单位：字节  | 
|  `threads_max` |  函数进程正在使用的线程数。作为函数作者，您无法控制运行时创建的线程的初始数量。 单位：个  | 
|  `tmp_used` |  `/tmp` 目录中已使用的空间量。 单位：字节  | 
|  `tmp_max` |  `/tmp` 目录中可用的空间量。 单位：字节  | 
|  `total_memory` |  分配给您的 Lambda 函数的内存量。此内存量与函数的内存大小相同。 单位：兆字节  | 
|  `total_network` |  `rx_bytes` 和 `tx_bytes` 的总和。由于 Lambda 运行时做出了网络调用，即使对于不执行输入/输出任务的函数，此值通常也大于零。 单位：字节  | 

# 托管实例 Lambda 函数
<a name="Lambda-Insights-metrics-managed-instances"></a>

以下指标将以时间序列聚合数据的形式，在 CloudWatch Metrics 的 `LambdaInsights` 命名空间中，向运行于托管实例的 Lambda 函数开放。


| 指标名称 | Dimensions | 说明 | 
| --- | --- | --- | 
|  `cpu_utilization` |  function\$1name function\$1name、版本  |  以执行环境分配的虚拟 CPU 占比表示的平均 CPU 利用率。 单位：百分比  | 
|  `cpu_utilization_max` |  function\$1name function\$1name、版本  |  以执行环境分配的虚拟 CPU 占比表示的最大 CPU 利用率。此指标采用 1 秒间隔采样。 单位：百分比  | 
|  `cpu_total_time` |  function\$1name function\$1name、版本  |  `cpu_system_time` 和 `cpu_user_time` 的总和。 单位：毫秒  | 
|  `memory_utilization` |  function\$1name function\$1name、版本  |  以执行环境分配内存占比表示的平均内存利用率。 单位：百分比  | 
|  `memory_utilization_max` |  function\$1name function\$1name、版本  |  以执行环境分配内存占比表示的最大内存利用率。此指标采用 50 毫秒间隔采样。 单位：百分比  | 
|  `used_memory_max` |  function\$1name function\$1name、版本  |  函数执行环境的测量内存。 单位：兆字节  | 
|  `rx_bytes` |  function\$1name function\$1name、版本  |  函数接收的字节数。 单位：字节  | 
|  `tmp_free` |  function\$1name function\$1name、版本  |  `/tmp` 目录中可用的空间量。 单位：字节  | 
|  `tmp_used` |  function\$1name function\$1name、版本  |  `/tmp` 目录中已使用的空间量。 单位：字节  | 
|  `tx_bytes` |  function\$1name function\$1name、版本  |  函数发送的字节数。 单位：字节  | 
|  `total_memory` |  function\$1name function\$1name、版本  |  分配给您的 Lambda 函数的内存量。此指标数值与函数配置的内存规格一致。 单位：兆字节  | 
|  `total_network` |  function\$1name function\$1name、版本  |  `rx_bytes` 和 `tx_bytes` 的总和。由于 Lambda 运行时做出了网络调用，即使对于不执行输入/输出任务的函数，此值通常也大于零。 单位：字节  | 
|  `used_memory_max` |  function\$1name function\$1name、版本  |  函数沙盒的测量内存。 单位：兆字节  | 

以下指标可以使用 CloudWatch Logs Insights 在嵌入式指标格式日志条目中找到。有关 CloudWatch Logs Insights 的更多信息，请参阅[使用 CloudWatch Logs Insights 分析日志数据](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AnalyzingLogData.html)。

有关嵌入式指标格式的更多信息，请参阅[在日志中嵌入指标](CloudWatch_Embedded_Metric_Format.md)。


| 指标名称 | 说明 | 
| --- | --- | 
|  `lambda_mode` |  标识此日志事件是否归属运行于 Lambda 托管实例的函数。若此字段出现在日志事件中，其仅能取一个值：`managed-instance`。此字段缺失，即表示对应函数为标准 Lambda 函数。 单位：字符串  | 
|  `agent_version` |  Lambda 函数上运行的 Lambda 洞察扩展代理当前版本。 单位：字符串  | 
|  `cpu_utilization` |  以执行环境分配的虚拟 CPU 占比表示的平均 CPU 利用率。 单位：百分比  | 
|  `cpu_utilization_max` |  以执行环境分配的虚拟 CPU 占比表示的最大 CPU 利用率。此指标采用 1 秒间隔采样。 单位：百分比  | 
|  `cpu_user_time` |  CPU 执行用户代码所花费的时间。 单位：毫秒  | 
|  `cpu_system_time` |  CPU 执行内核代码所花费的时间。 单位：毫秒  | 
|  `cpu_total_time` |  `cpu_system_time` 和 `cpu_user_time` 的总和。 单位：毫秒  | 
|  `fd_use` |  当前已使用的文件描述符数量。 单位：个  | 
|  `fd_max` |  可用的文件描述符最大数量。 单位：个  | 
|  `execution_environment_init` |  布尔值，标识是否为此函数新启动了执行环境。 单位：布尔值  | 
|  `version` |  收集其他指标时对应的 Lambda 函数版本。 单位：个  | 
|  `agent_memory_max` |  Lambda 洞察扩展代理占用的最大内存。 单位：字节  | 
|  `agent_memory_avg` |  Lambda 洞察扩展代理占用的平均内存。 单位：字节  | 
|  `memory_utilization` |  以执行环境分配内存占比表示的平均内存利用率。 单位：百分比  | 
|  `memory_utilization_max` |  以执行环境分配内存占比表示的最大内存利用率。此指标采用 50 毫秒间隔采样。 单位：百分比  | 
|  `used_memory_max` |  函数执行环境的测量内存。 单位：兆字节  | 
|  `rx_bytes` |  函数接收的字节数。 单位：字节  | 
|  `tx_bytes` |  函数发送的字节数。 单位：字节  | 
|  `threads_max` |  函数进程正在使用的线程数。作为函数作者，您无法控制运行时创建的线程的初始数量。 单位：个  | 
|  `tmp_free` |  `/tmp` 目录中可用的空间量。 单位：字节  | 
|  `tmp_used` |  `/tmp` 目录中已使用的空间量。 单位：字节  | 
|  `tmp_max` |  `/tmp` 目录中可用的空间量。 单位：字节  | 
|  `total_memory` |  分配给您的 Lambda 函数的内存量。此指标数值与函数配置的内存规格一致。 单位：兆字节  | 
|  `total_network` |  `rx_bytes` 和 `tx_bytes` 的总和。由于 Lambda 运行时做出了网络调用，即使对于不执行输入/输出任务的函数，此值通常也大于零。 单位：字节  | 

# CloudWatch Lambda Insights 的故障排除和已知问题
<a name="Lambda-Insights-Troubleshooting"></a>

对任何问题执行问题排查的第一步是在 Lambda Insights 扩展程序中启用调试日志记录。为此，请对 Lambda 函数设置以下环境变量：`LAMBDA_INSIGHTS_LOG_LEVEL=info`。有关更多信息，请参阅[使用 AWS Lambda 环境变量](https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html)。

Lambda Insights 扩展程序会将日志发送到与函数相同的日志组中 (`/aws/lambda/function-name)`。查看这些日志，看看错误是否可能与设置问题有关。

## 我没有看到 Lambda Insights 中的任何指标
<a name="Lambda-Insights-Troubleshooting-nometrics"></a>

如果您未看到预计可以看到的 Lambda Insights 指标，请检查以下可能性：
+ **指标可能只是存在延迟**：如果函数尚未被调用或数据尚未刷新，则您将看不到 CloudWatch 中的指标。有关更多信息，请参阅本部分后文的**已知问题**。
+ **确认 Lambda 函数具有正确的权限**：确保已将 **CloudWatchLambdaInsightsExecutionRolePolicy** IAM 策略分配给了函数的执行角色。
+ **检查 Lambda 运行时**：Lambda Insights 仅支持某些 Lambda 运行时。有关支持的运行时的列表，请参阅 [Lambda Insights](Lambda-Insights.md)。

  例如，要在 Java 8 上使用 Lambda Insights，您必须使用 `java8.al2` 运行时，而不能使用 `java8` 运行时。
+ **检查网络访问**：Lambda 函数可能使用的是不具有 Internet 访问权限的 VPC 私有子网，并且您没有为 CloudWatch Logs 配置 VPC 终端节点。为了帮助调试此问题，您可以设置环境变量 `LAMBDA_INSIGHTS_LOG_LEVEL=info`。

## 已知问题
<a name="Lambda-Insights-Troubleshooting-knownissues"></a>

数据延迟可能高达 20 分钟。当函数处理程序完成时，Lambda 会冻结沙盒，此操作也会冻结 Lambda Insights 扩展程序。当函数运行时，我们使用基于函数 TPS 的自适应批处理策略来输出数据。但是，如果长时间停止调用函数，并且缓冲区中仍有事件数据，则这些数据可能会被延迟到直到 Lambda 关闭空闲沙盒。当 Lambda 关闭沙盒时，我们会刷新缓冲的数据。

# CloudWatch Lambda Insights 中的示例遥测事件
<a name="Lambda-Insights-example-event"></a>

每次调用启用了 Lambda Insights 的 Lambda 函数，都会向 `/aws/lambda-insights` 日志组写入一个日志事件。每个日志事件都包含嵌入式指标格式的指标。有关嵌入式指标格式的更多信息，请参阅[在日志中嵌入指标](CloudWatch_Embedded_Metric_Format.md)。

您可以使用以下方法分析这些日志事件：
+ CloudWatch 控制台的 Lambda Insights 部分（见 [查看 Lambda Insights 指标](Lambda-Insights-view-metrics.md) 中的说明）。
+ 使用 CloudWatch Logs Insights 记录事件查询。有关更多信息，请参阅[使用 CloudWatch Logs Insights 分析日志数据](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AnalyzingLogData.html)。
+ `LambdaInsights` 命名空间中收集的指标，您可以通过使用 CloudWatch 指标来绘制这些指标的图形。

以下是嵌入式指标格式的 Lambda Insights 日志事件示例。

```
{
    "_aws": {
        "Timestamp": 1605034324256,
        "CloudWatchMetrics": [
            {
                "Namespace": "LambdaInsights",
                "Dimensions": [
                    [ "function_name" ],
                    [ "function_name", "version" ]
                ],
                "Metrics": [
                    { "Name": "memory_utilization", "Unit": "Percent" },
                    { "Name": "total_memory", "Unit": "Megabytes" },
                    { "Name": "used_memory_max", "Unit": "Megabytes" },
                    { "Name": "cpu_total_time", "Unit": "Milliseconds" },
                    { "Name": "tx_bytes", "Unit": "Bytes" },
                    { "Name": "rx_bytes", "Unit": "Bytes" },
                    { "Name": "total_network", "Unit": "Bytes" },
                    { "Name": "init_duration", "Unit": "Milliseconds" }
                ]
            }
        ],
        "LambdaInsights": {
            "ShareTelemetry": true
        }
    },
    "event_type": "performance",
    "function_name": "cpu-intensive",
    "version": "Blue",
    "request_id": "12345678-8bcc-42f7-b1de-123456789012",
    "trace_id": "1-5faae118-12345678901234567890",
    "duration": 45191,
    "billed_duration": 45200,
    "billed_mb_ms": 11571200,
    "cold_start": true,
    "init_duration": 130,
    "tmp_free": 538329088,
    "tmp_max": 551346176,
    "threads_max": 11,
    "used_memory_max": 63,
    "total_memory": 256,
    "memory_utilization": 24,
    "cpu_user_time": 6640,
    "cpu_system_time": 50,
    "cpu_total_time": 6690,
    "fd_use": 416,
    "fd_max": 32642,
    "tx_bytes": 4434,
    "rx_bytes": 6911,
    "timeout": true,
    "shutdown_reason": "Timeout",
    "total_network": 11345,
    "agent_version": "1.0.72.0",
    "agent_memory_avg": 10,
    "agent_memory_max": 10
}
```

以下为运行于 Lambda 托管实例的 Lambda 函数的 Lambda 洞察日志事件示例。

```
{
    "total_network": 16443,
    "tmp_free": 531492864,
    "total_memory": 2048,
    "fd_use": 85,
    "tmp_used": 11984896,
    "execution_environment_init": false,
    "version": "3",
    "event_type": "performance",
    "agent_memory_max": 6,
    "fd_max": 1024,
    "function_name": "cpu-intensive",
    "tx_bytes": 8404,
    "memory_utilization": 3,
    "used_memory_max": 73,
    "memory_utilization_max": 3,
    "cpu_system_time": 541,
    "threads_max": 49,
    "tmp_max": 543477760,
    "cpu_utilization_max": 2,
    "agent_memory_avg": 6,
    "cpu_total_time": 815,
    "rx_bytes": 8039,
    "lambda_mode": "managed-instance",
    "agent_version": "1.0.660.0",
    "_aws": {
        "CloudWatchMetrics": [
            {
                "Namespace": "LambdaInsights",
                "Dimensions": [
                    [
                        "function_name"
                    ],
                    [
                        "function_name",
                        "version"
                    ]
                ],
                "Metrics": [
                    {
                        "Name": "cpu_total_time",
                        "Unit": "Milliseconds"
                    },
                    {
                        "Name": "cpu_utilization",
                        "Unit": "Percent"
                    },
                    {
                        "Name": "cpu_utilization_max",
                        "Unit": "Percent"
                    },
                    {
                        "Name": "tx_bytes",
                        "Unit": "Bytes"
                    },
                    {
                        "Name": "rx_bytes",
                        "Unit": "Bytes"
                    },
                    {
                        "Name": "total_network",
                        "Unit": "Bytes"
                    },
                    {
                        "Name": "used_memory_max",
                        "Unit": "Megabytes"
                    },
                    {
                        "Name": "memory_utilization",
                        "Unit": "Percent"
                    },
                    {
                        "Name": "memory_utilization_max",
                        "Unit": "Percent"
                    },
                    {
                        "Name": "total_memory",
                        "Unit": "Megabytes"
                    },
                    {
                        "Name": "tmp_used",
                        "Unit": "Bytes"
                    },
                    {
                        "Name": "tmp_free",
                        "Unit": "Bytes"
                    }
                ]
            }
        ],
        "Timestamp": 1764164871353,
        "LambdaInsights": {
            "ShareTelemetry": true
        }
    },
    "cpu_utilization": 1,
    "cpu_user_time": 273
}
```

# CloudWatch Database Insights
<a name="Database-Insights"></a>

使用 CloudWatch 数据库洞察功能，可大规模监控以下数据库并排查其问题：Amazon Aurora MySQL、Amazon Aurora PostgreSQL、Amazon Aurora PostgreSQL Limitless、Amazon RDS for SQL Server、RDS for MySQL、RDS for PostgreSQL、RDS for Oracle 和 RDS for MariaDB。

借助 Database Insights，可以使用预先构建的自主控制面板来监控数据库实例集。为了便于分析实例集的性能，Database Insights 控制面板会显示精选的指标和可视化，您可以自定义这些控制面板。通过在单个控制面板中显示实例集中所有数据库的指标，Database Insights 可同时监控数据库。

例如，可以使用 Database Insights 在数百个数据库实例的实例集中查找性能不佳的数据库。然后，可以选择该实例并使用 Database Insights 来排查问题。

有关引擎、AWS 区域和实例类支持的信息，请参阅[支持数据库洞察的 Aurora 数据库引擎、区域和实例类](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_DatabaseInsights.Engines.html)和 [Amazon RDS DB engine, Region, and instance class support for Database Insights](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_DatabaseInsights.Engines.html)。

数据库洞察支持跨多账户、多区域监控工作负载。要了解有关数据库洞察跨账户跨区域监控的更多信息，请参阅[为 CloudWatch 数据库洞察配置跨账户跨区域监控](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Database-Insights-Cross-Account-Cross-Region.html)

要开始使用 Database Insights，请参阅以下主题。

**主题**
+ [开始使用 CloudWatch Database Insights](Database-Insights-Get-Started.md)
+ [查看 CloudWatch Database Insights 的实例集运行状况视图](Database-Insights-Fleet-Health-Dashboard.md)
+ [查看数据库实例控制面板以获取 CloudWatch Database Insights](Database-Insights-Database-Instance-Dashboard.md)
+ [CloudWatch Database Insights 问题排查](Database-Insights-Troubleshooting.md)

## Database Insights 模式
<a name="Database-Insights-modes"></a>

Database Insights 有“高级”模式和“标准”模式。“标准”模式是 Database Insights 的默认模式，可以为数据库开启“高级”模式。

下表显示了 CloudWatch 对 Database Insights 的“高级”模式和“标准”模式支持的功能。


| 功能 | 标准模式 | “高级”模式 | 
| --- | --- | --- | 
| 按维度分析数据库负载排名靠前的贡献者 | 支持 | 支持 | 
| 查询、绘制数据库指标图表并设置警报，最长可保留 7 天 | 支持 | 支持 | 
| 定义精细访问控制策略，限制对 SQL 文本等潜在敏感维度的访问 | 支持 | 支持 | 
| 使用每个正在运行的进程的详细指标，分析数据库中发生的操作系统进程 此功能需要启用 [Amazon RDS 增强监控](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_PerfInsights_Counters.html)才可使用。 | 不支持 | 支持 | 
| 定义并保存全实例集监控视图，实现数据库运行状况的规模化评估 | 不支持 | 支持 | 
| 分析具有 15 个月保留期和引导式用户体验的 SQL 锁定 | 不支持 | 仅支持 Aurora PostgreSQL | 
| 分析具有 15 个月保留期和引导式用户体验的 SQL 执行计划 | 不支持 | 仅支持 Aurora PostgreSQL、RDS for Oracle 和 RDS for SQL Server | 
| 可视化每个查询的统计数据 | 不支持 | 支持 | 
| 分析较慢的 SQL 查询此功能需要将数据库日志导出到 CloudWatch Logs 才可使用。 | 不支持 | 支持 | 
| 使用 CloudWatch Application Signals 查看调用服务 | 不支持 | 支持 | 
| 查看指标、日志、事件和应用程序等所有数据库遥测的整合控制面板要在数据库洞察控制台中查看数据库日志，需将数据库日志导出到 CloudWatch Logs。 | 不支持 | 支持 | 
| 将 Performance Insights 计数器指标自动导入 CloudWatch | 不支持 | 支持 | 
| 在 CloudWatch 中查看 Amazon RDS 事件 | 不支持 | 支持 | 
| 使用按需分析功能分析所选时间段内的数据库性能 | 不支持 | 支持 | 

**注意**  
数据库洞察功能的可用性因 AWS 区域而异，因为并非所有高级模式功能在所有区域都可用。

## 数据留存
<a name="Database-Insights-retention"></a>

Database Insights 的“高级”模式保留 Performance Insights 收集的 15 个月的指标。

如果为“标准”模式启用了 Performance Insights，Amazon RDS 将保留 7 天的 Performance Insights 计数器指标。

有关 Amazon RDS 性能详情计数器指标的更多信息，请参阅 [Performance Insights 计数器指标](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_PerfInsights_Counters.html)。

有关 Database Insights 收集的 CloudWatch 指标的保留期信息，请参阅以下主题。
+ 《Amazon Aurora 用户指南》中的 [Amazon Aurora 的 Amazon CloudWatch 指标](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.AuroraMonitoring.Metrics.html)**
+ 《Amazon RDS 用户指南》**中的 [Amazon Relational Database Service 的 Amazon CloudWatch 指标](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/rds-metrics.html)
+ 《Amazon Aurora User Guide》中的 [Amazon RDS 性能详情的 Amazon CloudWatch 指标](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_PerfInsights.Cloudwatch.html)**
+ 《Amazon Aurora User Guide》中的 [Amazon RDS 性能详情的 Amazon CloudWatch 指标](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_PerfInsights.Cloudwatch.html)**

## Database Insights 如何与 Performance Insights 集成
<a name="Database-Insights-pi"></a>

Performance Insights 是一项数据库性能监控服务。

Database Insights 基于 Performance Insights 构建，并扩展了其功能。Database Insights 增加了监控、分析和优化的功能。

要启用 Database Insights 的“高级”模式，必须启用 Performance Insights。

Database Insights 将 Performance Insights 计数器指标自动导入 CloudWatch。数据库洞察的高级模式会自动将数据库洞察收集的所有指标保留 15 个月，包括性能详情指标和 CloudWatch 指标。在实例中启用高级模式后，无需进一步配置，系统会自动执行此操作。有关 Performance Insights 计数器指标的更多信息，请参阅《Amazon Aurora User Guide》中的 [Performance Insights 计数器指标](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_PerfInsights_Counters.html)。**

## 定价
<a name="Database-Insights-pricing"></a>

有关定价的信息，请参阅 [Amazon CloudWatch 定价](https://aws.amazon.com/cloudwatch/pricing/)。

# 开始使用 CloudWatch Database Insights
<a name="Database-Insights-Get-Started"></a>

Amazon RDS 和 Aurora 数据库默认启用数据库洞察的标准模式。要开始使用 Database Insights 的高级模式，可以创建新数据库或修改数据库。

有关为 Amazon RDS 数据库启用数据库洞察的高级模式或标准模式的信息，请参阅以下主题。
+ 《Amazon RDS 用户指南》**中的 [Turning on the Advanced mode of Database Insights for Amazon RDS](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_DatabaseInsights.TurningOnAdvanced.html)
+ 《Amazon RDS 用户指南》**中的 [Turning on the Standard mode of Database Insights for Amazon RDS](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_DatabaseInsights.TurningOnStandard.html)
+ 《Amazon RDS 用户指南》**中的[为 Amazon RDS 创建数据库实例或多可用区数据库集群时开启或关闭 CloudWatch 数据库洞察](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_DatabaseInsights.TurnOnCreateDatabase.html)

有关为 Amazon Aurora 数据库启用 Database Insights 的高级模式或标准模式的信息，请参阅以下主题。
+ 《Amazon Aurora 用户指南》**中的[为 Amazon Aurora 启用 Database Insights 的高级模式](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_DatabaseInsights.TurningOnAdvanced.html)
+ 《Amazon Aurora 用户指南》**中的[为 Amazon Aurora 启用 Database Insights 的标准模式](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_DatabaseInsights.TurningOnStandard.html)

有关为 Aurora PostgreSQL Limitless 数据库启用数据库洞察的高级模式或标准模式的信息，请参阅以下主题。
+ 《Amazon Aurora 用户指南》**中的[为 Aurora PostgreSQL Limitless 数据库开启数据库洞察的高级模式](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/limitless-monitoring.cwdbi.advanced.html)
+ 《Amazon Aurora 用户指南》**中的[为 Aurora PostgreSQL Limitless 数据库开启数据库洞察的标准模式](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/limitless-monitoring.cwdbi.standard.html)

## Database Insights 所需的权限
<a name="w2aac26c13c31c17"></a>

使用 Database Insights 需要某些 IAM 权限。Database Insights 需要 CloudWatch、CloudWatch Logs、Amazon RDS 和 Amazon RDS 性能详情的权限。如果您拥有更广泛的权限，则可能不需要向您的用户或角色提供这些权限。

使用 Database Insights 需要以下 CloudWatch 权限。
+ `cloudwatch:BatchGetServiceLevelIndicatorReport`
+ `cloudwatch:DescribeAlarms`
+ `cloudwatch:GetDashboard`
+ `cloudwatch:GetMetricData`
+ `cloudwatch:ListMetrics`
+ `cloudwatch:PutDashboard`

使用 Database Insights 需要以下 CloudWatch Logs 权限。
+ `logs:DescribeLogGroups`
+ `logs:GetQueryResults`
+ `logs:StartQuery`
+ `logs:StopQuery`

使用 Database Insights 需要以下 Amazon RDS 权限。
+ `rds:DescribeDBClusters`
+ `rds:DescribeDBInstances`
+ `rds:DescribeEvents`
+ `rds:DescribeDBShardGroups`（如果正在监控 Aurora PostgreSQL Limitless 数据库）

使用 Database Insights 需要以下性能洞察权限。
+ `pi:ListAvailableResourceMetrics`
+ `pi:ListAvailableResourceDimensions`
+ `pi:DescribeDimensionKeys`
+ `pi:GetDimensionKeyDetails`
+ `pi:GetResourceMetrics`
+ `pi:ListPerformanceAnalysisReports`
+ `pi:GetResourceMetadata`
+ `pi:GetPerformanceAnalysisReport`
+ `pi:CreatePerformanceAnalysisReport`
+ `pi:DeletePerformanceAnalysisReport`
+ `pi:ListTagsForResource`
+ `pi:TagResource`
+ `pi:UntagResource`

以下示例策略包含对 Database Insights 的完全访问所需的权限。

### 实现完全访问权限的策略示例
<a name="Database-Insights-permissions-sample"></a>

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [{
    "Effect" : "Allow",
      "Action" : [
        "cloudwatch:BatchGetServiceLevelIndicatorReport",
        "cloudwatch:DescribeAlarms",
        "cloudwatch:GetMetricStatistics",
        "cloudwatch:GetMetricData",
        "cloudwatch:ListMetrics",
        "cloudwatch:PutDashboard"
      ],
      "Resource" : "*"
    },
    {
    "Effect" : "Allow",
      "Action" : [
        "logs:DescribeLogGroups",
        "logs:GetQueryResults",
        "logs:StartQuery",
        "logs:StopQuery"
      ],
      "Resource" : "*"
    },
    {
    "Effect" : "Allow",
      "Action" : [
        "pi:DescribeDimensionKeys",
        "pi:GetDimensionKeyDetails",
        "pi:GetResourceMetadata",
        "pi:GetResourceMetrics",
        "pi:ListAvailableResourceDimensions",
        "pi:ListAvailableResourceMetrics",
        "pi:CreatePerformanceAnalysisReport",
        "pi:GetPerformanceAnalysisReport",
        "pi:ListPerformanceAnalysisReports",
        "pi:DeletePerformanceAnalysisReport",
        "pi:TagResource",
        "pi:UntagResource",
        "pi:ListTagsForResource"
      ],
      "Resource" : "arn:aws:pi:*:*:*/rds/*"
    },
    {
    "Effect" : "Allow",
      "Action" : [
        "rds:DescribeDBInstances",
        "rds:DescribeDBClusters",
        "rds:DescribeEvents"
      ],
      "Resource" : "*"
    }
  ]
}
```

------

# 为 CloudWatch 数据库洞察设置跨账户跨区域监控
<a name="Database-Insights-Cross-Account-Cross-Region"></a>

 CloudWatch 数据库洞察可实现对数据库实例集的跨账户跨区域监控，为您的整个数据库 AWS 基础设施提供集中式可观测性。您还能通过单一的统一控制台，对跨多个 AWS 账户和区域的数据库开展监控、故障排查与性能优化操作。

**Topics**
+ [先决条件](#Database-Insights-Cross-Account-Cross-Region-Prereq)
+ [为数据库洞察跨账户访问配置监控账户与源账户](#Database-Insights-Cross-Account-Cross-Region-MonitoringSourceAccountSetup)
+ [为跨账户跨区域控制台配置数据库洞察](#Database-Insights-Cross-Account-Cross-Region-setup)
+ [使用数据库洞察跨账户跨区域控制面板](#Database-Insights-Cross-Account-Cross-Region-Using)

## 先决条件
<a name="Database-Insights-Cross-Account-Cross-Region-Prereq"></a>
+ 使用数据库洞察的跨账户跨区域功能，需先完成 **CloudWatch 跨账户可观测性**的配置，以及**跨账户跨区域 CloudWatch 控制台**的部署。请参阅以下说明，了解如何同时启用这两项功能。
+ 若已完成上述两项配置，仍需为数据库洞察配置额外的数据共享规则，才能使其在您的环境中实现跨账户跨区域运行。请参阅以下说明，确保已选择正确的数据共享配置。

## 为数据库洞察跨账户访问配置监控账户与源账户
<a name="Database-Insights-Cross-Account-Cross-Region-MonitoringSourceAccountSetup"></a>

1. 遵照 [CloudWatch 跨账户可观测性](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Unified-Cross-Account-Setup.html)中的分步指导进行操作。我们提供 CloudFormation 模板，支持通过基础设施即代码的方式完成部署。

1. 在**步骤 1：配置监控账户**环节，为使数据库洞察实现跨账户跨区域运行，您至少需要选择以下数据类型共享给监控账户：**日志**、**指标**、**跟踪**，以及**Application Signals – 服务、服务级别目标（SLO）**。

1. 您需要在计划启用数据库洞察跨账户跨区域功能的**所有区域**，执行上述配置流程。

## 为跨账户跨区域控制台配置数据库洞察
<a name="Database-Insights-Cross-Account-Cross-Region-setup"></a>

1. 遵照[跨账户跨区域 CloudWatch 控制台](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Cross-Account-Cross-Region.html)中的分步指导操作。

1. 在**步骤 5：权限配置**环节，您至少需要选择以下数据类型共享给监控账户：**包含 CloudWatch 自动控制面板**、**包含数据库洞察的只读访问权限**。此外，您也可选择**账户内所有资源的完全只读访问权限**，该选项将包含账户中所有可用的数据来源。

1.  CloudWatch 跨区域控制台为全局配置项，因此该步骤仅需执行一次，配置后即对所有区域生效。

## 使用数据库洞察跨账户跨区域控制面板
<a name="Database-Insights-Cross-Account-Cross-Region-Using"></a>

 完成数据库洞察跨账户跨部分功能的配置后，即可在左侧面板的**筛选器**部分（**数据库视图**正下方），启用“跨账户跨部分”模式。您会在页面左上角看到一个开关按钮，如下方截图所示。

![\[alt text not found\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/database-insights-enable-cross-account-toggle.png)


 “跨账户跨区域”模式启用后，控制台将新增筛选条件。您可通过这些筛选条件选择多个区域，并按 AWS 账户 ID/标签、数据库资源类型、数据库资源标符进行筛选。

 默认情况下，系统会选中当前区域及所有账户。若修改区域和账户的选择范围，实例集运行状况控制面板将自动更新，展示与所选区域、账户筛选条件匹配的资源。

 在实例集运行状况控制面板中，您可直接跳转到其他 AWS 账户/区域下数据库实例对应的数据库实例集控制面板。

 使用数据库洞察开展跨账户、跨区域监控时，有以下几点必须注意：
+  警报仅可在监控账户中创建。您可以基于源账户的指标配置警报，但警报的创建操作必须在监控账户中完成。
+  实例集监控视图仅可在监控账户中定义并保存。
+  数据库洞察实例控制面板中的自定义指标控制面板，仅可在监控账户中进行自定义配置。
+  同一时间，数据库洞察实例集运行状况控制面板中最多支持选择 3 个区域。
+  监控账户仅支持执行只读操作。这意味着您无法从监控账户中创建性能分析报告。
+  在实例集运行状况控制面板中启用“跨账户跨区域”模式后，将无法按 AWS 资源标签和资源属性进行筛选。

# 查看 CloudWatch Database Insights 的实例集运行状况视图
<a name="Database-Insights-Fleet-Health-Dashboard"></a>

您可以使用实例集运行状况控制面板查看数据库实例集的运行状况快照。

![\[实例集运行状况控制面板\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/dbi_fhd.png)


## 实例集运行状况视图
<a name="Database-Insights-fleet-views"></a>

Database Insights 中的*数据库实例集*是您要监控的一组数据库。您可以通过在**筛选条件**组件中选择筛选条件来为数据库实例集创建监控视图。此组件允许您对属性（例如集群或实例名称和标签）应用筛选条件。在实例集运行状况控制面板中，CloudWatch 会显示与实例集运行状况视图的至少一个筛选条件相匹配的数据库。

![\[按属性和标签筛选\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/dbi_filter.png)


要创建、修改或删除数据库实例集的视图，请使用以下主题中的过程。
+ [创建 CloudWatch Database Insights 的实例集运行状况视图](Database-Insights-fleet-views-create.md)
+ [编辑 CloudWatch Database Insights 的实例集运行状况视图](Database-Insights-fleet-views-edit.md)
+ [删除 CloudWatch Database Insights 的实例集运行状况视图](Database-Insights-fleet-views-delete.md)

## RDS 实例概述表
<a name="Database-Insights-instances"></a>

使用 **RDS 实例概览**表查看实例集中每个实例的警报状态、最大 DB 负载百分比和上次状态更新的时间。

![\[Amazon RDS 资源表\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/dbi_fhd-resources.png)


## 实例状态摘要
<a name="Database-Insights-Instances-State-Summary"></a>

使用**实例状态摘要**查看实例集中所有实例的运行状况。实例状态摘要提供了基于**警报**和 DB 负载指标的两个视图。默认情况下，CloudWatch 会显示**警报**视图。

![\[实例状态摘要\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/dbi_iss.png)


蜂窝中的每个节点都代表一个实例。有关实例的更多信息，您可以选择相应的节点，然后选择**按此实例筛选视图**。

![\[已选择实例状态摘要\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/dbi_iss-selected.png)


蜂窝组件汇总了实例集中实例的警报状态，每种状态下的节点数量位于蜂窝顶部。CloudWatch 显示蜂窝中显示的数据的最后一次刷新时间。

切换到 **DB 负载**视图时，您可以从 DB 负载指标的角度查看实例集的整体运行状况。数据库负载（DB 负载）衡量数据库中的活动会话数。DB 负载是 Database Insights 中的关键指标，每秒会收集一次。CloudWatch 会根据 DB 负载阈值将数据库实例分类为以下状态。
+ 高
+ 警告
+ 确定
+ Idle

您可以通过选择相应的状态图标来查看 DB 负载的阈值。

有关 Amazon RDS 数据库负载的信息，请参阅《Amazon RDS 用户指南》**中的[数据库负载](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_PerfInsights.Overview.ActiveSessions.html)。有关 Amazon Aurora 的 DB 负载的信息，请参阅《Amazon Aurora 用户指南》**中的[数据库负载](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_PerfInsights.Overview.ActiveSessions.html)。

默认情况下，CloudWatch 会显示数据库的平均 DB 负载。选择**最大值**可监控每个实例的最大 DB 负载。

从实例状态摘要中选择一个节点以显示该实例的警报和 DB 负载。

## “前 10 个实例”图表
<a name="Database-Insights-Top-Ten"></a>

使用**每个相对 DB 负载的前 10 个实例**图表查看 DB 负载最高的 10 个实例的 DB 负载随时间变化的趋势。该图表还提供了 DB 负载最高的实例的热门查询和热门等待事件。

![\[“按 DB 负载排序的前 10 个实例”图表\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/dbi_top10.png)


使用**每个指标的前 10 个实例**图表比较实例集中前 10 个实例的两个关键指标。您可以选择以下指标。
+ CPU 利用率（%）
+ 可用内存（%）
+ DB 连接（%）
+ 网络吞吐量
+ 读取 IOPS
+ 写入 IOPS
+ Read Latency (读取延迟)
+ Write Latency (写入延迟)

![\[“每个指标的前 10 个实例”图表\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/dbi_fhd-top10per.png)


## Amazon RDS 事件
<a name="Database-Insights-Events"></a>

使用**事件**摘要和表查看实例集中实例的 RDS 事件。

![\[事件摘要\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/dbi_events.png)


要查看**事件**表，请选择**详细信息**。

![\[事件详细信息\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/dbi_events-details.png)


有关 Amazon RDS 和 Amazon Aurora 的事件列表，请参阅以下主题。
+ 《Amazon Aurora 用户指南》**中的 [Aurora 的 Amazon RDS 事件类别和事件消息](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_Events.Messages.html)
+ 《Amazon RDS 用户指南》**中的 [Amazon RDS 事件类别和事件消息](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_Events.Messages.html)

## “调用服务”表
<a name="Database-Insights-Calling-Services"></a>

使用**呼叫服务**表查看正在调用您的数据库端点的 CloudWatch Application Signals 服务和相关的应用程序级指标，例如延迟或错误。

![\[“调用服务”表\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/dbi_fhd-calling.png)


Database Insights 会显示正在通过 DB 负载调用您的前 10 个实例的服务。要查看其他实例的调用服务，请在数据库实例控制面板中选择该实例。

如果应用程序调用的端点是 Aurora 集群，数据库洞察将在**调用服务**表中显示 Aurora 集群的写入器或读取器端点，而不是单个数据库实例。但是，如果应用程序调用的端点是 Amazon RDS 集群，数据库洞察会显示应用程序在 Amazon RDS 集群中调用的特定数据库实例。

有关 CloudWatch Application Signals 的更多信息，请参阅 [Application Signals](CloudWatch-Application-Monitoring-Sections.md)。

# 创建 CloudWatch Database Insights 的实例集运行状况视图
<a name="Database-Insights-fleet-views-create"></a>

要创建实例集运行状况视图，应使用以下过程。

**创建实例集运行状况视图**

1. 登录 AWS 管理控制台 并打开 CloudWatch 控制台，网址为 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/)。

1. 选择 **Insights**。

1. 选择 **Database Insights**。

1. 为要监控的数据库实例集选择筛选条件。

1. 选择**将筛选条件另存为实例集**。

1. 在**保存筛选条件集（实例集）**窗口中，输入实例集的名称。

1. 选择**保存**按钮。

要访问已保存的实例集，请选择**已保存实例集**下拉列表。然后，选择实例集。

# 编辑 CloudWatch Database Insights 的实例集运行状况视图
<a name="Database-Insights-fleet-views-edit"></a>

要编辑实例集运行状况试图，应使用以下过程。

**编辑实例集运行状况视图**

1. 登录 AWS 管理控制台 并打开 CloudWatch 控制台，网址为 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/)。

1. 选择 **Insights**。

1. 选择 **Database Insights**。

1. 选择**已保存的实例集**下拉列表。

1. 选择要编辑的实例集运行状况视图的垂直省略号。

1. 在**编辑筛选条件集（实例集）**窗口中，您可以编辑实例集的名称和实例集的筛选条件。

1. 选择**保存**按钮。

# 删除 CloudWatch Database Insights 的实例集运行状况视图
<a name="Database-Insights-fleet-views-delete"></a>

要删除实例集运行状况视图，应使用以下过程。

**删除实例集运行状况视图**

1. 登录 AWS 管理控制台 并打开 CloudWatch 控制台，网址为 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/)。

1. 选择 **Insights**。

1. 选择 **Database Insights**。

1. 选择**已保存的实例集**下拉列表。

1. 选择要删除的实例集运行状况视图的垂直省略号。

1. 在**删除筛选条件集（实例集）**窗口中，选择**删除**按钮。

# 查看数据库实例控制面板以获取 CloudWatch Database Insights
<a name="Database-Insights-Database-Instance-Dashboard"></a>

使用数据库实例控制面板查看 DB 实例运行状况的快照。

要分析 Amazon Aurora PostgreSQL 的锁定树和执行计划，请参阅以下主题。

**主题**
+ [使用 CloudWatch 数据库洞察分析 Amazon Aurora PostgreSQL 和 Amazon RDS for PostgreSQL 的锁定树](Database-Insights-Lock-Analysis.md)
+ [使用 CloudWatch 数据库洞察分析执行计划](Database-Insights-Execution-Plans.md)

## 数据库负载图表
<a name="Database-Insights-database-load"></a>

*数据库负载（DB 负载）*衡量数据库中的会话活动级别。DB 负载是 Database Insights 中的关键指标，而 Database Insights 每秒会收集一次 DB 负载。

![\[数据库实例控制面板\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/dbi_did.png)


要了解有关数据库负载的更多信息，请参阅《Amazon RDS 用户指南》**中的[数据库负载](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_PerfInsights.Overview.ActiveSessions.html) 或《Amazon Aurora 用户指南》**中的[数据库负载](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_PerfInsights.Overview.ActiveSessions.html)。

使用**数据库负载**图表，查看所有支持的数据库引擎按以下维度切片（分组）的数据库负载。
+ 阻止对象（仅适用于[支持锁定分析的数据库引擎](Database-Insights-Lock-Analysis.md)）
+ 阻止会话（仅适用于[支持锁定分析的数据库引擎](Database-Insights-Lock-Analysis.md)）
+ 阻止 SQL（仅适用于[支持锁定分析的数据库引擎](Database-Insights-Lock-Analysis.md)）
+ 数据库
+ 主机
+ SQL
+ 用户
+ 等待
+ 应用程序（仅适用于 Amazon Aurora PostgreSQL）
+ 计划（仅适用于[支持执行计划捕获的数据库引擎](Database-Insights-Execution-Plans.md)）
+ 会话类型（仅适用于 Amazon Aurora PostgreSQL）

**注意**  
有关分析 Amazon RDS 中 Oracle PDB 负载的信息，请参阅《Amazon RDS 用户指南》**中的[分析 Oracle 最大 PDB 负载](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_PerfInsights.UsingDashboard.AnalyzeDBLoad.TopPDB.html)。

![\[数据库实例控制面板中的 DB 负载\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/dbi_did-dbload.png)


默认情况下，CloudWatch 使用条形图显示 DB 负载。选择**线形图**，使用堆叠折线图显示 DB 负载。

![\[数据库实例控制面板中的 DB 负载的折线图\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/dbi_did-dbload-line.png)


## “DB 负载分析”选项卡
<a name="Database-Insights-DB-load-analysis"></a>

**DB 负载分析**选项卡可用于监控以下每个维度对 DB 负载的最大贡献者。
+ 数据库
+ 主机
+ SQL
+ 用户
+ 等待
+ 锁定分析（仅适用于[支持锁定分析的数据库引擎](Database-Insights-Lock-Analysis.md)）
+ 应用程序（仅适用于 Amazon Aurora PostgreSQL）
+ 会话类型（仅适用于 Amazon Aurora PostgreSQL）

![\[显示数据库负载分析选项卡的控制面板\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/dbi_lat.png)


## 分析查询的统计信息
<a name="Database-Insights-sql-stats"></a>

您可能需要分析 DB 负载较高的查询的统计信息。要分析查询的统计信息，请按以下过程操作。

**分析查询的统计信息**

1. 登录 AWS 管理控制台并打开 CloudWatch 控制台（[https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/)）。

1. 选择 **Insights**。

1. 选择 **Database Insights**。

1. 选择**数据库实例**视图。

1. 选择一个数据库实例。

1. 选择**主要 SQL** 选项卡。

1. 要查看查询的统计信息，请选择查询。  
![\[“主要 SQL”选项卡中显示的表。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/DBInsights_LoadTopSQL.png)

## “数据库遥测”选项卡
<a name="Database-Insights-database-telemetry"></a>

使用**数据库遥测**选项卡，查看所选实例的指标、日志、事件和慢速查询。

### 数据库遥测的指标部分
<a name="Database-Insights-metrics-tel"></a>

**指标**部分显示为每种引擎类型自定义的默认指标控制面板。

可通过向其添加操作系统指标、数据库计数器指标和 CloudWatch 指标来自定义此控制面板。还可以从控制面板中删除指标。您可以为账户中某个区域的每种引擎类型自定义一个控制面板。这意味着同一账户中该区域的特定引擎类型的所有实例都将具有相同的指标控制面板。

对您账户中的控制面板具有编辑权限的用户可以编辑任何引擎的控制面板。

您对控制面板所做的更改会自动保存，并应用于该区域和账户中数据库引擎的每个实例。

![\[显示不同类型数据库指标示例的控制面板。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/dbi_dbmetrics.png)


**要在“数据库遥测”选项卡中为引擎类型自定义控制面板**

1. 登录 AWS 管理控制台并打开 CloudWatch 控制台（[https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/)）。

1. 选择 **Insights**、**Database Insights**。

1. 对于**数据库视图**，选择**数据库实例**。

1. 在**筛选器**部分，找到并选择要查看其指标的数据库实例。

1. 选择**数据库遥测**选项卡，然后选择**指标**选项卡。

   此时将显示默认数据库实例控制面板。

1. 要向控制面板添加小组件，请执行以下操作：

   1. 选择**添加创建小组件**。

   1. 在**创建小组件**弹出窗口中，找到要添加的一个或多个指标，然后选中每个指标的复选框。如果您在此步骤中选择多个指标，则会全部显示在控制面板上同一个新建小组件中。然后选择**创建小组件**。

      记住，您对此控制面板所做的任何更改都将应用于账户中该区域内此引擎类型的所有 Database Insights 控制面板。

1. 要从控制面板中删除图表，请在小组件中选择垂直省略号，然后选择**删除**。

1. 要向控制面板中的现有小组件添加更多指标或更改其标题，请在小组件中选择垂直省略号，然后选择**编辑**。然后在**更新小组件**弹出窗口中，找到要添加的一个或多个指标，选中其复选框，然后选择**更新小组件**。您还可以更改小组件标题。

1. 自定义控制面板后，您可以选择**重置控制面板**将其重置为原始默认状态。

### 数据库遥测的日志部分
<a name="Database-Insights-logs-tel"></a>

**日志**部分提供为所选 DB 实例导出到 CloudWatch Logs 的数据库日志视图。

![\[数据库实例控制面板中的数据库遥测\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/dbi_did-telemetry-logs.png)


有关将日志发布到适用于 Amazon RDS 的 CloudWatch Logs 的信息，请参阅《Amazon RDS 用户指南》**中的[将数据库日志发布到 Amazon CloudWatch Logs](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_LogAccess.Procedural.UploadtoCloudWatch.html)。有关将日志发布到适用于 Amazon Aurora 的 CloudWatch Logs 的更多信息，请参阅**《Amazon Aurora 用户指南》中的[将数据库日志发布到 Amazon CloudWatch Logs](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_LogAccess.Procedural.UploadtoCloudWatch.html)。

对于 Aurora PostgreSQL Limitless 数据库，日志会自动发布到 CloudWatch Logs，并且可在数据库洞察控制台上找到。

### 数据库遥测操作系统进程数据
<a name="Database-Insights-OS-processes"></a>

您可以使用**数据库遥测**选项卡中的**操作系统进程**选项卡来查看数据库实例运行的操作系统（OS）的指标。这些指标提供给定时间戳内在数据库上运行的操作系统进程的快照以及关键指标，例如每个正在运行的进程的内存和 CPU 利用率。数据库洞察功能将这些指标与数据库负载图表中的指标相关联，因此，如果您在数据库负载图表中选择数据点，则操作系统进程数据会更新为显示来自同一时间戳的遥测数据。

选择数据点时，数据库洞察功能会自动选择要显示的时段，具体取决于您为整个页面选择的时间范围。您可以返回的最远时间取决于您为 `RDSOSMetrics` 日志组配置的保留时间。

如果未选择时间戳，则默认情况下，表中会填充最新时间戳的遥测数据。

**注意**  
只有在启用了 [Amazon RDS 增强监控](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_PerfInsights_Counters.html)的情况下才提供操作系统进程信息。增强监控会产生额外费用。有关更多信息，请参阅[增强监控的成本](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_Monitoring.OS.html#USER_Monitoring.OS.cost)。Aurora PostgreSQL Limitless 数据库会自动启用增强监控功能。

![\[事件表\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/dbinsights-osprocesses.png)


在**操作系统进程**视图中，显示每个进程的以下数据：
+ **进程 ID**：此进程的 ID。
+ **虚拟内存**：分配给进程的虚拟内存量（以 KB 为单位）。
+ **剩余地址**：进程正在使用的实际物理内存。
+ **CPU %**：显示进程正在使用的总 CPU 带宽的百分比。
+ **内存 %**：显示进程正在使用的总内存的百分比。
+ **虚拟机限制**：可以分配给进程的最大虚拟内存量。

  如果此列中的值为 0，则虚拟机限制不适用于该进程。

显示的监测数据是从 Amazon CloudWatch Logs 中检索的。您也可以直接从 CloudWatch Logs 中的日志流中检索这些指标。有关更多信息，请参阅[使用 CloudWatch Logs 查看操作系统指标](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_Monitoring.OS.CloudWatchLogs.html)。

以下情况下不会返回操作系统进程指标：
+ 数据库实例的失效转移。
+ 更改数据库实例的实例类（扩展计算）。

只有数据库引擎重启，因此将在重启数据库实例期间返回操作系统进程指标。仍会报告操作系统的指标。

### 数据库遥测的“慢速 SQL 查询”部分
<a name="Database-Insights-slow-sql-tel"></a>

要查看慢速 SQL 查询和查询模式，必须启用针对 CloudWatch Logs 的日志导出功能，并为数据库配置 DB 参数。

有关将 Amazon RDS 日志发布到 CloudWatch Logs 的信息，请参阅《Amazon RDS 用户指南》**中的[将数据库日志发布到 Amazon CloudWatch Logs](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_LogAccess.Procedural.UploadtoCloudWatch.html)。

有关将 Aurora 日志发布到 CloudWatch Logs 的信息，请参阅《Amazon Aurora 用户指南》**中的[将数据库日志发布到 Amazon CloudWatch Logs](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_LogAccess.Procedural.UploadtoCloudWatch.html)。

有关在 Amazon RDS 中配置数据库参数的信息，请参阅《Amazon RDS 用户指南》**中的[使用适用于 Amazon RDS 的数据库洞察配置您的数据库以监控慢速 SQL 查询](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_DatabaseInsights.SlowSQL.html)。

有关在 Amazon Aurora 中配置数据库参数的信息，请参阅《Amazon Aurora 用户指南》**中的[使用适用于 Amazon Aurora 的数据库洞察配置您的数据库以监控慢速 SQL 查询](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_DatabaseInsights.SlowSQL.html)。

**慢速 SQL 查询**部分提供了按频率排序的慢速查询模式列表。通过选择模式，您可以查看与所选模式匹配的慢速查询列表。您可以使用慢速查询列表来识别影响 DB 实例的慢速查询。

Database Insights 会显示慢速查询的统计信息。统计信息仅表示超过配置的慢速查询持续时间阈值的查询。

![\[显示有关慢 SQL 查询示例的详细信息\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/dbi_slowsql.png)


**重要**  
慢速查询可能包含敏感数据。使用 CloudWatch Logs 掩盖敏感数据。有关掩盖日志数据更多信息，请参阅《Amazon CloudWatch Logs User Guide》**中的 [Help protect sensitive log data with masking](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/mask-sensitive-log-data.html)。

### 事件表
<a name="Database-Insights-events-tel"></a>

使用**事件**表查看 DB 实例的 RDS 事件。有关 Amazon Aurora 的事件列表，请参阅《Amazon Aurora 用户指南》**中的 [Aurora 的 Amazon RDS 事件类别和事件消息](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_Events.Messages.html)。有关 Amazon Relational Database Service 的事件列表，请参阅《Amazon RDS 用户指南》**中的 [Aurora 的 Amazon RDS 事件类别和事件消息](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_Events.Messages.html)。

![\[事件表\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/dbi_did-events.png)


## “调用服务”选项卡
<a name="Database-Insights-calling"></a>

Database Insights 会显示正在调用您的实例的服务和操作。Database Insights 与 CloudWatch Application Signals 集成，为每项服务和操作提供指标，包括可用性、延迟、错误和数量。

如果应用程序调用的端点是 Aurora 集群，数据库洞察将在**调用服务**表中显示 Aurora 集群的写入器或读取器端点，而不是单个数据库实例。但是，如果应用程序调用的端点是 Amazon RDS 集群，数据库洞察会显示应用程序在 Amazon RDS 集群中调用的特定数据库实例。

![\[“调用服务”选项卡\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/dbi_did-calling.png)


## 使用 CloudWatch Database Insights 按需分析数据库性能
<a name="Database-Insights-On-demand-Analysis"></a>

借助 CloudWatch Database Insights，为您的 Amazon RDS 数据库按需分析 Amazon RDS 数据库的性能。

在**数据库负载**图表的右上角选择**分析性能**，即可执行按需性能分析。分析报告将针对选定的时间范围生成。使用**性能分析**选项卡查看实例集中数据库的性能分析报告。

![\[“性能分析”选项卡\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/dbi_dl-perfanalysis.png)


有关 Amazon Aurora 的性能分析报告的信息，请参阅《Amazon Aurora 用户指南》**中的[分析一段时间内的数据库性能](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_PerfInsights.UsingDashboard.AnalyzePerformanceTimePeriod.html)。

## 将 CloudWatch Database Insights 与 CloudWatch Application Signals 集成
<a name="Database-Insights-Integration-Application-Signals"></a>

将 CloudWatch Database Insights 与 CloudWatch Application Signals 集成。

使用**调用服务**选项卡查看调用了所选实例端点的 CloudWatch Application Signals 服务和操作。默认情况下，CloudWatch 按故障率对表进行排序。在**服务**、**操作**或**端点地址**列中选择值，在 CloudWatch Application Signals 控制台中查看相应的资源。

有关 CloudWatch Application Signals 支持的系统的更多信息，请参阅 [支持的系统](CloudWatch-Application-Signals-supportmatrix.md)。

# 使用 CloudWatch 数据库洞察分析 Amazon Aurora PostgreSQL 和 Amazon RDS for PostgreSQL 的锁定树
<a name="Database-Insights-Lock-Analysis"></a>

要解决由锁定引起的性能问题，您可以使用 CloudWatch 数据库洞察来分析 Amazon Aurora PostgreSQL 和 Amazon RDS for PostgreSQL 数据库的锁定树，方法如下。
+ **划分者**下拉列表：在**数据库负载**图表中选择**阻止对象**、**阻止会话**或**阻止 SQL** 维度，以查看排名靠前的各个拦截器在一段时间内对数据库负载的贡献。使用数据库负载图表，您可以分析排名靠前的拦截器是保持恒定还是经常变化。之后，您就可以对拦截器进行故障排除。  
![\[在切片方式下拉列表中选择了“阻止会话”的主要 SQL 表\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/DBInsights_TopSQLBlocking.png)
+ **锁定分析**选项卡 – 选择**数据库负载分析**，然后选择**锁定分析**选项卡以查看有关数据库中锁定争用的信息。  
![\[数据库负载控制面板中的锁定树表\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/DBInsights_LoadLockAnalysis.png)

**注意**  
CloudWatch 数据库洞察支持所有 Aurora PostgreSQL 版本的锁定分析。要分析锁定树，必须启用数据库洞察高级模式。有关如何开启高级模式的信息，请参阅[开启适用于 Amazon Aurora 的数据库洞察的高级模式](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_DatabaseInsights.TurningOnAdvanced.html)和 [Turning on the Advanced mode of Database Insights for Amazon Relational Database Service](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_DatabaseInsights.TurningOnAdvanced.html)

锁定分析选项卡提供有关数据库锁定争用的信息。锁定树可视化会显示来自不同会话的锁定请求之间的关系和依赖关系。

数据库洞察会每 15 秒捕获一次快照。快照显示的是数据库在某个时间点的锁定数据。

**注意**  
当 CloudWatch 检测到高锁定率时，CloudWatch 会在**锁定分析**选项卡中显示**检测到高锁定率**横幅。如果 CloudWatch 在连续 15 分钟内每隔 15 秒拍摄一次锁定快照，则表示 CloudWatch 检测到高锁定率。

锁定树中的每个节点代表一个特定的会话。父节点是阻止其子节点的会话。

要分析锁定树，请按照以下流程操作。

**分析锁定树的步骤**

1. 登录 AWS 管理控制台并打开 CloudWatch 控制台（[https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/)）。

1. 选择 **Insights**。

1. 选择 **Database Insights**。

1. 选择**数据库实例**视图。

1. 选择一个数据库实例。

1. 选择**数据库负载分析**选项卡。

1. 选择**锁定分析**选项卡。

   要查看数据库实例的锁定数据，请选择 1 天或更短的时间段。

1. 选择快照窗口。默认情况下，数据库洞察会选择受阻会话最多的快照窗口。  
![\[锁定分析表\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/dbi_lock-analysis.png)

1. 要查看快照的锁定数据，请选择数据库洞察功能拍摄快照的时间。

1. 要展开锁定树，请选择会话 ID 旁边的箭头。  
![\[锁定树已展开\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/dbi_lock-analysis-expand.png)

## 锁定快照数据
<a name="Database-Insights-Lock-Analysis-snapshot-data"></a>

数据库洞察功能可提供每个锁定请求的以下信息。要查看默认情况下未启用的列，请选择**锁定树**表格的**设置**图标并启用其他列。


| 列名称 | 定义  | 默认列 | 备注 | 
| --- | --- | --- | --- | 
|  `session_id`  | 会话唯一标识符。 |  是  | `session_id` 派生自 `HEX(pg_stat_activity.backend_start).HEX(pg_locks.pid)`。 | 
|  `pid`  | 此后端的 PID。 |  是  | `pg_locks.pid` | 
|  `blocked_sessions_count`  | 此锁定阻止的会话数。 |  是  | `blocked_sessions_count` 派生自此锁定阻止的会话 ID 的数量。 | 
|  `last_query_executed`  | 此会话执行的最后一个查询。对于拦截器来说，其可能不是保留了拦截锁定的查询。 |  是  | `pg_stat_activity.query` | 
|  `wait_event`  | 如果后端当前正在等待，则为等待事件名称，否则值为 NULL。 |  是  | `pg_stat_activity.wait_event` | 
|  `blocking_time_(In Seconds)`  | 自此锁定开始以来的时间（以秒为单位）。 |  是  | `blocking_time_(In Seconds)` 派生自第一个 Waiter 的等待事务的开始时间 (`pg_locks.waitstart`)。 | 
|  `blocking_mode`  | 由阻止会话保留的锁定模式。 |  否  | `pg_locks.mode` | 
|  `waiting_mode`  | 由等待会话请求的锁定模式。 |  否  | `pg_locks.mode` | 
|  `application`  | 连接到此后端的应用程序的名称。 |  否  | `pg_stat_activity.application_name` | 
|  `blocking_txn_start_time`  | 阻止事务的开始时间；如果没有处于活动状态的事务，则为 null。 |  否  | `pg_stat_activity.xact_start` | 
|  `waiting_start_time`  | 等待中的用户会话开始等待此锁定的时间；如果保留锁定，则为 null。 |  否  | `pg_locks.waitstart` | 
|  `session_start_time`  | 用户会话开始的时间。 |  否  | `pg_stat_activity.backend_start` | 
|  `state`  | 后端的状态。 |  否  | `pg_stat_activity.state` | 
|  `wait_event_type`  | 此会话正在等待的等待事件类型。 |  否  | `pg_stat_activity.wait_event_type` | 
|  `last_query_exec_time`  | 最后一次查询开始的时间。 |  否  | `pg_stat_activity.query_start` | 
|  `user`  | 登录到此后端的用户名称。 |  否  | `pg_stat_activity.usename` | 
|  `host`  | 已连接客户端的主机名，如 `client_addr` 反向 DNS 查找所报告。只有针对 IP 连接，并且仅在已启用 [log\$1hostname](https://www.postgresql.org/docs/current/runtime-config-logging.html#GUC-LOG-HOSTNAME) 时，此字段才会为非空。 |  否  | `pg_stat_activity.client_hostname` | 
|  `port`  | 客户端用于与此后端通信的 TCP 端口号；如果使用 Unix 套接字，则为 `-1`。如果此字段为 null，则表示这是一个内部服务器进程。 |  否  | `pg_stat_activity.client_port` | 
|  `client_address`  | 连接到此后端的客户端 IP 地址。如果此字段为 null，则表示客户端是通过服务器计算机上的 Unix 套接字连接的，或者表示这是内部进程，例如 autovacuum。 |  否  | `pg_stat_activity.client_addr` | 
|  `granted`  | 如果保留锁定，则该值为 true；如果等待锁定，则该值为 false。 |  否  | `pg_locks.granted` | 
|  `waiting_tuple`  |  页面内锁定所针对的元组编号；如果目标不是元组，则为 null。  |  否  | `pg_locks.tuple` | 
|  `waiting_page`  | 关系内锁定所针对的页码；如果目标不是关系页面或元组，则为 null。 |  否  | `pg_locks.page` | 
|  `waiting_transaction_id`  | 锁定所针对的事务 ID；如果目标不是事务 ID，则为 null。 |  否  | `pg_locks.transactionid` | 
|  `waiting_relation`  | 锁定所针对的关系 OID；如果目标不是关系或关系的一部分，则为 null。 |  否  | `pg_locks.relation` | 
|  `waiting_object_id`  | 锁定目标在其系统目录中的 OID；如果目标不是通用数据库对象，则为 null。 |  否  | `pg_locks.objid` | 
|  `waiting_database_id`  | 锁定目标所在数据库的 OID；如果目标是共享对象，则为零；如果目标是事务 ID，则为 null。 |  否  | `pg_locks.database` | 
|  `waiting_database_name`  | 锁定目标所在数据库的名称。 |  否  | `pg_stat_activity.datname` | 
|  `waiting_locktype`  | 可锁定对象的类型：relation、extend、frozenid、page、tuple、transactionid、virtualxid、spectoken、object、userlock、advisory 或 applytransaction。 |  否  | `pg_locks.locktype` | 
|  `is_fastpath`  | 如果使用快速路径获取锁定，则该值为 true；如果从主锁定表中获取，则该值为 false。 |  否  | `pg_locks.fastpath` | 

有关 `pg_stat_activity` 和 `pg_locks` 视图中值的更多信息，请参阅 PostgreSQL 文档中的以下主题。
+ [pg\$1locks](https://www.postgresql.org/docs/current/view-pg-locks.html)
+ [pg\$1stat\$1activity](https://www.postgresql.org/docs/current/monitoring-stats.html#MONITORING-PG-STAT-ACTIVITY-VIEW)

# 使用 CloudWatch 数据库洞察分析执行计划
<a name="Database-Insights-Execution-Plans"></a>

您可以使用以下方法来分析 Amazon Aurora PostgreSQL、RDS for Microsoft SQL Server 和 RDS for Oracle 数据库的执行计划。
+ **划分者**下拉列表：在**数据库负载**图表中选择**计划**维度，以查看不同计划在一段时间内对数据库负载的贡献。
+ **热门 SQL** 选项卡 – 选择**数据库负载分析**，然后选择**热门 SQL** 选项卡，以查看各摘要查询的计划数量。

  要分析摘要查询的执行计划，可选择该查询，然后选择**计划**选项卡。有关更多信息，请参阅以下步骤。

## 先决条件
<a name="Database-Insights-Execution-Plans-prereqs"></a>

要分析执行计划，必须使用数据库洞察的高级模式。有关如何开启高级模式的信息，请参阅[开启适用于 Amazon Aurora 的数据库洞察的高级模式](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_DatabaseInsights.TurningOnAdvanced.html)和 [Turning on the Advanced mode of Database Insights for Amazon Relational Database Service](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_DatabaseInsights.TurningOnAdvanced.html)。

如果您使用的是 Aurora PostgreSQL，则还需满足以下先决条件：
+ 您的数据库实例必须使用 Aurora PostgreSQL 版本 14.10、15.5 或更高版本。有关升级 Aurora PostgreSQL 数据库集群的信息，请参阅**《Amazon Aurora 用户指南》中的[升级 Amazon Aurora PostgreSQL 数据库集群](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_UpgradeDBInstance.PostgreSQL.html)。
+ 您必须使用以下选项之一，将参数 `aurora_compute_plan_id` 设置为 `on` 来配置数据库集群以分析执行计划。
  + **《Amazon Aurora 用户指南》中的[在 Amazon Aurora 中创建数据库集群参数组](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_WorkingWithParamGroups.CreatingCluster.html)
  + 《Amazon Aurora 用户指南》**中的[在 Amazon Aurora 中修改数据库集群参数组中的参数](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_WorkingWithParamGroups.ModifyingCluster.html)

## 分析执行计划
<a name="Database-Insights-Execution-Plans-analyze"></a>

要分析执行计划，请按以下流程操作。

**分析执行计划**

1. 登录 AWS 管理控制台并打开 CloudWatch 控制台（[https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/)）。

1. 选择 **Insights**。

1. 选择 **Database Insights**。

1. 选择**数据库实例**视图。

1. 选择一个数据库实例。

1. 选择 **Top SQL**（主要 SQL）选项卡。**计划数**列显示针对每个摘要查询收集的计划数。

1. （可选）如果未出现**计划数**列，请选择**主要 SQL** 表上的**设置**图标，以自定义列的可见性和顺序。  
![\[计划详细信息表设置\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/DBInsights2.png)

1. 选择一个摘要查询，将其扩展为其组件语句。  
![\[将查询扩展为其组件语句\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/dbi_did-dbload-expand.png)

1. 向下滚动并查看 SQL 文本。然后，选择**计划**选项卡。

   默认情况下，CloudWatch 会显示预计的执行计划。对于 Aurora PostgreSQL，要查看实际执行计划，请启用数据库实例的 `aurora_stat_plans.with_analyze` 参数。有关参数 `aurora_stat_plans.with_analyze` 的更多信息，请参阅《Amazon Aurora 用户指南》**中的[监控 Aurora PostgreSQL 的查询执行计划和峰值内存](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraPostgreSQL.Monitoring.Query.Plans.html#aurora.with_analyze)。

1. 要比较来自同一摘要查询的计划，请从**摘要计划查询**列表中选择两个**计划**。

   您可以一次查看一个或两个查询计划。在以下示例屏幕截图中，两个计划都适用于 Aurora PostgreSQL。  
![\[比较计划\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/dbi_did-plans.png)

1. 您还可以通过在“数据库负载”图表的**切片方式**下拉列表中选择**计划**，查看随着时间的推移每个计划对数据库负载的贡献情况。  
![\[Database load chart showing active sessions over time with plans contribution highlighted.\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/DBInsights_OverTime.png)

# 使用数据库洞察监控 Aurora Limitless 数据库
<a name="database-insights-limitless"></a>

数据库洞察服务支持在实例集级别和实例级别监控 [Aurora PostgreSQL Limitless 数据库](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_DatabaseInsights.Engines.html)。数据库实例控制面板和实例集运行状况控制面板中都会显示 Aurora PostgreSQL Limitless 数据库。

Aurora PostgreSQL Limitless 数据库使用*分片组*。每个分片组由多个数据库实例组成，这些实例协同工作以处理分布式工作负载。数据库洞察功能有助于您了解分片组内实例之间的负载分布情况。

在实例集运行状况控制面板中，数据库洞察服务可对 Limitless 分片组以及构成数据库实例集的其余数据进行统一监控。用户可获取 Limitless 分片组的运行状况及数据库负载利用率的综合视图，方式与查看实例集中其他数据库类似。在实例控制面板中，数据库洞察服务提供分片组级别和组内单个实例级别的监控。数据库洞察服务按分片组提供新的视图，支持在其中查看分片组中各实例间的数据库负载分布情况。通过该控制面板，可导航到分片组内的特定实例控制面板。

## Aurora Limitless 的可用功能
<a name="database-insights-limitless-features"></a>

下表列出了 Aurora PostgreSQL Limitless 数据库的可用功能。表中标注了各项功能在标准监控模式和高级监控模式下是否受支持，是否在分片组级别和/或实例级别可用，以及是否在数据库洞察服务的实例集/实例控制面板中可用。


| 功能 | 标准 | 高级 | ShardGroup | 实例 | 数据库洞察控制面板 | 
| --- | --- | --- | --- | --- | --- | 
| 按维度分析数据库负载排名靠前的贡献者 | 支持 | 支持 | 支持 | 是 | 实例 | 
| 查询、绘制数据库指标图表并设置警报，最长可保留 7 天 | 支持 | 支持 | 支持 | 是 | 实例 | 
| 定义精细访问控制策略，限制对 SQL 文本等潜在敏感维度的访问 | 支持 | 支持 | 支持 | 是 | 实例 | 
| 使用“负载分布情况”组件分析同一分片组内实例间的负载分布情况 | 支持 | 支持 | 是 | 否 | 实例 | 
|  使用每个正在运行的进程的详细指标，分析数据库中发生的操作系统进程 此功能需要启用 [Amazon RDS 增强监控](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_PerfInsights_Counters.html)才可使用。  | 不支持 | 支持 | 否 | 是 | 实例 | 
| 创建并保存实例集范围的监控视图，评测数百个数据库的运行状况 | 不支持 | 支持 | 是 | 否 | Fleet | 
| 分析具有 15 个月保留期和引导式用户体验的 SQL 锁定 | 不支持 | 不支持 | 否 | 否 | 实例 | 
| 分析具有 15 个月保留期和引导式用户体验的 SQL 执行计划 | 不支持 | 不支持 | 否 | 否 | 实例 | 
| 可视化每个查询的统计数据 | 不支持 | 支持 | 否 | 是 | 实例 | 
| 分析较慢的 SQL 查询 此功能需要将数据库日志导出到 CloudWatch Logs 才可使用。 | 不支持 | 支持 | 否 | 是 | 实例 | 
| 使用 CloudWatch Application Signals 查看调用服务 | 不支持 | 支持 | 是 | 否 | 二者 | 
| 查看指标、日志、事件和应用程序等所有数据库遥测的整合控制面板要在数据库洞察控制台中查看数据库日志，需将数据库日志导出到 CloudWatch Logs。 | 不支持 | 支持 | 否 | 是 | 实例 | 
| 将 Performance Insights 计数器指标自动导入 CloudWatch | 不支持 | 支持 | 不适用 | 不适用 | 实例 | 
| 在 CloudWatch 中查看 Amazon RDS 事件 | 不支持 | 支持 | 是 | 否 | 二者 | 
| 使用按需分析功能分析所选时间段内的数据库性能 | 不支持 | 不支持 | 否 | 否 | 实例 | 

**注意**  
Aurora PostgreSQL Limitless 数据库会自动启用增强监控功能。增强监控会产生额外费用。有关更多信息，请参阅[增强监控的成本](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_Monitoring.OS.html#USER_Monitoring.OS.cost)。  
对于 Aurora PostgreSQL Limitless 数据库，日志会自动发布到 CloudWatch Logs，并且可在数据库洞察控制台上找到。此操作会产生额外费用，具体遵循标准 CloudWatch Logs 定价规则。有关 CloudWatch Logs 及数据库洞察服务的定价方式和定价示例的详细信息，请参阅 [Amazon CloudWatch 定价](https://aws.amazon.com/cloudwatch/pricing/?nc1=h_ls)。

## 在实例集运行状况控制面板中监控 Aurora Limitless 分片组
<a name="database-insights-limitless-fleet"></a>

 数据库洞察服务支持在实例集运行状况控制面板中监控 Aurora Limitless 分片组。

该视图中会显示 Limitless 分片组以及构成数据库实例集的其他数据库。实例集运行状况控制面板为 Limitless 分片组提供运行状况与数据库负载利用率的综合视图，其信息呈现方式与实例集中其他数据库的信息展示方式类似。

![\[数据库洞察服务的实例集运行状况控制面板。主面板显示一个代表数据库实例的六边形网格，其中特别标注了代表“shardgroup2”的实例，并展示了路由器和分片的数据库负载利用率。右上区域显示了随时间变化的“数据库负载利用率排名前十实例”趋势图。下方区域显示了 db-microsoftsqlserver-enterprise-1-dbi-advanced 的详细信息，包括高频查询与等待事件。底部区域没有显示任何关键事件，也没有调用服务。左侧边栏显示总共有 44 个实例，其中 2 个处于警报状态，数据库负载利用率平均值为 25.1%。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/dbi_fhd.png)


 在实例集运行状况控制面板中查看 Aurora Limitless 数据库时：
+ 只会显示分片组，不显示单个实例
+ 分片组信息显示在以下小组件中：
  + 蜂窝图
  + 数据库负载排名前十列表
  + Events
  + 服务调用
  + 表格列表
+ 同时提供路由器和分片的数据库负载利用率数据

通过此实例集级别视图可监控 Aurora Limitless 分片组的性能并将其与实例集中的其他数据库进行比较，从而获得整个数据库实例集的综合运行状况概览。

![\[显示了数据库实例列表的数据库洞察控制面板。该表格显示了 7 个实例的详细信息，包括数据库标识符、警报状态、引擎类型、数据库负载利用率、上次状态更新时间及数据库版本。引擎类型包括 PostgreSQL、SQL Server Enterprise、Oracle Standard、Aurora MySQL 和 Aurora PostgreSQL。SQL Server 实例的负载率最高，为 25.21%。两个 Aurora PostgreSQL 实例被标记为“Limitless”，并分别显示分片和路由器的利用率数据。该界面包含用于筛选、排序及查看其他详细信息的选项。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/dbi_fhd-limitless-list-view.png)


## 在实例控制面板中监控 Aurora PostgreSQL Limitless 数据库
<a name="database-insights-limitless-monitor"></a>

数据库洞察功能在 Aurora PostgreSQL Limitless 数据库上的工作原理与在标准 Aurora 数据库集群上的工作原理类似。但是，您可以在分片组级别跟踪 Aurora PostgreSQL Limitless Database 的指标。要跟踪的两个主要指标如下：
+ **数据库负载**：衡量数据库中的活动级别。关键指标是 `DBLoad`，每秒收集一次。`DBLoad` 指标的单位是平均活动会话数（AAS）。为了获取平均活动会话数，数据库洞察功能会对同时运行查询的会话数进行采样。平均活动会话数等于会话总数除以特定时间段内的样本总数。
+ **最大 CPU**：数据库可用的最大计算能力。要查看活动会话是否超过最大 CPU，请查看它们与 `Max vCPU` 线的关系。`Max vCPU` 值由数据库实例的 vCPU（虚拟 CPU）内核数决定。

您还可以将 `DBLoad` 指标按维度进行“切片”分析，这些维度即为该指标的子类别。最有用的维度如下：
+ **高负载实例**：按降序显示实例（分片和路由器）的相对数据库负载。
+ **等待事件**：会导致 SQL 语句等待特定事件发生，然后才能继续运行。等待事件显示工作受阻的位置。
+ **主要 SQL**：显示哪些查询造成的数据库负载最大。

![\[显示了数据库性能指标的数据库洞察控制面板。顶部区域显示的折线图追踪了 7 月 14 日 12:00 至 14:45 期间的数据库活动情况。下方的“数据库负载分析”选项卡显示“高负载实例”视图，其中列出了 4 个数据库实例（DTR-3-757、DTR-2-903、DAS-4-112 和 DAS-5-992）及各自的负载利用率指标，所有实例的数值均低于 0.01 AAS（平均活动会话数）。该界面包含警报状态、筛选条件和各种分析视图的选项。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/dbi_limitless-top-instances.png)


## 使用数据库洞察功能分析 Aurora PostgreSQL Limitless 数据库的数据库负载
<a name="database-insights-limitless-dbload"></a>

借助数据库洞察功能，您可以在分片组级别和实例级别跟踪 Aurora PostgreSQL Limitless 数据库的指标。在分析 Aurora PostgreSQL Limitless Database 的数据库负载时，您可能需要将每个分片和路由器的数据库负载与最大 vCPU 进行比较。

绝对视图显示平均活动会话（AAS）数和预计 vCPU 数。相对视图显示 AAS 与预计 vCPU 的比率。

![\[显示了 shardgroup1 Aurora PostgreSQL 集群的数据库负载分布情况的数据库洞察控制面板。该界面显示了平均活动会话数（AAS）的时间序列图，以及展示 5 个数据库实例间负载分布情况的饼状图。饼状图显示 AAS 总数为 261 个，以及 DTR-2-103、DTR-3-650、DAS-4-659、DAS-5-784 和 DAS-6-336 分别所占的 AAS 数量和百分比。控制面板包含筛选条件、警报状态和数据库遥测选项。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/dbi_limitless-doughnut.png)


### 使用数据库洞察控制面板分析相对数据库负载
<a name="analyzing-relative-db-load"></a>

您可能需要通过跟踪相对数据库负载来提高 Aurora PostgreSQL Limitless Database 的性能。要按实例分析 Aurora PostgreSQL Limitless Database 的相对数据库负载，请执行以下步骤。

**使用控制台分析相对数据库负载**

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 在导航窗格中，选择“数据库洞察”。

1. 选择 Aurora PostgreSQL Limitless Database。此时会显示该 Aurora PostgreSQL Limitless 数据库的数据库洞察控制面板。

1. 在数据库负载（DB 负载）部分，选择*实例*作为*切片依据*。要查看 Aurora PostgreSQL Limitless Database 中所有实例的平均活动会话数（AAS）与 vCPU 内核数的比率，请为*查看方式*选择*相对*。

   平均活动会话图表显示了 Aurora PostgreSQL Limitless 数据库中实例的数据库负载。

1. 要查看高负载实例，请选择*高负载实例*选项卡。

1. （可选）要分析 Aurora PostgreSQL Limitless Database 中实例的数据库负载，请在*实例*列中选择实例名称。

### 使用数据库洞察控制面板分析数据库负载
<a name="analyzing-db-load-waits"></a>

您可能需要通过跟踪等待事件来提高 Aurora PostgreSQL Limitless Database 的性能。要按等待事件分析 Aurora PostgreSQL Limitless Database 的数据库负载，请使用以下步骤。

**使用控制台按等待状态分析 Aurora PostgreSQL Limitless Database 的数据库负载**

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 在导航窗格中，选择“数据库洞察”。

1. 选择 Aurora PostgreSQL Limitless Database。此时会显示该 Aurora PostgreSQL Limitless 数据库的数据库洞察控制面板。

1. 在数据库负载（DB 负载）部分，选择*等待*作为*切片依据*。要查看 AAS 和预计 vCPU 的数量，请为*查看方式*选择*绝对*。

   平均活动会话图表显示了您的 Aurora PostgreSQL Limitless Database 中实例的数据库负载。

1. 向下滚动至*主要 SQL* 选项卡。

1. 选择 SQL 语句，以将其扩展到其组件语句中。

### 使用数据库洞察控制面板分析负载分布情况
<a name="analyzing-db-load-distribution"></a>

您可能需要在 Aurora PostgreSQL Limitless Database 上平衡实例的负载分配。要分析 Aurora PostgreSQL Limitless Database 上实例的负载分配，请使用以下步骤。

**使用控制台分析 Aurora PostgreSQL Limitless Database 上实例的负载分配**

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 在导航窗格中，选择“数据库洞察”。

1. 选择 Aurora PostgreSQL Limitless Database。此时会显示该 Aurora PostgreSQL Limitless 数据库的数据库洞察控制面板。

1. 在数据库负载（DB 负载）部分，选择*实例*作为*切片依据*。要查看 Aurora PostgreSQL Limitless Database 中所有实例的 AAS 和预计 vCPU 的数量，请为*查看方式*选择*绝对*。

   平均活动会话图表显示了您的 Aurora PostgreSQL Limitless Database 中实例的数据库负载。

1. 要查看 Aurora PostgreSQL Limitless Database 中实例的负载分配图表，请选择*负载分配*选项卡。

# CloudWatch Database Insights 问题排查
<a name="Database-Insights-Troubleshooting"></a>

使用以下信息排查 CloudWatch Database Insights 的问题。

## 为 Amazon RDS 资源应用标签
<a name="Database-Insights-Troubleshooting-tags"></a>

要对数据库应用标签，应使用 Amazon RDS API、AWS CLI 或 Amazon RDS 控制台。有关更多信息，请参阅以下主题。
+ 《Amazon RDS API 参考》**中的 [AddTagsToResource](https://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_AddTagsToResource.html)
+ 《Amazon RDS Command Line Reference》**中的 [add-tags-to-resource](https://docs.aws.amazon.com/cli/latest/reference/rds/add-tags-to-resource.html)
+ 《Amazon Aurora 用户指南》**中的 [Tagging Amazon Aurora and Amazon RDS resources](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_Tagging.html)

## 实例集的最大 DB 实例数
<a name="Database-Insights-Troubleshooting-fleet-limit"></a>

在一个数据库实例集中，您无法监控超过 500 个 DB 实例。您可以使用筛选条件创建包含少于 500 个 DB 实例的实例集运行状况视图。

# 使用 Contributor Insights 分析高基数数据
<a name="ContributorInsights"></a>

您可以使用 Contributor Insights 分析日志数据，并创建显示贡献者数据的时间序列。您可以查看有关前 N 个贡献者、独特贡献者总数及其使用情况的指标。这有助于您找到排名靠前的说话者，并了解影响系统性能的人员或内容。例如，您可以查找无效主机，确定最多的网络用户或查找产生最多错误的 URL。

您可以从 Scratch 构建规则，并且在使用 AWS 管理控制台 时，还可以使用 AWS 已创建的示例规则。规则定义要用于定义贡献者的日志字段，例如 `IpAddress`。还可以筛选日志数据来查找和分析各个贡献者的行为。

CloudWatch 还提供了内置规则，可用于分析来自其他 AWS 服务的指标。

所有规则都将实时分析传入数据。

如果您登录的账户在 CloudWatch 跨账户可观测性中设置为监控账户，则您可以在该监控账户中创建 Contributor Insights 规则，以分析源账户和该监控账户中的日志组。您还可以创建单个规则来分析多个账户中的日志组。有关更多信息，请参阅 [CloudWatch 跨账户可观测性](CloudWatch-Unified-Cross-Account.md)。

使用 Contributor Insights，需要为每个与规则匹配的日志事件付费。有关更多信息，请参阅 [Amazon CloudWatch 定价](https://aws.amazon.com/cloudwatch/pricing/)。

**注意**  
只有当规则引用的数字值介于 -1e9 和 1e9 之间时，Contributor Insights 才会匹配日志条目。如果日志条目中的值超出此范围，Contributor Insights 会跳过该日志条目。

**Topics**
+ [在 CloudWatch 中创建 Contributor Insights 规则](ContributorInsights-CreateRule.md)
+ [CloudWatch 中的 Contributor Insights 规则语法](ContributorInsights-RuleSyntax.md)
+ [CloudWatch Contributor Insights 规则示例](ContributorInsights-Rule-Examples.md)
+ [在 CloudWatch 中查看 Contributor Insights 报告](ContributorInsights-ViewReports.md)
+ [绘制 CloudWatch 中规则生成的指标的图表](ContributorInsights-GraphReportData.md)
+ [在 CloudWatch 中使用 Contributor Insights 内置规则](ContributorInsights-BuiltInRules.md)

# 在 CloudWatch 中创建 Contributor Insights 规则
<a name="ContributorInsights-CreateRule"></a>

您可创建规则以分析日志数据。可以评估任何采用 JSON 或常用日志格式 (CLF) 的日志。这包括遵循这些格式之一的自定义日志以及来自 AWS 服务的日志，例如 Amazon VPC 流日志、Amazon Route 53 DNS 查询日志、Amazon ECS 容器日志以及来自 AWS CloudTrail、Amazon SageMaker AI、Amazon RDS、AWS AppSync 和 API Gateway 的日志。

在规则中指定字段名称或值时，所有匹配都区分大小写。

在创建规则时，您可以使用内置示例规则，也可以从 Scratch 创建自己的规则。Contributor Insights 包括以下日志类型的示例规则：
+ Amazon API Gateway 日志
+ Amazon Route 53 公有 DNS 查询日志
+ Amazon Route 53 resolver 查询日志
+ CloudWatch Container Insights 日志
+ VPC 流日志

如果您登录的账户在 CloudWatch 跨账户可观测性中设置为监控账户，则除了为该监控账户中的日志组创建规则外，您可以为与该监控账户关联的源账户中的日志组创建 Contributor Insights 规则。您还可以设置单个规则来监控不同账户中的日志组。有关更多信息，请参阅 [CloudWatch 跨账户可观测性](CloudWatch-Unified-Cross-Account.md)。

**重要**  
当您向用户授予 `cloudwatch:PutInsightRule` 权限时，默认情况下，该用户可以创建一个规则来评估 CloudWatch Logs 中的任何日志组。您可以添加 IAM 策略条件，以限制用户的这些权限，使其包含和排除特定的日志组。有关更多信息，请参阅 [使用条件键限制 Contributor Insights 用户对日志组的访问](iam-cw-condition-keys-contributor.md)。

**要使用内置示例规则创建规则，请执行以下操作：**

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 在导航窗格中，选择**日志**、**Contributor Insights**。

1. 选择 **Create rule**（创建规则）。

   

1.  对于 **Select log group(s)**（选择日志组），请选择您希望您的规则监控的日志组。您可以选择多达 20 个日志组。如果您登录的账户是为 CloudWatch 跨账户可观测性设置的监控账户，则可以选择源账户中的日志组，也可以设置单个规则来分析不同账户中的日志组。

   1.  （可选）要选择名称以特定字符串开头的所有日志组，请选择 **Select by prefix match**（按前缀匹配选择）下拉菜单，然后输入前缀。如果这是监控账户，则可以选择要在其中进行搜索的账户，否则将选择所有账户。
**注意**  
 您需要为与您的规则匹配的每个日志事件支付费用。如果您选择 **Select by prefix match**（按前缀匹配选择）下拉菜单，请注意前缀可以匹配多少个日志组。如果您搜索了超出预期数量的日志组，可能会产生意外费用。有关更多信息，请参阅 [Amazon CloudWatch 定价](https://aws.amazon.com/cloudwatch/pricing)。

1. 对于 **Rule type**（规则类型），选择 **Sample rule**（示例规则）。然后选择 **Select sample rule**（选择示例规则），并选择相应的规则。

1. 对于**日志格式**，请选择规则会评估的日志格式。

1. 对于**转换器**，请选择**启用转换器 Contributor Insights**，以便在经 [CloudWatch Logs 日志转换](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CloudWatch-Logs-Transformation.html.html)处理后，让规则对日志事件进行评估。如果选择启用此功能：
   + 如果规则会评估任何具有转换器的日志组，则该规则将应用于日志的转换版本。
   + 如果该规则会评估任何没有转换器的日志组，则该规则将应用于日志的原始版本。

   如果不选择此选项，则将对所有日志组中的原始日志事件进行评估，包括经日志转换功能转换的日志事件。
**注意**  
如果日志组具有转换器且某些日志事件转换失败，Contributor Insights 则不会评估这些日志事件。有关调查日志转换失败的信息，请参阅 [Transformation metrics and errors](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Transformation-Errors-Metrics.html)。

1.  所选示例规则已填写**日志格式**、**贡献**、**筛选条件**和**聚合**字段。您可以根据需要对这些值进行调整。

1. 选择**下一步**。

1. 为 **Rule name (规则名称)** 输入一个名称。有效字符包括 A-Z、a-z、0-9、（连字符）、（下划线）和（半角句点）。

1. 选择是创建处于已禁用状态还是已启用状态的规则。如果您选择启用规则，它将立即开始对您的数据进行分析。运行启用的规则时，您需要支付费用。有关更多信息，请参阅 [Amazon CloudWatch 定价](https://aws.amazon.com/cloudwatch/pricing/)。

   Contributor Insights 仅在创建规则后分析新的日志事件。规则无法处理之前已由 CloudWatch Logs 处理的日志事件。

1. （可选）对于 **Tags**（标签），请添加一个或多个键/值对作为此规则的标签。标签可帮助您识别和组织 AWS 资源并跟踪 AWS 成本。有关更多信息，请参阅 [标记 Amazon CloudWatch 资源](CloudWatch-Tagging.md)。

1. 选择**创建**。

**要从 Scratch 创建规则，请执行以下操作：**

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 在导航窗格中，选择**日志**、**Contributor Insights**。

1. 选择 **Create rule**（创建规则）。

   

1.  对于 **Select log group(s)**（选择日志组），请选择您希望您的规则监控的日志组。您可以选择多达 20 个日志组。如果您登录的账户是为 CloudWatch 跨账户可观测性设置的监控账户，则可以选择源账户中的日志组，也可以设置单个规则来分析不同账户中的日志组。

   1.  （可选）要选择名称以特定字符串开头的所有日志组，请选择 **Select by prefix match**（按前缀匹配选择）下拉菜单，然后输入前缀。
**注意**  
 您需要为与您的规则匹配的每个日志事件支付费用。如果您选择 **Select by prefix match**（按前缀匹配选择）下拉菜单，请注意前缀可以匹配多少个日志组。如果您搜索了超出预期数量的日志组，可能会产生意外费用。有关更多信息，请参阅 [Amazon CloudWatch 定价](https://aws.amazon.com/cloudwatch/pricing)。

1. 对于 **Rule type**（规则类型），请选择 **Custom rule**（自定义规则）。

1. 对于 **Log format (日志格式)**，请选择 **JSON** 或 **CLF**。

1. 对于**转换器**，请选择**启用转换器 Contributor Insights**，以便在经 [CloudWatch Logs 日志转换](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CloudWatch-Logs-Transformation.html.html)处理后，让规则对日志事件进行评估。如果选择启用此功能：
   + 如果规则会评估任何具有转换器的日志组，则该规则将应用于日志的转换版本。
   + 如果该规则会评估任何没有转换器的日志组，则该规则将应用于日志的原始版本。

   如果不选择此选项，则将对所有日志组中的原始日志事件进行评估，包括经日志转换功能转换的日志事件。
**注意**  
如果日志组具有转换器且某些日志事件转换失败，Contributor Insights 则不会评估这些日志事件。有关调查日志转换失败的信息，请参阅 [Transformation metrics and errors](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Transformation-Errors-Metrics.html)。

1. 您可以通过以下方式完成规则的创建过程：使用向导，或选择 **Syntax (语法)** 选项卡并手动指定规则语法。

   要继续使用此向导，请执行以下操作：

   1. 对于 **Contribution (贡献)**、**Key (键)**，请输入要报告的贡献者类型。此报告将显示该贡献者类型的前 N 个值。

      有效条目为任何具有值的日志字段。示例包括 **requestId**、**sourceIPaddress** 和 **containerID**。

      有关查找特定日志组中日志的日志字段名称的信息，请参阅[查找日志字段](#finding_log_fields)。

      大于 1 KB 的键将被截断至 1KB。

   1. （可选）选择 **Add new key**（添加新键）以添加更多键。可以在规则中包含最多四个键。如果输入多个键，则报告中的贡献者将由键的唯一值组合定义。例如，如果您指定三个键，则三个键的每个唯一值组合将被计为一个独特贡献者。

   1. （可选）如果要添加筛选条件以缩小结果范围，请选择 **Add filter**（添加筛选条件）。对于 **Match**（匹配），输入要作为筛选条件的日志字段的名称。对于 **Condition**（条件），选择比较运算符，并输入要作为筛选条件的值。

      您可以在规则中最多添加 4 个筛选条件。多个筛选条件通过 AND 逻辑联接，因此，仅返回与所有筛选条件都匹配的日志事件。
**注意**  
遵循比较运算符的数组（例如 `In`、`NotIn` 或者 `StartsWith`）可以包含最多 10 个字符串值。有关 Contributor Insights 规则语法的更多信息，请参阅 [CloudWatch 中的 Contributor Insights 规则语法](ContributorInsights-RuleSyntax.md)。

   1. 对于 **Aggregate on（聚合）**，选择 **Count（计数）**或 **Sum（总计）**。选择 **Count（计数）**会使贡献者排名基于出现次数。选择 **Sum（总计）**会使排名基于您为 **Contribution（贡献）**、**Value（值）**指定的字段值的总和。

1. 要输入规则作为 JSON 对象而不是使用此向导，请执行以下操作：

   1. 选择 **Syntax (语法)** 选项卡。

   1. 在 **Rule body (规则正文)** 中，输入规则的 JSON 对象。有关规则语法的信息，请参阅 [CloudWatch 中的 Contributor Insights 规则语法](ContributorInsights-RuleSyntax.md)。

1. 选择**下一步**。

1. 为 **Rule name (规则名称)** 输入一个名称。有效字符为 A-Z、a-z、0-9、“-”、“\$1”和“.”。

1. 选择是创建处于已禁用状态还是已启用状态的规则。如果您选择启用规则，它将立即开始对您的数据进行分析。运行启用的规则时，您需要支付费用。有关更多信息，请参阅 [Amazon CloudWatch 定价](https://aws.amazon.com/cloudwatch/pricing/)。

   Contributor Insights 仅在创建规则后分析新的日志事件。规则无法处理之前已由 CloudWatch Logs 处理的日志事件。

1. （可选）对于 **Tags**（标签），请添加一个或多个键/值对作为此规则的标签。标签可帮助您识别和组织 AWS 资源并跟踪 AWS 成本。有关更多信息，请参阅 [标记 Amazon CloudWatch 资源](CloudWatch-Tagging.md)。

1. 选择**下一步**。

1. 确认您输入的设置，然后选择 **Create rule**（创建规则）。

可以禁用、启用或删除已创建的规则。

**在 Contributor Insights 中启用、禁用或删除规则**

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 在导航窗格中，选择**日志**、**Contributor Insights**。

1. 在规则列表中，选中单个规则旁边的复选框。

   内置规则由 AWS 服务创建，无法编辑、禁用或删除这些规则。

1. 选择 **Actions (操作)**，然后选择所需选项。<a name="finding_log_fields"></a>

**查找日志字段**

创建规则时，您需要知道日志组的日志条目中的字段名称。

**查找日志组中的日志字段**

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 在导航窗格中的 **Logs (日志)** 下，选择 **Insights (见解)**。

1. 在查询编辑器上方，选择要查询的一个或多个日志组。

   当您选择日志组时，CloudWatch Logs Insights 会自动检测日志组数据中的字段，并将其显示在右侧窗格中的 **Discovered fields（发现的字段）**中。

# CloudWatch 中的 Contributor Insights 规则语法
<a name="ContributorInsights-RuleSyntax"></a>

此部分说明了 Contributor Insights 规则的语法。仅当您通过输入 JSON 块来创建规则时使用此语法。如果您使用此向导创建规则，则无需知道语法。有关使用此向导创建规则的更多信息，请参阅 [在 CloudWatch 中创建 Contributor Insights 规则](ContributorInsights-CreateRule.md)。

日志事件字段名称和值的所有规则匹配都区分大小写。

以下示例说明了 JSON 日志的语法。

```
{
    "Schema": {
        "Name": "CloudWatchLogRule",
        "Version": 1
    },
    "LogGroupNames": [
        "API-Gateway-Access-Logs*",
        "Log-group-name2"
    ],
    "LogFormat": "JSON",
    "Contribution": {
        "Keys": [
            "$.ip"
        ],
        "ValueOf": "$.requestBytes",
        "Filters": [
            {
                "Match": "$.httpMethod",
                "In": [
                    "PUT"
                ]
            }
        ]
    },
    "AggregateOn": "Sum"
}
```Contributor Insights 规则中的字段

架构  
 用于分析 CloudWatch Logs 数据 `Schema` 的规则的值必须始终为 `{"Name": "CloudWatchLogRule", "Version": 1}` 

LogGroupNames  
 字符串数组。对于数组中的每个元素，您可以选择在字符串末尾使用 `*` 以包含名称以该前缀开头的所有日志组。  
将通配符用于日志组名称时要小心。您需要为与规则匹配的每个日志事件支付费用。如果不小心搜索了超出预期数量的日志组，可能会产生意外费用。有关更多信息，请参阅 [Amazon CloudWatch 定价](https://aws.amazon.com/cloudwatch/pricing)。

LogGroupARN  
如果您在 CloudWatch 跨账户可观测性监控账户中创建此规则，则可以使用 `LogGroupARNs` 在与该监控账户关联的源账户中指定日志组，然后指定该监控账户本身的日志组。您必须在规则中指定 `LogGroupNames` 或 `LogGroupARNs`，但不能同时指定两者。  
 `LogGroupARNs` 是一个字符串数组。对于该数组中的每个元素，在某些情况下可以选择使用 `*` 作为通配符。例如，您可以指定 `arn:aws:logs:us-west-1:*:log-group/MyLogGroupName2`，以便在美国西部（北加利福尼亚）地区的所有源账户和该监控账户中指定名为 `MyLogGroupName2` 的日志组。您还可以指定 `arn:aws:logs:us-west-1:111122223333:log-group/GroupNamePrefix*`，以便在 111122223333 中指定美国西部（北加利福尼亚）所有名称以 `GroupNamePrefix` 开头的日志组。  
您不能将部分 AWS 账户 ID 指定为带通配符的前缀。  
将通配符用于日志组 ARN 时要小心。您需要为与规则匹配的每个日志事件支付费用。如果不小心搜索了超出预期数量的日志组，可能会产生意外费用。有关更多信息，请参阅 [Amazon CloudWatch 定价](https://aws.amazon.com/cloudwatch/pricing)。

LogFormat  
 有效值为 `JSON` 和 `CLF`。

贡献  
 此对象包含一个具有最多个四个成员的 `Keys` 数组、（可选）一个 `ValueOf`、（可选）一个具有最多四个 `Filters` 的数组。

键  
 一个最多具有四个日志字段的数组，这些字段用作维度以对贡献者进行分类。如果您输入多个键，则这些键的每个唯一值组合将被计为一个独特贡献者。必须使用 JSON 属性格式表示法指定字段。

ValueOf  
 （可选）仅当您指定 `Sum` 作为 `AggregateOn` 的值时指定此选项。`ValueOf` 指定具有数值的日志字段。在此类规则中，贡献者按其在此字段中的值的和来进行排名，而不是按其在日志条目中的出现次数进行排名。例如，如果您希望按贡献者在一段时间内的 `BytesSent` 总数对其进行排名，则需要将 `ValueOf` 设置为 `BytesSent`，并为 `AggregateOn` 指定 `Sum`。

筛选条件  
 指定具有最多四个筛选条件的数组可缩小报告中包含的日志事件的范围。如果您指定多个筛选条件，则 Contributor Insights 会使用逻辑 AND 运算符对它们进行评估。您可以使用此选项来筛掉搜索中不相关的日志事件，也可以使用它选择单个贡献者来分析其行为。  
数组中的每个成员必须包含一个 `Match` 字段和一个指示要使用的匹配运算符类型的字段。  
`Match` 字段指定要在筛选条件中评估的日志字段。使用 JSON 属性格式表示法指定日志字段。  
匹配的运算符字段必须是下列项目之一：`In`、`NotIn`、`StartsWith`、`GreaterThan`、`LessThan`、`EqualTo`、`NotEqualTo` 或 `IsPresent`。如果运算符字段为 `In`、`NotIn` 或 `StartsWith`，则它后跟一个要检查的字符串值数组。Contributor Insights 使用 OR 运算符评估字符串值的数组。该数组可以包含最多 10 个字符串值。  
如果运算符字段为 `GreaterThan`、`LessThan`、`EqualTo` 或 `NotEqualTo`，则它后跟要比较的单个数值。  
如果运算符字段为 `IsPresent`，则它后跟 `true` 或 `false`。此运算符将根据日志事件中是否存在指定的日志字段来匹配日志事件。`isPresent` 仅使用 JSON 属性的叶节点中的值。例如，查找 `c-count` 的匹配项的筛选条件不会返回具有值 `details.c-count.c1` 的日志事件。  
有关四个筛选条件示例，请参阅以下内容:  

```
{"Match": "$.httpMethod", "In": [ "PUT", ] }
{"Match": "$.StatusCode", "EqualTo": 200 }
{"Match": "$.BytesReceived", "GreaterThan": 10000}
{"Match": "$.eventSource", "StartsWith": [ "ec2", "ecs" ] }
```

AggregateOn  
 有效值为 `Count` 和 `Sum`。指定是基于出现次数，还是基于 `ValueOf` 字段中指定的字段值的总和来聚合报告。

**JSON 属性格式表示法**

`Keys`、`ValueOf` 和 `Match` 字段遵循带点符号的 JSON 属性格式，其中 `$` 表示 JSON 对象的根。这之后是句点，然后是带子属性名称的字母数字字符串。支持多个属性级别。

字符串的第一个字符只能是 A-Z 或 a-z。字符串的后续字符可以是 A-Z、a-z 或 0-9。

以下列表显示了 JSON 属性格式的有效示例：

```
$.userAgent
$.endpoints[0]
$.users[1].name
$.requestParameters.instanceId
```

**CLF 日志规则中的其他字段**

常用日志格式 (CLF) 日志事件不像 JSON 那样具有字段的名称。要提供用于 Contributor Insights 规则的字段，CLF 日志事件可被视为具有从 `1` 开始的索引的数组。您可以将第一个字段指定为 **"1"**，将第二个字段指定为 **"2"**，以此类推。

要使 CLF 日志的规则更易于读取，可以使用 `Fields`。这可让您为 CLF 字段位置提供命名别名。例如，您可以指定位置“4”为 IP 地址。指定后，`IpAddress` 可用作规则中的 `Keys`、`ValueOf` 和 `Filters` 中的属性。

以下是使用 `Fields` 字段的 CLF 日志规则的示例。

```
{
    "Schema": {
        "Name": "CloudWatchLogRule",
        "Version": 1
    },
    "LogGroupNames": [
        "API-Gateway-Access-Logs*"
    ],
    "LogFormat": "CLF",
    "Fields": {
        "4": "IpAddress",
        "7": "StatusCode"
    },
    "Contribution": {
        "Keys": [
            "IpAddress"
        ],
        "Filters": [
            {
                "Match": "StatusCode",
                "EqualTo": 200
            }
        ]
    },
    "AggregateOn": "Count"
}
```

# CloudWatch Contributor Insights 规则示例
<a name="ContributorInsights-Rule-Examples"></a>

此部分包含的示例说明了 Contributor Insights 规则的使用案例。

**VPC 流日志：按源和目标 IP 地址进行的字节传输**

```
{
    "Schema": {
        "Name": "CloudWatchLogRule",
        "Version": 1
    },
    "LogGroupNames": [
        "/aws/containerinsights/sample-cluster-name/flowlogs"
    ],
    "LogFormat": "CLF",
    "Fields": {
        "4": "srcaddr",
        "5": "dstaddr",
        "10": "bytes"
    },
    "Contribution": {
        "Keys": [
            "srcaddr",
            "dstaddr"
        ],
        "ValueOf": "bytes",
        "Filters": []
    },
    "AggregateOn": "Sum"
}
```

**VPC 流日志：最大 HTTPS 请求数**

```
{
    "Schema": {
        "Name": "CloudWatchLogRule",
        "Version": 1
    },
    "LogGroupNames": [
        "/aws/containerinsights/sample-cluster-name/flowlogs"
    ],
    "LogFormat": "CLF",
    "Fields": {
        "5": "destination address",
        "7": "destination port",
        "9": "packet count"
    },
    "Contribution": {
        "Keys": [
            "destination address"
        ],
        "ValueOf": "packet count",
        "Filters": [
            {
                "Match": "destination port",
                "EqualTo": 443
            }
        ]
    },
    "AggregateOn": "Sum"
}
```

**VPC 流日志：被拒绝的 TCP 连接数**

```
{
    "Schema": {
        "Name": "CloudWatchLogRule",
        "Version": 1
    },
    "LogGroupNames": [
        "/aws/containerinsights/sample-cluster-name/flowlogs"
    ],
    "LogFormat": "CLF",
    "Fields": {
        "3": "interfaceID",
        "4": "sourceAddress",
        "8": "protocol",
        "13": "action"
    },
    "Contribution": {
        "Keys": [
            "interfaceID",
            "sourceAddress"
        ],
        "Filters": [
            {
                "Match": "protocol",
                "EqualTo": 6
            },
            {
                "Match": "action",
                "In": [
                    "REJECT"
                ]
            }
        ]
    },
    "AggregateOn": "Sum"
}
```

**Route 53 NXDomain 按源地址响应**

```
{
    "Schema": {
        "Name": "CloudWatchLogRule",
        "Version": 1
    },
    "AggregateOn": "Count",
    "Contribution": {
        "Filters": [
            {
                "Match": "$.rcode",
                "StartsWith": [
                    "NXDOMAIN"
                ]
            }
        ],
        "Keys": [
            "$.srcaddr"
        ]
    },
    "LogFormat": "JSON",
    "LogGroupNames": [
        "<loggroupname>"
    ]
}
```

**Route 53 Resolver 按域名查询**

```
{
    "Schema": {
        "Name": "CloudWatchLogRule",
        "Version": 1
    },
    "AggregateOn": "Count",
    "Contribution": {
        "Filters": [],
        "Keys": [
            "$.query_name"
        ]
    },
    "LogFormat": "JSON",
    "LogGroupNames": [
        "<loggroupname>"
    ]
}
```

**Route 53 Resolver 按查询类型和源地址查询**

```
{
    "Schema": {
        "Name": "CloudWatchLogRule",
        "Version": 1
    },
    "AggregateOn": "Count",
    "Contribution": {
        "Filters": [],
        "Keys": [
            "$.query_type",
            "$.srcaddr"
        ]
    },
    "LogFormat": "JSON",
    "LogGroupNames": [
        "<loggroupname>"
    ]
}
```

# 在 CloudWatch 中查看 Contributor Insights 报告
<a name="ContributorInsights-ViewReports"></a>

要查看报告数据的图表和您的规则找到的贡献者排名列表，请执行以下步骤。

**查看规则报告**

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 在导航窗格中，选择**日志**、**Contributor Insights**。

   

1. 在该规则列表中，选择规则的名称。

   图表显示了过去三小时内的规则结果。图表下方的表显示了前 10 名贡献者。

1. 要更改表中显示的贡献者数，请选择图表顶部的 **Top 10 contributors (前 10 名贡献者)**。

1. 要筛选图表以仅显示单个贡献者的结果，请在表图例中选择该贡献者。要再次显示所有贡献者，请在图例中再次选择同一个贡献者。

1. 要更改报告中显示的时间范围，请选择图表顶部的 **15m**（15 分钟）、**30m**（30 分钟）、**1h**（1 小时）、**2h**（2 小时）、**3h**（3 小时）或 **custom**（自定义）。

   报告的最大时间范围为 24 小时，但您可以选择最多 15 天前发生的 24 小时时段。要选择过去的时段，请选择 **custom (自定义)**、**absolute (绝对)**，然后指定您的时段。

1. 要更改用于聚合和贡献者排名的时段的长度，请选择图表顶部的 **period (周期)**。查看较长的时段通常会显示更平滑的报告，其中包含的峰值很少。选择较短的时段更有可能显示峰值。

1. 要将此图表添加到 CloudWatch 控制面板，请选择 **Add to dashboard（添加到控制面板）**。

1. 要打开 CloudWatch Logs Insights 查询窗口（此报告中的日志组已加载到查询框中），请选择 **View logs（查看日志）**。

1. 要将报告数据导出到剪贴板或 CSV 文件，请选择 **Export (导出)**。

# 绘制 CloudWatch 中规则生成的指标的图表
<a name="ContributorInsights-GraphReportData"></a>

Contributor Insights 提供了一个指标数学函数，即 `INSIGHT_RULE_METRIC`。您可以使用此函数将 Contributor Insights 报告中的数据添加到 CloudWatch 控制台的 **Metrics（指标）**选项卡中的图表。您也可以根据此数学函数来设置警报。有关指标数学函数的更多信息，请参阅 [将数学表达式与 CloudWatch 指标结合使用](using-metric-math.md)。

要使用此指标数学函数，您必须登录到同时具有 `cloudwatch:GetMetricData` 和 `cloudwatch:GetInsightRuleReport` 权限的账户。



语法为 `INSIGHT_RULE_METRIC(ruleName, metricName)`。*ruleName* 是 Contributor Insights 规则的名称，*metricName* 是以下列表中的值之一。*metricName* 的值决定了数学函数返回的数据类型。
+ `UniqueContributors` – 每个数据点的独特贡献者数。
+ `MaxContributorValue` – 每个数据点的顶级贡献者的值。对于图表中的每个数据点，确定的贡献者可能会变化。

  如果此规则按 `Count` 进行聚合，则每个数据点的顶级贡献者是该时段内出现次数最多的贡献者。如果此规则按 `Sum` 进行聚合，则排在最前面的贡献者是此时段内具有该规则的 `Value` 指定的日志字段中最大总和的贡献者。
+ `SampleCount` – 规则匹配的数据点数。
+ `Sum` – 该数据点表示的时段内来自所有贡献者的值的总和。
+ `Minimum` – 该数据点所表示的时段内单个观察结果中的最小值。
+ `Maximum` – 该数据点所表示的时段内单个观察结果中的最大值。
+ `Average` – 该数据点表示的时段内来自所有贡献者的平均值。

## 为 Contributor Insights 指标数据设置告警
<a name="ContributorInsights-GraphReportData-Alarm"></a>

您可以使用函数 `INSIGHT_RULE_METRIC` 对 Contributor Insights 生成的指标设置告警。例如，您可以根据已被拒绝的传输控制协议（TCP）连接的百分比来创建告警。要开始使用这种类型的告警，您可以创建类似以下两个示例中所示的规则:

**示例规则: "RejectedConnectionsRule"**

```
{
    "Schema": {
        "Name": "CloudWatchLogRule",
        "Version": 1
    },
    "LogGroupNames": [
        "/aws/containerinsights/sample-cluster-name/flowlogs"
    ],
    "LogFormat": "CLF",
    "Fields": {
        "3": "interfaceID",
        "4": "sourceAddress",
        "8": "protocol",
        "13": "action"
    },
    "Contribution": {
        "Keys": [
            "interfaceID",
            "sourceAddress"
        ],
        "Filters": [
            {
                "Match": "protocol",
                "EqualTo": 6
            },
            {
                "Match": "action",
                "In": [
                    "REJECT"
                ]
            }
        ]
    },
    "AggregateOn": "Sum"
}
```

**示例规则: "TotalConnectionsRule"**

```
{
    "Schema": {
        "Name": "CloudWatchLogRule",
        "Version": 1
    },
    "LogGroupNames": [
        "/aws/containerinsights/sample-cluster-name/flowlogs"
    ],
    "LogFormat": "CLF",
    "Fields": {
        "3": "interfaceID",
        "4": "sourceAddress",
        "8": "protocol",
        "13": "action"
    },
    "Contribution": {
        "Keys": [
            "interfaceID",
            "sourceAddress"
        ],
        "Filters": [{
            "Match": "protocol",
            "EqualTo": 6
        }],
        "AggregateOn": "Sum"
    }
}
```

创建规则后，您可以选择 CloudWatch 控制台中的 **Metrics**（指标）选项卡，在其中使用以下示例指标数学表达式来绘制 Contributor Insights 报告的数据的图表:

**示例: 指标数学表达式**

```
e1 INSIGHT_RULE_METRIC("RejectedConnectionsRule", "Sum")
e2 INSIGHT_RULE_METRIC("TotalConnectionsRule", "Sum")
e3 (e1/e2)*100
```

在该示例中，指标数学表达式 `e3` 返回所有已被拒绝的 TCP 连接。如果您想要在已被拒绝的 TCP 连接达到 20% 时收到通知，则可以修改表达式，将阈值从 `100` 更改为 `20`。

**注意**  
在 **Metrics**（指标）部分中，您可以对您监控的指标设置告警。在 **Graphed metrics**（绘制的指标）选项卡中，您可以选择 **Actions**（操作）列下的 **Create alarm**（创建告警）。**Create alarm**（创建告警）图标看起来像个铃铛。

有关绘制指标的图表和使用指标数学函数的更多信息，请参阅以下部分: [向 CloudWatch 图表中添加数学表达式](using-metric-math.md#adding-metrics-expression-console)。

# 在 CloudWatch 中使用 Contributor Insights 内置规则
<a name="ContributorInsights-BuiltInRules"></a>

您可以使用 Contributor Insights 内置规则来分析其他 AWS 服务的指标。以下服务支持内置规则：
+ *Amazon DynamoDB 开发人员指南*中的 [Amazon DynamoDB 的 Contributor Insights](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/contributorinsights.html)。
+ *AWS PrivateLink 指南*中的[使用内置的 Contributor Insights 规则](https://docs.aws.amazon.com/vpc/latest/privatelink/privatelink-cloudwatch-metrics.html#privatelink-contributor-insights)。

# 使用 CloudWatch Application Insights 检测常见应用程序问题
<a name="cloudwatch-application-insights"></a>

您可以使用 Amazon CloudWatch Application Insights 检测应用程序的问题。CloudWatch Application Insights 简化了观察您的应用程序和基础 AWS 资源的过程。它可用帮助您为应用程序资源设置最佳的监控，以持续分析数据，以便找出应用程序出现问题的迹象。Application Insights 由 [Sagemaker](https://docs.aws.amazon.com/sagemaker/latest/dg/wahtis.html) 和其他 AWS 技术提供支持，它提供了自动化控制面板以显示监控的应用程序的潜在问题，从而帮助您快速找出应用程序和基础设施当前存在的问题。Application Insights 提高了应用程序运行状况的可见性，可以帮助您缩短平均修复时间 (MTTR)，以便对应用程序进行故障排除。

在将应用程序添加到 Amazon CloudWatch Application Insights 时，它扫描应用程序中的资源，并在 [CloudWatch](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html) 上为应用程序组件建议和配置指标和日志。示例应用程序组件可能包括 SQL Server 后端数据库和 Microsoft IIS/Web 层。Application Insights 使用历史数据分析指标模式以检测异常情况，并从应用程序、操作系统和基础设施日志中持续检测错误和异常情况。它使用分类算法和内置规则组合以关联这些观察结果。然后，它自动创建控制面板以显示相关的观察结果和问题严重性信息，以帮助您确定操作的优先级。对于 .NET 和 SQL 应用程序堆栈中的常见问题（例如，应用程序延迟、SQL Server 备份失败、内存泄漏、过大的 HTTP 请求以及输入/输出操作取消），它提供了额外的洞察，以指出可能的根本原因和解决步骤。与 [AWS SSM OpsCenter](https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter.html) 进行内置集成后，您可以通过运行相关的 Systems Manager Automation 文档来解决问题。

**Topics**
+ [Amazon CloudWatch Application Insights 是什么？](appinsights-what-is.md)
+ [Application Insights 的工作方式](appinsights-how-works.md)
+ [先决条件、IAM 策略和权限](appinsights-accessing.md)
+ [设置应用程序以进行监控](appinsights-setting-up.md)
+ [Application Insights 跨账户可观测性](appinsights-cross-account.md)
+ [使用组件配置](component-config.md)
+ [使用 CloudFormation 模板](appinsights-cloudformation.md)
+ [教程：为 SAP ASE 设置监控](appinsights-tutorial-sap-ase.md)
+ [教程：为 SAP HANA 设置监控](appinsights-tutorial-sap-hana.md)
+ [教程：为 SAP NetWeaver 设置监控](appinsights-tutorial-sap-netweaver.md)
+ [查看和排查 Application Insights](appinsights-troubleshooting.md)
+ [支持的日志和指标](appinsights-logs-and-metrics.md)

# Amazon CloudWatch Application Insights 是什么？
<a name="appinsights-what-is"></a>

CloudWatch Application Insights 可帮助您监控使用 Amazon EC2 实例以及其他[应用程序资源](#appinsights-components)的应用程序。它可在应用程序资源和技术堆栈（例如，Microsoft SQL Server 数据库、Web (IIS) 和应用程序服务器、操作系统、负载均衡器和队列）中识别和设置关键指标、日志和警报。它会持续监控指标和日志，以检测异常情况和错误并将它们关联起来。在检测到错误和异常情况时，Application Insights 生成 [CloudWatch Events](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/WhatIsCloudWatchEvents.html)，您可以使用这些事件来设置通知或执行操作。为了帮助进行故障排除，它会为检测到的问题创建自动化控制面板，其中包含关联的指标异常情况和日志错误，以及可指出潜在根本原因的其他洞察。自动化控制面板可帮助您快速采取修复操作，以保持应用程序正常运行，并防止对应用程序的终端用户造成影响。此外，它还会创建 OpsItems，以便您可以使用 [AWS SSM OpsCenter](https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter.html) 解决问题。

您可以在 CloudWatch 上配置重要的计数器，例如镜像写入事务数/秒、恢复队列长度、事务延迟以及 Windows 事件日志。当 SQL HA 工作负载发生故障转移事件或问题（例如，查询目标数据库的访问权限受限）时，CloudWatch Application Insights 会提供自动化洞察。

CloudWatch Application Insights 与 [AWS Launch Wizard](https://docs.aws.amazon.com/launchwizard/latest/userguide/what-is-launch-wizard.html) 集成，从而为在 AWS 上部署 SQL Server HA 工作负载提供一键式监控设置体验。当您在 [Launch Wizard 控制台](https://console.aws.amazon.com/launchwizard)上选择使用 Application Insights 设置监控和洞察的选项时，CloudWatch Application Insights 会自动在 CloudWatch 上设置相关指标、日志和告警，并开始监控新部署的工作负载。您可以在 CloudWatch 控制台上查看自动化的洞察和检测到的问题，以及 SQL Server HA 工作负载的运行状况。

**Topics**
+ [功能](#appinsights-features)
+ [概念](#appinsights-concepts)
+ [定价](#appinsights-pricing)
+ [相关服务](#appinsights-related-services)
+ [支持的应用程序组件](#appinsights-components)
+ [支持的技术堆栈](#appinsights-stack)

## 功能
<a name="appinsights-features"></a>

Application Insights 提供以下功能。

**自动为应用程序资源设置监视器**  
CloudWatch Application Insights 可减少为应用程序设置监控所需的时间。它扫描应用程序资源，提供可自定义的建议指标和日志列表，并在 CloudWatch 上设置，从而为所需的应用程序资源（例如 Amazon EC2 和 Elastic Load Balancer (ELB)）提供可见性，从而减少为应用程序设置监控所需的时间。它还会为监控的指标设置动态警报。将根据前两周检测到的异常情况自动更新警报。

**问题检测和通知**  
CloudWatch Application Insights 检测应用程序出现潜在问题的迹象，例如指标异常情况和日志错误。它关联这些观察结果以找出应用程序的潜在问题。然后，它生成 CloudWatch Events，[可以配置这些事件以接收通知或执行操作](appinsights-cloudwatch-events.md)。这样，您无需为指标或日志错误创建单独的警报。此外，您可以[配置 Amazon SNS 通知](appinsights-problem-notifications.md)，进而在检测到问题时接收提醒。

**问题排查**  
CloudWatch Application Insights 为检测到的问题创建 CloudWatch 自动化控制面板。这些控制面板显示有关问题的详细信息（包括关联的指标异常情况和日志错误）以帮助您进行故障排除。它们还提供额外的信息，以指出异常情况和错误的潜在根本原因。

## 概念
<a name="appinsights-concepts"></a>

要了解 Application Insights 如何监控应用程序，以下概念是非常重要的。

**组件**  
对组成应用程序的类似资源进行自动分组、单独分组或自定义分组。我们建议将类似资源分组到自定义组件中，以更好地进行监控。

**观察**  
为应用程序或应用程序资源检测到的单个事件（指标异常情况、日志错误或异常）。

**问题**  
关联、分类和分组相关的观察结果以检测问题。

有关 CloudWatch Application Insights 的其他重要概念的定义，请参阅 [Amazon CloudWatch 概念](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html)。

## 定价
<a name="appinsights-pricing"></a>

CloudWatch Application Insights 使用 CloudWatch Metrics、Logs 和 Events 为选定的应用程序资源设置建议的指标和日志，以便就检测到的问题发出通知。将根据 [CloudWatch 定价](https://aws.amazon.com/cloudwatch/pricing)对您的 AWS 账户收取这些功能的费用。对于检测到的问题，Application Insights 还会创建 [SSM OpsItems](https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-working-with-OpsItems.html)，以通知您相关问题。此外，Application Insights 会创建 [SSM Parameter Store 参数](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html)，以便在您的实例上配置 CloudWatch 代理。Amazon EC2 Systems Manager 的功能根据 [SSM 定价](https://aws.amazon.com/systems-manager/pricing/)收费。不会向您收取设置帮助、监控、数据分析或问题检测费用。

### CloudWatch Application Insights 的成本
<a name="appinsights-pricing-ec2"></a>

Amazon EC2 的成本包括使用以下功能：
+ CloudWatch 代理
  + CloudWatch 代理日志组
  + CloudWatch 代理指标
  + Prometheus 日志组（用于 JMX 工作负载）

所有资源的成本包括使用以下功能：
+ CloudWatch 告警（大部分成本）
+ SSM OpsItems（最低成本）

### 成本计算示例
<a name="appinsights-pricing-example"></a>

本示例中的成本是根据以下方案考虑的。

您创建了一个包含以下内容的资源组：
+ 安装了 SQL Server 的 Amazon EC2 实例。
+ 附加的 Amazon EBS 卷。

当您使用 CloudWatch Application Insights 载入此资源组时，会检测到安装在 Amazon EC2 实例上的 SQL Server 工作负载。CloudWatch Application Insights 开始监控以下指标。

为 SQL Server 实例监控以下指标：
+ CPUUtilization
+ StatusCheckFailed
+ Memory % Committed Bytes in Use
+ Memory Available Mbytes
+ Network Interface Bytes Total/sec
+ Paging File % Usage
+ Physical Disk % Disk Time
+ Processor % Processor Time
+ SQLServer:Buffer Manager cache hit ratio
+ SQLServer:Buffer Manager life expectancy
+ SQLServer:General Statistics Processes blocked
+ SQLServer:General Statistics User Connections
+ SQLServer:Locks Number of Deadlocks/sec
+ SQLServer:SQL Statistics Batch Requests/sec
+ System Processor Queue Length

为附加到 SQL Server 实例的卷监控以下指标：
+ VolumeReadBytes
+ VolumeWriteBytes
+ VolumeReadOps
+ VolumeWriteOps
+ VolumeTotalReadTime
+ VolumeTotalWriteTime
+ VolumeIdleTime
+ VolumeQueueLength
+ VolumeThroughputPercentage
+ VolumeConsumedReadWriteOps
+ BurstBalance

此方案的成本是根据 [CloudWatch 定价](https://aws.amazon.com/cloudwatch/pricing/)页面和 [SSM 定价](https://aws.amazon.com/systems-manager/pricing/)页面计算的：
+ **自定义指标**

  对于此方案，上述指标中的 13 个指标是使用 CloudWatch 代理发送到 CloudWatch 的。这些指标被视为自定义指标。每个自定义指标的成本为每月 0.3 美元。这些自定义指标的总成本为 13 \$1 0.3 美元 = 3.90 美元/月。
+ **警报**

  对于此方案，CloudWatch Application Insights 总共监控 26 个指标，这会创建 26 个告警。每个告警的成本为每月 0.1 美元。告警的总成本为 26 \$1 0.1 美元 = 2.60 美元/月。
+ **数据摄取和错误日志**

  数据摄取的成本为 0.05 美元/GB，SQL Server 错误日志的存储成本为 0.03 美元/GB。数据摄取和错误日志的总成本为 0.05 美元/GB \$1 0.03 美元/GB = 0.08 美元/GB。
+ **Amazon EC2 Systems Manager OpsItems**

  系统为 CloudWatch Application Insights 检测到的每个问题创建一个 SSM OpsItem。对于应用程序中的 *n* 个问题，总成本为 0.00267 \$1 *n* 美元/月。

## 相关服务
<a name="appinsights-related-services"></a>

以下服务与 CloudWatch Application Insights 一起使用：

**相关 AWS 服务**
+ **Amazon CloudWatch** 在系统范围内提供资源使用率、应用程序性能和运行状况信息。它收集并跟踪指标，发送警报通知，根据您定义的规则自动更新监控的资源，并允许您监控自己的自定义指标。CloudWatch Application Insights 是通过 CloudWatch 启动的，具体来说，是在 CloudWatch 默认运行控制面板中启动的。有关更多信息，请参阅《[https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html)》。
+ **CloudWatch Container Insights** 从容器化应用程序和微服务中收集、聚合及汇总指标与日志。您可以使用 Container Insights 来监控 Amazon ECS、Amazon Elastic Kubernetes Service 以及 Amazon EC2 上的 Kubernetes 平台。在 Container Insights 或 Application Insights 控制台中启用 Application Insights 后，Application Insights 会将检测到的问题显示在 Container Insights 控制面板上。有关更多信息，请参阅 [Container Insights](ContainerInsights.md)。
+ **Amazon DynamoDB** 是完全托管式 NoSQL 数据库服务器，您可以用它免除操作和扩展分布式数据库的管理工作负担，因而无需担心硬件预置、设置和配置、复制、软件修补或集群扩展等问题。此外，DynamoDB 提供了加密静态，这可以消除在保护敏感数据时涉及的操作负担和复杂性。
+ **Amazon EC2** 在 AWS 云中提供可扩展的计算容量。您可以使用 Amazon EC2 启动所需数量的虚拟服务器，配置安全性和联网，以及管理存储。您可以扩展或缩减以处理需求变化或使用高峰，从而减少预测流量的需求。有关更多信息，请参阅[https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts.html](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts.html) 或[https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/concepts.html](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/concepts.html)。
+ **Amazon Elastic Block Store (Amazon EBS)** 提供了数据块级的存储卷以用于 Amazon EC2 实例。Amazon EBS 卷的行为类似于原始、未格式化的块储存设备。您可以将这些卷作为设备挂载在实例上。附加到实例的 Amazon EBS 卷公开为独立于实例生命周期而持续存在的存储卷。您可以在这些卷上创建文件系统，或者以使用块储存设备（如硬盘）的任何方式使用这些卷。您可以动态更改附加到实例的卷的配置。有关更多信息，请参阅 [Amazon EBS 用户指南](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AmazonEBS.html)。
+ **Amazon EC2 Auto Scaling** 帮助确保您具有正确数量的 EC2 实例以处理应用程序负载。有关更多信息，请参阅 [https://docs.aws.amazon.com/autoscaling/ec2/userguide/what-is-amazon-ec2-auto-scaling.html](https://docs.aws.amazon.com/autoscaling/ec2/userguide/what-is-amazon-ec2-auto-scaling.html)。
+ **Elastic Load Balancing** 在多个可用区中的多个目标（如 EC2 实例、容器和 IP 地址）之间分配传入的应用程序或网络流量。有关更多信息，请参阅 [https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/what-is-load-balancing.html](https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/what-is-load-balancing.html)。
+ **IAM** 是一项 Web 服务，可帮助您安全地控制用户对 AWS 资源的访问权限。可以通过 IAM 控制哪些用户可以使用您的 AWS 资源（身份验证），以及控制他们可以使用的资源和使用资源的方式（授权）。有关更多信息，请参阅 [Amazon CloudWatch 的身份验证和访问控制](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/auth-and-access-control-cw.html)。
+ 您可以通过 **AWS Lambda** 构建由事件触发的函数组成的无服务器应用程序，并使用 CodePipeline 和 AWS CodeBuild 自动部署这些应用程序。有关更多信息，请参阅 [AWS Lambda 应用程序](https://docs.aws.amazon.com/lambda/latest/dg/deploying-lambda-apps.html)。
+ **AWS Launch Wizard for SQL Server** 缩短了将 SQL Server 高可用性解决方案部署到云所需的时间。您可以在服务控制台上输入应用程序要求，包括性能、节点数量和连接性，并且，AWS Launch Wizard 可标识正确的 AWS 资源来部署和运行 SQL Server Always On 应用程序。
+ **AWS Resource Groups** 帮助您划分组成应用程序的资源。通过使用 Resource Groups，您可以同时管理和自动完成针对大量资源的任务。只能为单个应用程序注册一个资源组。有关更多信息，请参阅 [https://docs.aws.amazon.com/ARG/latest/userguide/welcome.html](https://docs.aws.amazon.com/ARG/latest/userguide/welcome.html)。
+ **Amazon SQS** 提供了一个安全、持久且可用的托管队列，以允许您集成和分离分布式软件系统和组件。有关更多信息，请参阅 [https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/welcome.html](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/welcome.html)。
+ **AWS Step Functions** 是一个无服务器函数构建工具，它允许您对各种 AWS 服务和资源（包括 AWS Lambda 函数）排序为结构化的可视化工作流。有关更多信息，请参阅[《AWS Step Functions 用户指南》](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html)。
+ **AWS SSM OpsCenter** 跨服务聚合并标准化 OpsItem，同时提供关于每个 OpsItem、相关 OpsItem 和相关资源的上下文调查数据。OpsCenter 还提供 Systems Manager Automation 文档 (runbook)，让您可以快速解决问题。您可以为每个 OpsItem 指定可搜索的自定义数据。您还可以按状态和源查看自动生成的 OpsItem 相关摘要报告。有关更多信息，请参阅[《*AWS Systems Manager 用户指南》*](https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter.html)。
+ **Amazon API Gateway** 是一项 AWS 服务，用于创建、发布、维护、监控和保护任意规模的 REST、HTTP 和 WebSocket API。API 开发人员可以创建能够访问 AWS 或其他 Web 服务以及存储在 AWS 云中的数据的 API。有关更多信息，请参阅 [Amazon API Gateway 用户指南](https://docs.aws.amazon.com/apigateway/latest/developerguide/welcome.html)。
**注意**  
Application Insights 仅支持 REST API 协议（v1 的 API Gateway 服务）。
+ **Amazon Elastic Container Service (Amazon ECS)** 是一项完全托管式的容器编排服务。您可以使用 Amazon ECS 运行最敏感和任务关键型的应用程序。有关更多信息，请参阅 [Amazon Elastic Container Service 开发人员指南](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/Welcome.html)。
+ **Amazon Elastic Kubernetes Service (Amazon EKS)** 是一项托管式服务，可让您在 AWS 上轻松运行 Kubernetes，而无需安装、操作或维护您自己的 Kubernetes 控制面板或节点。Kubernetes 是一个用于实现容器化应用程序的部署、扩缩和管理自动化的开源系统。有关更多信息，请参阅 [Amazon EKS 用户指南](https://docs.aws.amazon.com/eks/latest/userguide/what-is-eks.html)。
+ **Amazon EC2 上的 Kubernetes**。Kubernetes 是一个开源软件，可帮助您大规模部署和管理容器化应用程序。Kubernetes 可管理 Amazon EC2 计算实例的集群，并通过部署、维护和扩展流程在这些实例上运行容器。使用 Kubernetes，您可以在本地和云中使用相同的工具集运行任何类型的容器化应用程序。有关更多信息，请参阅 [Kubernetes 文档：入门](https://kubernetes.io/docs/setup/)。
+ **Amazon FSx**可帮助您启动和运行流行的 AWS 完全托管式文件系统。使用 Amazon FSx，您可以利用通用开源文件系统和获商业许可的文件系统的功能集和性能来避免耗时的管理任务。有关更多信息，请参阅 [Amazon FSx 文档](https://docs.aws.amazon.com/fsx/)。
+ **Amazon Simple Notification Service (SNS)** 是一项完全托管式消息收发服务，适用于应用程序间和应用程序与人之间的通信。您可以将 Amazon SNS 配置为由 Application Insights 对其进行监控。当将 Amazon SNS 配置为监控资源时，Application Insights 会跟踪 SNS 指标，帮助确定 SNS 消息可能会遇到问题或失败的原因。
+ **Amazon Elastic File System（Amazon EFS）**是一种完全托管式的弹性 NFS 文件系统，可用于 AWS 云 服务和本地资源。它专为在不中断应用程序的情况下按需扩展到 PB 级容量而打造。文件系统会在您添加和移除文件时自动增大和缩小容量，无需预调配和管理容量来满足容量增长需求。有关更多信息，请参阅 [Amazon Elastic File System 文档](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AmazonEFS.html)。

**相关第三方服务**
+ 对于在 Application Insights 中监控的某些工作负载和应用程序，**Prometheus JMX Exporter** 使用 AWS Systems Manager Distributor 安装，以便 CloudWatch Application Insights 可以检索 Java 特定的指标。当您选择监控 Java 应用程序时，Application Insights 会自动为您安装 Prometheus JMX Exporter。

## 支持的应用程序组件
<a name="appinsights-components"></a>

CloudWatch Application Insights 可扫描您的资源组以识别应用程序组件。组件可能采用单独分组、自动分组（例如自动扩缩组中的实例或负载均衡器后面的实例）或自定义分组（将各个 Amazon EC2 实例分组在一起）。

CloudWatch Application Insights 支持以下组件：

**AWS 组件**
+ Amazon EC2
+ Amazon EBS
+ Amazon RDS
+ Elastic Load Balancing：Application Load Balancer 和经典负载均衡器（指定和配置这些负载均衡器的所有目标实例）。
+ Amazon EC2 Auto Scaling 组：AWS Auto Scaling（为所有目标实例动态配置自动扩缩组；如果应用程序纵向扩展，CloudWatch Application Insights 将自动配置新实例）。基于 CloudFormation 堆栈的 Resource Groups 不支持自动扩缩组。
+ AWS Lambda
+ Amazon Simple Queue Service (Amazon SQS)
+ Amazon DynamoDB 表
+ Amazon S3 存储桶指标
+ AWS Step Functions
+ Amazon API Gateway REST API 阶段
+ Amazon Elastic Container Service (Amazon ECS)：集群、服务和任务
+ Amazon Elastic Kubernetes Service (Amazon EKS)：集群
+ Amazon EC2 上的 Kubernetes：在 EC2 上运行的 Kubernetes 集群
+ Amazon SNS 主题

CloudWatch Application Insights 当前不会追踪任何其他组件类型资源。如果在 Application Insights 应用程序中未显示某种支持的组件类型，则您拥有并由 Application Insights 监控的其他应用程序可能已注册和管理该组件。

## 支持的技术堆栈
<a name="appinsights-stack"></a>

您可以在“Application tier（应用程序层）”下拉菜单选项中选择以下技术之一，从而使用 CloudWatch Application Insights 监控在 Windows Server 和 Linux 操作系统上运行的应用程序：
+ 前端：Microsoft Internet 信息服务 (IIS) Web 服务器
+ 工件层：
  + NET Framework。
  + .NET 内核
+ 应用程序：
  + Java
  + SAP NetWeaver 标准、分布式和高可用性部署
+ Active Directory
+ SharePoint
+ 数据库：
  + 在 Amazon RDS 或 Amazon EC2 上运行的 Microsoft SQL Server（包括 SQL Server 高可用性配置，请参阅 [组件配置示例](component-configuration-examples.md)）。
  + 在 Amazon RDS、Amazon Aurora 或 Amazon EC2 上运行的 MySQL
  + 在 Amazon RDS 或 Amazon EC2 上运行的 PostgreSQL
  + Amazon DynamoDB 表
  + 在 Amazon RDS 或 Amazon EC2 上运行的 Oracle
  + 单个 Amazon EC2 实例和多个 EC2 实例上的 SAP HANA 数据库
  + 跨可用区 SAP HANA 数据库高可用性设置
  + 单个 Amazon EC2 实例上的 SAP Sybase ASE 数据库
  + 跨可用区 SAP Sybase ASE 数据库高可用性设置

如果上面列出的任何技术堆栈都不适用于您的应用程序资源，则您可以通过在 **Manage monitoring（管理监控）**页面上的“Application tier（应用程序层）”下拉菜单中选择 **Custom（自定义）**来监控您的应用程序堆栈。

# Amazon CloudWatch Application Insights 的工作方式
<a name="appinsights-how-works"></a>

CloudWatch Application Insights 提供对应用程序资源的监控。以下信息描述了 Application Insights 的工作原理。

**Topics**
+ [Application Insights 监控应用程序的方式](#appinsights-how-works-sub)
+ [数据留存](#appinsights-retention)
+ [配额](#appinsights-limits)
+ [CloudWatch Application Insights 使用的 AWS Systems Manager (SSM) 软件包](appinsights-ssm-packages.md)
+ [CloudWatch Application Insights 使用的 AWS Systems Manager（SSM）文档](appinsights-ssm-documents.md)

## Application Insights 监控应用程序的方式
<a name="appinsights-how-works-sub"></a>

以下信息描述了 Application Insights 如何监控应用程序。

**应用程序发现和配置**  
首次将应用程序添加到 CloudWatch Application Insights 时，它扫描应用程序组件以建议关键指标、日志和其他数据源，以便监控您的应用程序。然后，您可以根据这些建议配置应用程序。

**数据预处理**  
CloudWatch Application Insights 持续分析在应用程序资源中监控的数据源，以查找指标异常情况和日志错误（观察结果）。

**智能问题检测**  
CloudWatch Application Insights 引擎使用分类算法和内置规则关联观察结果，以检测应用程序中的问题。为了帮助进行故障排除，它创建一些自动化 CloudWatch 控制面板，其中包含有关问题的上下文信息。

**警报和操作**  
在 CloudWatch Application Insights 检测到应用程序出现问题时，它生成 CloudWatch Events 以通知您该问题。有关如何设置这些事件的更多信息，请参阅[检测到的问题的 Application Insights CloudWatch Events](appinsights-cloudwatch-events.md)。此外，您可以[配置 Amazon SNS 通知](appinsights-problem-notifications.md)，进而在检测到问题时接收提醒。

**示例方案**

您具有一个由 SQL Server 数据库支持的 ASP .NET 应用程序。突然，您的数据库由于内存压力过高而开始发生故障。这会导致应用程序性能下降，并且可能会导致在 Web 服务器和负载均衡器中出现 HTTP 500 错误。

借助于 CloudWatch Application Insights 及其智能分析，您可以检查动态创建的控制面板（显示相关指标和日志文件片段）以找出导致问题的应用程序层。在这种情况下，问题可能出在 SQL 数据库层。

## 数据留存
<a name="appinsights-retention"></a>

CloudWatch Application Insights 将问题保留 55 天，并将观察结果保留 60 天。

## 配额
<a name="appinsights-limits"></a>

有关 CloudWatch Application Insights 的默认配额，请参阅 [Amazon CloudWatch Application Insights 端点和配额](https://docs.aws.amazon.com/general/latest/gr/applicationinsights.html)。除非另有说明，否则，每个配额针对的是每个 AWS 区域。如需请求增加服务配额，请联系 [AWS Support](https://console.aws.amazon.com/support/home#/case/create?issueType=technical)。许多服务包含无法更改的配额。有关特定服务的配额的更多信息，请参阅针对该服务的文档。

# CloudWatch Application Insights 使用的 AWS Systems Manager (SSM) 软件包
<a name="appinsights-ssm-packages"></a>

本节中列出的软件包由 Application Insights 使用，可独立管理并可通过 AWS Systems Manager Distributor 部署。有关 SSM Distributor 的更多信息，请参阅 *AWS Systems Manager 用户指南*中的 [AWS Systems Manager Distributor](https://docs.aws.amazon.com/systems-manager/latest/userguide/distributor.html)。

**Topics**
+ [`AWSObservabilityExporter-JMXExporterInstallAndConfigure`](#configure-java)
+ [`AWSObservabilityExporter-SAP-HANADBExporterInstallAndConfigure`](#appinsights-ssm-sap-prometheus)
+ [`AWSObservabilityExporter-HAClusterExporterInstallAndConfigure`](#appinsights-ssm-sap-prometheus-ha)
+ [`AWSObservabilityExporter-SAP-SAPHostExporterInstallAndConfigure`](#appinsights-ssm-sap-host-exporter)
+ [`AWSObservabilityExporter-SQLExporterInstallAndConfigure`](#appinsights-ssm-sql-prometheus)

## `AWSObservabilityExporter-JMXExporterInstallAndConfigure`
<a name="configure-java"></a>

您可以从 [Prometheus JMX Exporter](https://prometheus.io/docs/instrumenting/exporters/#third-party-exporters) 中检索工作负载特定的 Java 指标，以供 Application Insights 配置和监控告警。在 Application Insights 控制台的 **Manage monitoring（管理监控）**页面上，在 **Application tier（应用程序层）**下拉菜单选择 **JAVA application（JAVA 应用程序）**。然后在 **JAVA Prometheus exporter configuration（JAVA Prometheus Exporter 配置）**下，选择您的 **Collection method（收集方法）**和 **JMX port number（JMX 端口号）**。

要使用 [AWS Systems Manager Distributor](https://docs.aws.amazon.com/systems-manager/latest/userguide/distributor.html) 来打包、安装和配置 AWS 提供的 Prometheus JMX Exporter（独立于 Application Insights），请完成以下步骤。

**使用 Prometheus JMX Exporter SSM 软件包的先决条件**
+ 2.3.1550.0 版或更高版本的 SSM Agent 已安装
+ JAVA\$1HOME 环境变量已设置

**安装和配置 `AWSObservabilityExporter-JMXExporterInstallAndConfigure` 软件包**  
`AWSObservabilityExporter-JMXExporterInstallAndConfigure` 软件包是一个 SSM Distributor 软件包，您可以使用它来安装和配置 [Prometheus JMX Exporter](https://github.com/prometheus/jmx_exporter)。当 Prometheus JMX Exporter 发送 Java 指标时，可以配置 CloudWatch 代理来检索 CloudWatch 服务的指标。

1. 根据您的首选项，准备位于 Prometheus GitHub 存储库中的 [Prometheus JMX Exporter YAML 配置文件](https://github.com/prometheus/jmx_exporter#configuration)。使用示例配置和选项说明为您提供指导。

1. 将编码为 Base64 的 Prometheus JMX Exporter YAML 配置文件复制到 [SSM Parameter Store](https://console.aws.amazon.com/systems-manager/parameters) 中的新 SSM 参数。

1. 导航到 [SSM Distributor](https://console.aws.amazon.com/systems-manager/distributor) 控制台，然后打开 **Owned by Amazon**（Amazon 所拥有）选项卡。选择 **AWSObservabilityExporter-JMXExporterInstallAndConfigure**，然后选择 **Install one time（安装一次）**。

1. 通过将“Additional Arguments（其他实际参数）”替换为以下内容来更新您在第一步中创建的 SSM 参数：

   ```
   {
     "SSM_EXPORTER_CONFIGURATION": "{{ssm:<SSM_PARAMETER_STORE_NAME>}}",
     "SSM_EXPOSITION_PORT": "9404"
   }
   ```
**注意**  
端口 9404 是用于发送 Prometheus JMX 指标的默认端口。您可以更新此端口。

**示例：配置 CloudWatch 代理以检索 Java 指标**

1. 如前面的步骤所述，安装 Prometheus JMX Exporter。然后检查端口状态，确认它是否已正确安装在您的实例上。

   在 Windows 实例示例上的成功安装

   ```
   PS C:\> curl http://localhost:9404 (http://localhost:9404/)
   StatusCode : 200
   StatusDescription : OK
   Content : # HELP jvm_info JVM version info
   ```

   在 Linux 实例示例上的成功安装

   ```
   $ curl localhost:9404
   # HELP jmx_config_reload_failure_total Number of times configuration have failed to be reloaded.
   # TYPE jmx_config_reload_failure_total counter
   jmx_config_reload_failure_total 0.0
   ```

1. 创建 Prometheus 服务发现 YAML 文件。以下示例服务发现文件将执行以下操作：
   + 将 Prometheus JMX Exporter 主机端口指定为 `localhost: 9404`。
   + 将标签（`Application`、`ComponentName` 和 `InstanceId`）附加到指标，这些指标可以设置为 CloudWatch 指标维度。

   ```
   $ cat prometheus_sd_jmx.yaml 
   - targets:
     - 127.0.0.1:9404
     labels:
       Application: myApp
       ComponentName: arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/sampl-Appli-MMZW8E3GH4H2/aac36d7fea2a6e5b
       InstanceId: i-12345678901234567
   ```

1. 创建 Prometheus JMX Exporter 配置 YAML 文件。以下示例配置文件可指定以下内容：
   + 指标检索任务间隔和超时周期。
   + 指标检索任务（`jmx` 和 `sap`）也称为抓取，其中包括任务名称、一次返回的最大时间序列以及服务发现文件路径。

   ```
   $ cat prometheus.yaml 
   global:
     scrape_interval: 1m
     scrape_timeout: 10s
   scrape_configs:
     - job_name: jmx
       sample_limit: 10000
       file_sd_configs:
         - files: ["/tmp/prometheus_sd_jmx.yaml"]
     - job_name: sap
       sample_limit: 10000
       file_sd_configs:
         - files: ["/tmp/prometheus_sd_sap.yaml"]
   ```

1. 验证 CloudWatch 代理是否已安装在您的 Amazon EC2 实例上，以及版本是否为 1.247346.1b249759 或更高版本。要在 EC2 实例上安装 CloudWatch 代理，请参阅[安装 CloudWatch 代理](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/install-CloudWatch-Agent-on-EC2-Instance.html)。要验证版本，请参阅[查找有关 CloudWatch 代理版本的信息](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/troubleshooting-CloudWatch-Agent.html#CloudWatch-Agent-troubleshooting-agent-version)。

1. 配置 CloudWatch 代理。有关如何配置 CloudWatch 代理配置文件的更多信息，请参阅[手动创建或编辑 CloudWatch 代理配置文件](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Agent-Configuration-File-Details.html)。以下示例 CloudWatch 代理配置文件可执行以下操作：
   + 指定 Prometheus JMX Exporter 配置文件路径。
   + 指定要向其发布 EMF 指标日志的目标日志组。
   + 为每个指标名称指定两组维度。
   + 发送 8 个（每个指标名称 2 组维度，每组 4 个指标名称）CloudWatch 指标。

   ```
   {
      "logs":{
         "logs_collected":{
            ....
         },
         "metrics_collected":{
            "prometheus":{
               "cluster_name":"prometheus-test-cluster",
               "log_group_name":"prometheus-test",
               "prometheus_config_path":"/tmp/prometheus.yaml",
               "emf_processor":{
                  "metric_declaration_dedup":true,
                  "metric_namespace":"CWAgent",
                  "metric_unit":{
                     "jvm_threads_current":"Count",
                     "jvm_gc_collection_seconds_sum":"Second",
                     "jvm_memory_bytes_used":"Bytes"
                  },
                  "metric_declaration":[
                     {
                        "source_labels":[
                           "job"
                        ],
                        "label_matcher":"^jmx$",
                        "dimensions":[
                           [
                              "InstanceId",
                              "ComponentName"
                           ],
                           [
                              "ComponentName"
                           ]
                        ],
                        "metric_selectors":[
                           "^java_lang_threading_threadcount$",
                           "^java_lang_memory_heapmemoryusage_used$",
                           "^java_lang_memory_heapmemoryusage_committed$"
                        ]
                     }
                  ]
               }
            }
         }
      },
      "metrics":{
         ....
      }
   }
   ```

## `AWSObservabilityExporter-SAP-HANADBExporterInstallAndConfigure`
<a name="appinsights-ssm-sap-prometheus"></a>

您可以从 [Prometheus HANA Database Exporter](https://prometheus.io/docs/instrumenting/exporters/#third-party-exporters) 中检索工作负载特定的 SAP HANA 指标，以供 Application Insights 配置和监控告警。有关更多信息，请参阅本指南中的[设置 SAP HANA 数据库以进行监控](appinsights-tutorial-sap-hana.md#appinsights-tutorial-sap-hana-set-up)。

要使用 [AWS Systems Manager Distributor](https://docs.aws.amazon.com/systems-manager/latest/userguide/distributor.html) 来打包、安装和配置 AWS 提供的 Prometheus HANA Database Exporter 软件包（独立于 Application Insights），请完成以下步骤。

**使用 Prometheus HANA Database Exporter SSM 软件包的先决条件**
+ 2.3.1550.0 版或更高版本的 SSM Agent 已安装
+ SAP HANA 数据库
+ Linux 操作系统（SUSE Linux、RedHat Linux）
+ 带有 SAP HANA 数据库监控凭证的密钥（使用 AWS Secrets Manager）。使用键/值对格式创建密钥，指定密钥用户名，然后输入值的数据库用户。再添加一个密钥密码，然后输入值的密码。有关如何创建密钥的更多信息，请参阅 *AWS Secrets Manager 用户指南*中的[创建密钥](https://docs.aws.amazon.com/secretsmanager/latest/userguide/manage_create-basic-secret.html)。密钥必须采用以下格式：

  ```
  {
    "username": "<database_user>",
    "password": "<database_password>"
  }
  ```

**安装和配置 `AWSObservabilityExporter-SAP-HANADBExporterInstallAndConfigure` 软件包**  
`AWSObservabilityExporter-SAP-HANADBExporterInstallAndConfigure` 软件包是一个 SSM Distributor 软件包，您可以使用它来安装和配置 [Prometheus HANA Database Exporter](https://github.com/prometheus/jmx_exporter)。当 Prometheus HANA Database Exporter 发送 HANA 数据库指标时，就可以配置 CloudWatch 代理来检索 CloudWatch 服务的指标。

1. 在 [SSM Parameter Store](https://console.aws.amazon.com/systems-manager/parameters) 中创建 SSM 参数以存储该 Exporter 的配置。以下为示例参数值。

   ```
   {\"exposition_port\":9668,\"multi_tenant\":true,\"timeout\":600,\"hana\":{\"host\":\"localhost\",\"port\":30013,\"aws_secret_name\":\"HANA_DB_CREDS\",\"scale_out_mode\":true}}
   ```
**注意**  
在此示例中，导出任务仅在具有活跃 `SYSTEM` 数据库的 Amazon EC2 实例上运行，并在其他 EC2 实例上保持空闲状态，以免指标重复。该 Exporter 可以检索 `SYSTEM` 数据库中的所有数据库租户信息。

1. 在 [SSM Parameter Store](https://console.aws.amazon.com/systems-manager/parameters) 中创建 SSM 参数以存储该 Exporter 的指标查询。软件包可以接受多个指标参数。每个参数必须具有有效的 JSON 对象格式。以下为示例参数值：

   ```
   {\"SELECT MAX(TIMESTAMP) TIMESTAMP, HOST, MEASURED_ELEMENT_NAME CORE, SUM(MAP(CAPTION, 'User Time', TO_NUMBER(VALUE), 0)) USER_PCT, SUM(MAP(CAPTION, 'System Time', TO_NUMBER(VALUE), 0)) SYSTEM_PCT, SUM(MAP(CAPTION, 'Wait Time', TO_NUMBER(VALUE), 0)) WAITIO_PCT, SUM(MAP(CAPTION, 'Idle Time', 0, TO_NUMBER(VALUE))) BUSY_PCT, SUM(MAP(CAPTION, 'Idle Time', TO_NUMBER(VALUE), 0)) IDLE_PCT FROM sys.M_HOST_AGENT_METRICS WHERE MEASURED_ELEMENT_TYPE = 'Processor' GROUP BY HOST, MEASURED_ELEMENT_NAME;\":{\"enabled\":true,\"metrics\":[{\"name\":\"hanadb_cpu_user\",\"description\":\"Percentage of CPU time spent by HANA DB in user space, over the last minute (in seconds)\",\"labels\":[\"HOST\",\"CORE\"],\"value\":\"USER_PCT\",\"unit\":\"percent\",\"type\":\"gauge\"},{\"name\":\"hanadb_cpu_system\",\"description\":\"Percentage of CPU time spent by HANA DB in Kernel space, over the last minute (in seconds)\",\"labels\":[\"HOST\",\"CORE\"],\"value\":\"SYSTEM_PCT\",\"unit\":\"percent\",\"type\":\"gauge\"},{\"name\":\"hanadb_cpu_waitio\",\"description\":\"Percentage of CPU time spent by HANA DB in IO mode, over the last minute (in seconds)\",\"labels\":[\"HOST\",\"CORE\"],\"value\":\"WAITIO_PCT\",\"unit\":\"percent\",\"type\":\"gauge\"},{\"name\":\"hanadb_cpu_busy\",\"description\":\"Percentage of CPU time spent by HANA DB, over the last minute (in seconds)\",\"labels\":[\"HOST\",\"CORE\"],\"value\":\"BUSY_PCT\",\"unit\":\"percent\",\"type\":\"gauge\"},{\"name\":\"hanadb_cpu_idle\",\"description\":\"Percentage of CPU time not spent by HANA DB, over the last minute (in seconds)\",\"labels\":[\"HOST\",\"CORE\"],\"value\":\"IDLE_PCT\",\"unit\":\"percent\",\"type\":\"gauge\"}]}}
   ```

   有关指标查询的更多信息，请参阅 GitHub 上的 [https://github.com/SUSE/hanadb_exporter/blob/master/metrics.json](https://github.com/SUSE/hanadb_exporter/blob/master/metrics.json) 存储库。

1. 导航到 [SSM Distributor](https://console.aws.amazon.com/systems-manager/distributor) 控制台，然后打开 **Owned by Amazon**（Amazon 所拥有）选项卡。依次选择 **AWSObservabilityExporter-SAP-HANADBExporterInstallAndConfigure\$1** 和 **Install one time**（一次性安装）。

1. 通过将“Additional Arguments（其他实际参数）”替换为以下内容来更新您在第一步中创建的 SSM 参数：

   ```
   {
     "SSM_EXPORTER_CONFIG": "{{ssm:<*SSM_CONFIGURATIONS_PARAMETER_STORE_NAME>*}}",
     "SSM_SID": "<SAP_DATABASE_SID>",
     "SSM_EXPORTER_METRICS_1": "{{ssm:<SSM_FIRST_METRICS_PARAMETER_STORE_NAME>}}",
     "SSM_EXPORTER_METRICS_2": "{{ssm:<SSM_SECOND_METRICS_PARAMETER_STORE_NAME>}}"
   }
   ```

1. 选择带有 SAP HANA 数据库的 Amazon EC2 实例，然后选择 **Run**（运行）。

## `AWSObservabilityExporter-HAClusterExporterInstallAndConfigure`
<a name="appinsights-ssm-sap-prometheus-ha"></a>

您可以从 [Prometheus HANA Cluster Exporter](https://prometheus.io/docs/instrumenting/exporters/#third-party-exporters) 中检索工作负载特定的高可用性 (HA) 集群指标，以供 Application Insights 配置和监控 SAP HANA 高可用性设置的告警。有关更多信息，请参阅本指南中的[设置 SAP HANA 数据库以进行监控](appinsights-tutorial-sap-hana.md#appinsights-tutorial-sap-hana-set-up)。

要使用 [AWS Systems Manager Distributor](https://docs.aws.amazon.com/systems-manager/latest/userguide/distributor.html) 来打包、安装和配置 AWS 提供的 Prometheus HA Cluster Exporter 软件包（独立于 Application Insights），请完成以下步骤。

**使用 Prometheus HA Cluster Exporter SSM 软件包的先决条件**
+ 2.3.1550.0 版或更高版本的 SSM Agent 已安装
+ 适用于 Pacemaker、Corosync、SBD 和 DRBD 的 HA 集群
+ Linux 操作系统（SUSE Linux、RedHat Linux）

**安装和配置 `AWSObservabilityExporter-HAClusterExporterInstallAndConfigure` 软件包**  
`AWSObservabilityExporter-HAClusterExporterInstallAndConfigure` 软件包是一个 SSM Distributor 软件包，您可以使用它来安装和配置 Prometheus HA Cluster Exporter。当 Prometheus HANA Database Exporter 发送集群指标时，就可以配置 CloudWatch 代理来检索 CloudWatch 服务的指标。

1. 在 [SSM Parameter Store](https://console.aws.amazon.com/systems-manager/parameters) 中创建 SSM 参数，以 JSON 格式存储该 Exporter 的配置。以下为示例参数值。

   ```
   {\"port\":\"9664\",\"address\":\"0.0.0.0\",\"log-level\":\"info\",\"crm-mon-path\":\"/usr/sbin/crm_mon\",\"cibadmin-path\":\"/usr/sbin/cibadmin\",\"corosync-cfgtoolpath-path\":\"/usr/sbin/corosync-cfgtool\",\"corosync-quorumtool-path\":\"/usr/sbin/corosync-quorumtool\",\"sbd-path\":\"/usr/sbin/sbd\",\"sbd-config-path\":\"/etc/sysconfig/sbd\",\"drbdsetup-path\":\"/sbin/drbdsetup\",\"enable-timestamps\":false}
   ```

   有关该 Exporter 配置的更多信息，请参阅 GitHub 上的 [https://github.com/ClusterLabs/ha_cluster_exporter/blob/master/ha_cluster_exporter.yaml](https://github.com/ClusterLabs/ha_cluster_exporter/blob/master/ha_cluster_exporter.yaml) 存储库。

1. 导航到 [SSM Distributor](https://console.aws.amazon.com/systems-manager/distributor) 控制台，然后打开 **Owned by Amazon**（Amazon 所拥有）选项卡。依次选择 **AWSObservabilityExporter-HAClusterExporterInstallAndConfigure\$1** 和 **Install one time**（一次性安装）。

1. 通过将“Additional Arguments（其他实际参数）”替换为以下内容来更新您在第一步中创建的 SSM 参数：

   ```
   {
     "SSM_EXPORTER_CONFIG": "{{ssm:<*SSM_CONFIGURATIONS_PARAMETER_STORE_NAME>*}}"
   }
   ```

1. 选择带有 SAP HANA 数据库的 Amazon EC2 实例，然后选择 **Run**（运行）。

## `AWSObservabilityExporter-SAP-SAPHostExporterInstallAndConfigure`
<a name="appinsights-ssm-sap-host-exporter"></a>

您可以从 [Prometheus SAP 主机导出器](https://prometheus.io/docs/instrumenting/exporters/#third-party-exporters)中检索特定于工作负载的 SAP NetWeaver 指标，以便 Application Insights 为 SAP NetWeaver 分布式和高可用性部署配置和监控告警。

要使用 [AWS Systems Manager Distributor](https://docs.aws.amazon.com/systems-manager/latest/userguide/distributor.html) 来打包、安装和配置 SAP 主机导出器软件包（独立于 Application Insights），请完成以下步骤。

**使用 Prometheus SAP 主机导出器 SSM 软件包的先决条件**
+ 2.3.1550.0 版或更高版本的 SSM Agent 已安装
+ SAP NetWeaver 应用程序服务器
+ Linux 操作系统（SUSE Linux、RedHat Linux）

**安装和配置 `AWSObservabilityExporter-SAP-SAPHostExporterInstallAndConfigure` 软件包**  
`AWSObservabilityExporter-SAP-SAPHostExporterInstallAndConfigure` 软件包是一个 SSM Distributor 软件包，您可以使用它来安装和配置 SAP NetWeaver Prometheus 指标导出器。当 Prometheus 导出器发送 SAP NetWeaver 指标时，可以配置 CloudWatch 代理来检索 CloudWatch 服务的指标。

1. 在 [SSM Parameter Store](https://console.aws.amazon.com/systems-manager/parameters) 中创建 SSM 参数，以 JSON 格式存储该 Exporter 的配置。以下为示例参数值。

   ```
   {\"address\":\"0.0.0.0\",\"port\":\"9680\",\"log-level\":\"info\",\"is-HA\":false}
   ```
   + **address**

     发送 Prometheus 指标的目标地址。默认值为 `localhost`。
   + **port**

     发送 Prometheus 指标的目标端口。默认值为 `9680`。
   + **is-HA**

     对于 SAP NetWeaver 高可用性部署，其值为 `true`。对于所有其他部署，其值为 `false`。

1. 导航到 [SSM Distributor](https://console.aws.amazon.com/systems-manager/distributor) 控制台，然后打开 **Owned by Amazon**（Amazon 所拥有）选项卡。选择 **AWSObservabilityExporter-SAP-SAPHostExporterInstallAndConfigure**，然后选择 **Install one time**（安装一次）。

1. 通过将“Additional Arguments（其他实际参数）”替换为以下内容来更新您在第一步中创建的 SSM 参数：

   ```
   {
     "SSM_EXPORTER_CONFIG": "{{ssm:<SSM_CONFIGURATIONS_PARAMETER_STORE_NAME>}}",
     "SSM_SID": "<SAP_DATABASE_SID>",
     "SSM_INSTANCES_NUM": "<instances_number seperated by comma>"
   }
   ```

   **示例**

   ```
   {
     "SSM_EXPORTER_CONFIG": "{{ssm:exporter_config_paramter}}",
     "SSM_INSTANCES_NUM": "11,12,10",
     "SSM_SID": "PR1"
   }
   ```

1. 选择带有 SAP NetWeaver 应用程序的 Amazon EC2 实例，然后选择 **Run**（运行）。

**注意**  
Prometheus 导出器在本地端点上维护 SAP NetWeaver 指标。只有 Amazon EC2 实例上的操作系统用户才能访问本地端点。因此，在安装导出器软件包后，所有操作系统用户都可以使用这些指标。默认的本地端点是 `localhost:9680/metrics`。

## `AWSObservabilityExporter-SQLExporterInstallAndConfigure`
<a name="appinsights-ssm-sql-prometheus"></a>

您可以从 [Prometheus SQL 导出器](https://prometheus.io/docs/instrumenting/exporters/#third-party-exporters)中检索工作负载特定的 SQL Server 指标，以供 Application Insights 监控关键指标。

要使用 [AWS Systems Manager Distributor](https://docs.aws.amazon.com/systems-manager/latest/userguide/distributor.html) 来打包、安装和配置 SQL 导出器软件包（独立于 Application Insights），请完成以下步骤。

**使用 Prometheus SQL 导出器 SSM 软件包的先决条件**
+ 2.3.1550.0 版或更高版本的 SSM Agent 已安装
+ 在启用了 SQL Server 用户身份验证的 Windows 上运行 SQL Server 的 Amazon EC2 实例。
+ 具有以下权限的 SQL Server 用户：

  ```
  GRANT VIEW ANY DEFINITION TO
  ```

  ```
  GRANT VIEW SERVER STATE TO
  ```
+ 包含使用 AWS Secrets Manager 的数据库连接字符串的秘密。有关如何创建密钥的更多信息，请参阅 *AWS Secrets Manager 用户指南*中的[创建密钥](https://docs.aws.amazon.com/secretsmanager/latest/userguide/manage_create-basic-secret.html)。密钥必须采用以下格式：

  ```
  {
    "data_source_name":"sqlserver://<username>:<password>@localhost:1433"
  }
  ```
**注意**  
如果密码或用户名包含特殊字符，则必须对特殊字符进行百分号编码，以确保成功连接到数据库。

**安装和配置 `AWSObservabilityExporter-SQLExporterInstallAndConfigure` 软件包**  
`AWSObservabilityExporter-SQLExporterInstallAndConfigure` 软件包是一个 SSM Distributor 软件包，您可以使用它来安装和配置 SQL Prometheus 指标导出器。当 Prometheus 导出器发送 Java 指标时，可以配置 CloudWatch 代理来检索 CloudWatch 服务的指标。

1. 根据您的偏好，准备 SQL 导出器 YAML 配置。以下示例配置配置了一项指标。使用[示例配置](https://github.com/burningalchemist/sql_exporter/blob/master/examples/sql_exporter.yml)借助其他指标更新配置或创建自己的配置。

   ```
   ---
   global:
     scrape_timeout_offset: 500ms
     min_interval: 0s
     max_connections: 3
     max_idle_connections: 3
   target:
     aws_secret_name: <SECRET_NAME>
     collectors:
       - mssql_standard
   collectors:
     - collector_name: mssql_standard
       metrics: 
       - metric_name: mssql_batch_requests
         type: counter
         help: 'Number of command batches received.'
         values: [cntr_value]
         query: |
           SELECT cntr_value
           FROM sys.dm_os_performance_counters WITH (NOLOCK)
           WHERE counter_name = 'Batch Requests/sec'
   ```

1. 将编码为 Base64 的 Prometheus SQL 导出器 YAML 配置文件复制到 [SSM Parameter Store](https://console.aws.amazon.com/systems-manager/parameters) 中的新 SSM 参数。

1. 导航到 [SSM Distributor](https://console.aws.amazon.com/systems-manager/distributor) 控制台，然后打开 **Owned by Amazon**（Amazon 所拥有）选项卡。选择 **AWSObservabilityExporter-SQLExporterInstallAndConfigure**，然后选择**一次性安装**。

1. 将“其他参数”替换为以下信息。`SSM_PARAMETER_NAME` 是您在步骤 2 中创建的参数的名称。

   ```
   {
     "SSM_EXPORTER_CONFIGURATION": 
       "{{ssm:<SSM_PARAMETER_STORE_NAME>}}",
       "SSM_PROMETHEUS_PORT": "9399",
       "SSM_WORKLOAD_NAME": "SQL"                         
   }
   ```

1. 选择包含 SQL Server 数据库的 Amazon EC2 实例，然后选择运行。

# CloudWatch Application Insights 使用的 AWS Systems Manager（SSM）文档
<a name="appinsights-ssm-documents"></a>

Application Insights 使用本节中列出的 SSM 文档来定义 AWS Systems Manager 对托管实例执行的操作。这些文档使用 Systems Manager 的 `Run Command` 功能来自动完成执行 Application Insights 监控功能所需的任务。这些文档的运行时间表由 Application Insights 维护，无法更改。

有关 SSM 文档的更多信息，请参阅《AWS Systems Manager 用户指南》**中的 [AWS Systems Manager 文档](https://docs.aws.amazon.com/systems-manager/latest/userguide/documents.html)。

## 由 CloudWatch Application Insights 管理的文档
<a name="ssm-documents-appinsights-managed"></a>

下表列出了由 Application Insights 管理的 SSM 文档。


| 文档名称 | 说明 | 运行时间表 | 
| --- | --- | --- | 
|  `AWSEC2-DetectWorkload`  |  自动检测在您的应用程序环境中运行的应用程序，这些应用程序可以设置为由 Application Insights 监控。  |  本文档每小时在您的应用程序环境中运行一次，以获取最新的应用程序详细信息。  | 
|  `AWSEC2-CheckPerformanceCounterSets`  |  检查您的 Amazon EC2 Windows 实例上是否启用了性能计数器命名空间。  |  本文档在您的应用程序环境中每小时运行一次，并且仅在启用了相应的命名空间时才监控性能计数器指标。  | 
|  `AWSEC2-ApplicationInsightsCloudwatchAgentInstallAndConfigure`  |  根据您的应用程序组件的监控配置来安装和配置 CloudWatch 代理。  |  本文档每 30 分钟运行一次，以确保 CloudWatch 代理配置始终是准确和最新的。在更改应用程序监控设置（例如添加或移除指标或更新日志配置）后，该文档也会立即运行。  | 

## 由 AWS Systems Manager 管理的文档
<a name="ssm-documents-aws-managed"></a>

以下文档由 CloudWatch Application Insights 使用，并由 Systems Manager 管理。

**`AWS-ConfigureAWSPackage`**  
Application Insights 使用此文档来安装和卸载 Prometheus 导出程序分发服务器软件包，收集特定于工作负载的指标，并全面监控客户 Amazon EC2 实例上的工作负载。只有在您的实例上运行相关的目标工作负载时，CloudWatch Application Insights 才会安装 Prometheus 导出程序分发服务器软件包。

下表列出了 Prometheus 导出程序分发服务器软件包和相关的目标工作负载。


| Prometheus 导出程序分发服务器软件包名称 | 目标工作负载 | 
| --- | --- | 
|  `AWSObservabilityExporter-HAClusterExporterInstallAndConfigure`  |  SAP HANA HA  | 
|  `AWSObservabilityExporter-JMXExporterInstallAndConfigure`  |  Java/JMX  | 
|  `AWSObservabilityExporter-SAP-HANADBExporterInstallAndConfigure`  |  SAP HANA  | 
|  `AWSObservabilityExporter-SAP-SAPHostExporterInstallAndConfigure`  |  NetWeaver  | 
|  `AWSObservabilityExporter-SQLExporterInstallAndConfigure`  |  SQL Server（Windows）和 SAP ASE（Linux）  | 

**`AmazonCloudWatch-ManageAgent`**  
Application Insights 使用此文档来管理您的实例上的 CloudWatch 代理的状态和配置，并跨操作系统从 Amazon EC2 实例收集内部系统级指标和日志。

# 访问 CloudWatch Application Insights 所需的先决条件、IAM 策略和权限
<a name="appinsights-accessing"></a>

要开始使用 CloudWatch Application Insights，请验证您已满足以下先决条件、已创建 IAM 策略并已连接权限（如果需要）。

**Topics**
+ [配置应用程序进行监控的先决条件](appinsights-prereqs.md)
+ [CloudWatch Application Insights 的 IAM 策略](appinsights-iam.md)
+ [基于账户的应用程序载入的 IAM 角色权限](appinsights-account-based-onboarding-permissions.md)

# 配置应用程序进行监控的先决条件
<a name="appinsights-prereqs"></a>

您必须完成以下必需任务才能使用 CloudWatch Application Insights 配置应用程序：
+ **AWS Systems Manager 启用** – 在 Amazon EC2 实例上安装 Systems Manager Agent（SSM Agent），并启用 SSM 实例。有关如何安装 SSM Agent 的信息，请参阅《AWS Systems Manager 用户指南》中的[设置 AWS Systems Manager](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-setting-up.html)**。
+ **EC2 实例角色** – 您必须附加以下 Amazon EC2 实例角色，才能启用 Systems Manager
  + 要启用 Systems Manager，您必须附加 `AmazonSSMManagedInstanceCore` 角色。有关更多信息，请参阅 [AWS Systems Manager 基于身份的策略示例](https://docs.aws.amazon.com/systems-manager/latest/userguide/auth-and-access-control-iam-identity-based-access-control.html)。
  + 要使实例指标和日志通过 CloudWatch 发出，您必须附加 `CloudWatchAgentServerPolicy` 策略。有关更多信息，请参阅[创建用于 CloudWatch 代理的 IAM 角色和用户](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/create-iam-roles-for-cloudwatch-agent.html)
+ **AWS Resource Groups** – 要将应用程序添加到 CloudWatch Application Insights，请创建一个包含应用程序堆栈所用的所有相关 AWS 资源的资源组。这包括应用程序负载均衡器、运行 IIS 和 Web 前端的 Amazon EC2 实例、.NET 工作线程层和 SQL Server 数据库。有关 Application Insights 支持的应用程序组件和技术堆栈的更多信息，请参阅 [支持的应用程序组件](appinsights-what-is.md#appinsights-components)。CloudWatch Application Insights 自动包含使用与资源组相同的标签或 CloudFormation 堆栈的自动扩缩组，因为 CloudFormation 资源组不支持自动扩缩组。有关更多信息，请参阅 [AWS Resource Groups 入门](https://docs.aws.amazon.com/ARG/latest/userguide/gettingstarted.html)。
+ **IAM 权限** – 对于没有管理访问权限的用户，必须创建允许 Application Insights 创建服务相关角色的 AWS Identity and Access Management（IAM）policy，并将其附加到用户身份。有关如何创建 IAM policy 的更多信息，请参阅 [CloudWatch Application Insights 的 IAM 策略](appinsights-iam.md)。
+ **服务相关角色** – Application Insights 使用 AWS Identity and Access Management（IAM）服务相关角色。当您在 Application Insights 控制台中创建首个 Application Insights 应用程序时，将会为您创建服务相关角色。有关更多信息，请参阅 [在 CloudWatch Application Insights 中使用服务相关角色](CHAP_using-service-linked-roles-appinsights.md)。
+ **EC2 Windows 实例对性能计数器指标的支持** – 要在 Amazon EC2 Windows 实例上监控性能计数器指标，必须在实例上安装性能计数器。有关性能计数器指标和相应的性能计数器集名称，请参阅[性能计数器指标](application-insights-performance-counter.md)。有关性能计数器的更多信息，请参阅[性能计数器](https://docs.microsoft.com/en-us/windows/win32/perfctrs/performance-counters-portal)。
+ **Amazon CloudWatch 代理** – Application Insights 安装和配置 CloudWatch 代理。如果您安装了 CloudWatch 代理，则 Application Insights 会保留您的配置。为避免合并冲突，请从现有 CloudWatch 代理配置文件中删除您想在 Application Insights 中使用的资源的配置。有关更多信息，请参阅 [手动创建或编辑 CloudWatch 代理配置文件](CloudWatch-Agent-Configuration-File-Details.md)。

# CloudWatch Application Insights 的 IAM 策略
<a name="appinsights-iam"></a>

要使用 CloudWatch Application Insights，您必须创建一个 [AWS Identity and Access Management（IAM）policy](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html)，并将其附加到您的用户、组或角色。有关用户、组和角色的更多信息，请参阅 [IAM 身份（用户、用户组和角色）](https://docs.aws.amazon.com/IAM/latest/UserGuide/id.html)。IAM policy 定义了用户权限。

**使用控制台创建 IAM policy**  
要使用 IAM 控制台创建 IAM policy，请执行以下步骤。

1. 转到 [IAM 控制台](https://console.aws.amazon.com/iam/home)。在左侧导航窗格中，选择**策略**。

1. 在页面顶部，选择**创建策略**。

1. 选择 **JSON** 选项卡。

1. 在 **JSON** 选项卡下面复制并粘贴以下 JSON 文档。

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Action": [
                   "applicationinsights:*",
                   "iam:CreateServiceLinkedRole",
                   "iam:ListRoles",
                   "resource-groups:ListGroups"
               ],
               "Effect": "Allow",
               "Resource": "*"
           }
       ]
   }
   ```

------

1. 选择**查看策略**。

1. 输入策略的**名称**，例如“AppInsightsPolicy”。（可选）输入**描述**。

1. 选择 **Create Policy (创建策略)**。

1. 在左侧的导航窗格中，选择**用户组**、**用户**或**角色**。

1. 选择要附加策略的用户组、用户或角色的名称。

1. 选择**添加权限**。

1. 选择 **Attach existing policies directly**（直接附加现有策略）。

1. 搜索刚创建的策略，然后选中策略名称左侧的复选框。

1. 选择**下一步: 审核**。

1. 确保列出了正确的策略，然后选择**添加权限**。

1. 在使用 CloudWatch Application Insights 时，请确保使用与刚创建的策略关联的用户登录。

**使用 AWS CLI 创建 IAM policy**  
要使用 AWS CLI 创建 IAM policy，请使用上面的 JSON 文档作为当前文件夹中的文件，从命令行运行 [create-policy](https://docs.aws.amazon.com/cli/latest/reference/iam/create-policy.html) 操作。

**使用 AWS Tools for Windows PowerShell 创建 IAM policy**  
要使用 AWS Tools for Windows PowerShell 创建 IAM policy，请使用上面的 JSON 文档作为当前文件夹中的文件，运行 [New-IAMPolicy](https://docs.aws.amazon.com/powershell/latest/reference/items/New-IAMPolicy.html) cmdlt。

# 基于账户的应用程序载入的 IAM 角色权限
<a name="appinsights-account-based-onboarding-permissions"></a>

如果您想载入账户中的所有资源，并选择不使用 [Application Insights 托管式策略](security-iam-awsmanpol-appinsights.md)来完全访问 Application Insights 功能，则必须向 IAM 角色附加以下权限，以便 Application Insights 可以发现您账户中的所有资源：

```
"ec2:DescribeInstances" 
"ec2:DescribeNatGateways"
"ec2:DescribeVolumes"
"ec2:DescribeVPCs"
"rds:DescribeDBInstances"
"rds:DescribeDBClusters"
"sqs:ListQueues"
"elasticloadbalancing:DescribeLoadBalancers"
"autoscaling:DescribeAutoScalingGroups"
"lambda:ListFunctions"
"dynamodb:ListTables"
"s3:ListAllMyBuckets"
"sns:ListTopics"
"states:ListStateMachines"
"apigateway:GET"
"ecs:ListClusters"
"ecs:DescribeTaskDefinition" 
"ecs:ListServices"
"ecs:ListTasks"
"eks:ListClusters"
"eks:ListNodegroups"
"fsx:DescribeFileSystems"
"route53:ListHealthChecks"
"route53:ListHostedZones"
"route53:ListQueryLoggingConfigs"
"route53resolver:ListFirewallRuleGroups"
"route53resolver:ListFirewallRuleGroupAssociations"
"route53resolver:ListResolverEndpoints"
"route53resolver:ListResolverQueryLogConfigs"
"route53resolver:ListResolverQueryLogConfigAssociations"
"logs:DescribeLogGroups"
"resource-explorer:ListResources"
```

# 使用 AWS 管理控制台设置应用程序以进行监控
<a name="appinsights-setting-up"></a>

本节提供使用控制台、AWS CLI 和 AWS Tools for Windows PowerShell 来设置、配置和管理 CloudWatch Application Insights 应用程序的步骤。

**Topics**
+ [控制台步骤](appinsights-setting-up-console.md)
+ [命令行步骤](appinsights-setting-up-command.md)
+ [Events](appinsights-cloudwatch-events.md)
+ [通知](appinsights-problem-notifications.md)

# 设置、配置和管理您的应用程序以从 CloudWatch 控制台进行监控
<a name="appinsights-setting-up-console"></a>

本节提供设置、配置和管理应用程序以从 CloudWatch 控制台进行监控的步骤。

**Topics**
+ [添加和配置应用程序](#appinsights-add-configure)
+ [为 Amazon ECS 和 Amazon EKS 资源监控启用 Application Insights](#appinsights-container-insights)
+ [为应用程序组件禁用监控](#appinsights-disable-monitoring)
+ [删除应用程序](#appinsights-delete-app)

## 添加和配置应用程序
<a name="appinsights-add-configure"></a>

**从 CloudWatch 控制台添加和配置应用程序**  
要通过 CloudWatch 控制台开始使用 CloudWatch Application Insights，请执行以下步骤。

1. **开始。**打开 [CloudWatch 控制台登陆页面](https://console.aws.amazon.com/cloudwatch)。从左侧导航窗格中，选择 **Insights** 下的 **Application Insights**。所打开的页面将显示使用 CloudWatch Application Insights 监控的应用程序列表及它们的监控状态。

1. **添加应用程序。**要为应用程序设置监控，请选择 **Add an application**（添加应用程序）。在选择 **Add an application**（添加应用程序）时，系统会提示您 **Choose Application Type**（选择应用程序类型）。
   + **基于资源组的应用程序**。选择此选项后，您可以选择此账户中要监控的资源组。要在一个组件上使用多个应用程序，您必须使用基于资源组的监控。
   + **基于账户的应用程序**。选择此选项后，您可以监控此账户中的所有资源。如果您想监控账户中的所有资源，我们建议使用此选项而不是基于资源组的选项，因为应用程序载入过程更快。
**注意**  
不能使用 Application Insights 将基于资源组的监控与基于账户的监控相结合。要更改应用程序类型，必须删除所有正在监控之下的应用程序，并 **Choose Application Type**（选择应用程序类型）。

   当您添加第一个应用程序以进行监控时，CloudWatch Application Insights 会在账户中创建服务相关角色，该角色授予 Application Insights 代表您调用其他 AWS 服务的权限。有关 Application Insights 在您的账户中创建的服务相关角色的更多信息，请参阅 [在 CloudWatch Application Insights 中使用服务相关角色](CHAP_using-service-linked-roles-appinsights.md)。

1. 

------
#### [ Resource-based application monitoring ]

   1. **选择应用程序或资源组。**在 **Specify application details**（指定应用程序详细信息）页面上，从下拉列表中选择包含您应用程序资源的 AWS 资源组。这些资源包括前端服务器、负载均衡器、Auto Scaling 组和数据库服务器。

      如果还没有为应用程序创建资源组，则可以选择 **Create new resource group**（创建新资源组）来创建一个资源组。有关创建资源组的详细信息，请参阅 [https://docs.aws.amazon.com/ARG/latest/userguide/welcome.html](https://docs.aws.amazon.com/ARG/latest/userguide/welcome.html)。

   1. **问题见解通知。**要在检测到所选应用程序出现问题时查看问题并获得通知，请选择“Amazon SNS 通知”或“Systems Manager OpsCenter Opsitems”。

      1. **设置 Amazon SNS 通知（推荐）。**选择**选择现有主题**或**创建新主题**。

      1. **与 AWS Systems Manager OpsCenter 集成。**在**高级设置**下，选中**生成 Systems Manager OpsCenter OpsItems 以采取补救措施**复选框。要跟踪用于解析与 AWS 资源相关的操作工作项（OpsItem）的操作，请提供 Amazon SNS 主题 ARN。

   1. **监控 CloudWatch Events**。选中复选框以将 Application Insights 监控与 CloudWatch Events 集成，获取 Amazon EBS、Amazon EC2、AWS CodeDeploy、Amazon ECS、AWS Health API 和通知、Amazon RDS、Amazon S3 和 AWS Step Functions 中的洞察。

   1. **标签（可选）**。CloudWatch Application Insights 支持基于标签和基于 CloudFormation 的资源组（Auto Scaling 组除外）。有关更多信息，请参阅[使用标签编辑器](https://docs.aws.amazon.com/ARG/latest/userguide/tag-editor.html)。

   1. 选择**下一步**。

      将按以下格式为应用程序生成 [ARN](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html)：

      ```
      arn:partition:applicationinsights:region:account-id:application/resource-group/resource-group-name
      ```

      示例

      ```
      arn:aws:applicationinsights:us-east-1:123456789012:application/resource-group/my-resource-group
      ```

   1. 在**查看检测到的组件**页面的**查看要监控的组件**下，表列出了检测到的组件及其关联的检测到的工作负载。
**注意**  
对于支持多个自定义工作负载的组件，每个组件最多可以监控五个工作负载。这些工作负载将与组件分开监控。  
![\[CloudWatch Application Insights 控制台的“检测到的组件”部分：检测到的组件和关联的工作负载概述。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/appinsights-multiapp-review-component.png)

      在**关联的工作负载**下，如果未列出工作负载，则会显示几条可能的消息。
      + **无法检测工作负载** – 尝试检测工作负载时出现问题。确保您已完成 [配置应用程序进行监控的先决条件](appinsights-prereqs.md)。如果需要添加工作负载，请选择**编辑组件**。
      + **未检测到工作负载** – 我们未检测到任何工作负载。您可能需要添加工作负载。为此，请选择**编辑组件**。
      + **不适用** — 组件不支持自定义工作负载，将使用默认指标、警报和日志进行监控。您不能向这些组件添加工作负载。

   1. 要编辑组件，请选择一个组件，然后选择**编辑组件**。侧面板打开，显示在组件上检测到的工作负载。在此面板中，您可以编辑组件详细信息并添加新的工作负载。  
![\[CloudWatch Application Insights 控制台的“查看检测到的组件”部分：可以编辑关联的工作负载。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/appinsights-multiapp-edit-component.png)
      + 如需编辑工作负载类型或名称，请使用下拉列表。  
![\[CloudWatch Application Insights 控制台的“编辑组件”部分：工作负载类型的下拉列表。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/appinsights-multiapp-edit-name-type.png)
      + 要向组件添加工作负载，请选择**添加新的工作负载**。  
![\[CloudWatch Application Insights 控制台的“编辑组件”部分：用于添加新工作负载的左下角按钮。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/appinsights-multiapp-add-workload.png)
        + 如果未出现**添加新工作负载**，则此组件不支持多个工作负载。
        + 如果未出现**关联工作负载**标题，则此组件不支持自定义的工作负载。
      + 要删除工作负载，请选择要从监控中删除的工作负载旁边的**删除**。  
![\[CloudWatch Application Insights 控制台的“编辑组件”部分：删除工作负载。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/appinsights-multiapp-remove-workload.png)
      + 要禁用对整个组件的监控，请清除**监控**复选框。  
![\[CloudWatch Application Insights 复选框的“编辑组件”部分用于禁用监控。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/appinsights-multiapp-disable-monitoring.png)
      + 编辑完组件后，选择右下角的**保存更改**。组件工作负载的任何更改都将显示在**关联的工作负载**下的**查看要监控的组件**表中。

   1. 在**查看检测到的组件**页面上，选择**下一步**。

   1. **指定组件详细信息**页面包含上一步中具有可自定义关联工作负载的所有组件。
**注意**  
如果组件标题具有*可选*标签，则该组件中工作负载的其他详细信息是可选的。

      如果某个组件未出现在此页面上，则该组件没有任何可在此步骤中指定的其他详细信息。

   1. 选择**下一步**。

   1. 在**查看并提交**页面上，查看所有受监控的组件和工作负载详细信息。

   1. 选择**提交**。

------
#### [ Account-based application monitoring ]

   1. **应用程序名称**。为基于账户的应用程序输入名称。

   1. **自动监控新资源**。默认情况下，Application Insights 使用推荐的设置来配置对载入应用程序后添加到账户的资源组件的监控。通过清除复选框，可以排除对载入应用程序后添加的资源的监控。

   1. **监控 CloudWatch Events**。选中复选框以将 Application Insights 监控与 CloudWatch Events 集成，获取 Amazon EBS、Amazon EC2、AWS CodeDeploy、Amazon ECS、AWS Health API 和通知、Amazon RDS、Amazon S3 和 AWS Step Functions 中的洞察。

   1. **与 AWS Systems Manager OpsCenter 集成。**要在检测到所选应用程序的问题时查看问题并获得通知，请选中 **Generate Systems Manager OpsCenter OpsItems for remedial actions**（生成 Systems Manager OpsCenter OpsItems 以采取修复措施）复选框。要跟踪用于解析与 AWS 资源相关的操作工作项 (OpsItem) 的操作，请提供 SNS 主题 ARN。

   1. **标签（可选）**。CloudWatch Application Insights 支持基于标签和基于 CloudFormation 的资源组（Auto Scaling 组除外）。有关更多信息，请参阅[使用标签编辑器](https://docs.aws.amazon.com/ARG/latest/userguide/tag-editor.html)。

   1. **发现的资源**。在您的账户中发现的所有资源都会添加到此列表中。如果 Application Insights 无法发现您账户中的所有资源，则会在页面顶部显示一条错误消息。此消息中包含一个指向[有关如何添加所需权限的文档](appinsights-account-based-onboarding-permissions.md)的链接。

   1. 选择**下一步**。

      将按以下格式为应用程序生成 [ARN](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html)：

      ```
      arn:partition:applicationinsights:region:account-id:application/TBD/application-name
      ```

      示例

      ```
      arn:aws:applicationinsights:us-east-1:123456789012:application/TBD/my-application
      ```

------

1. 提交应用程序监控配置后，您将转到应用程序的详细信息页面，您可以在该页面查看 **Application summary**（应用程序摘要）、**Monitored components**（已监控组件）的列表和 **Unmonitored components**（未监控组件）的列表，并通过选择 **Components**（组件）旁边的选项卡，查看 **Configuration history**（配置历史记录）、**Log patterns**（日志模式）和您已应用的任何 **Tags**（标签）。

   要查看关于应用程序的洞察，请选择 **View Insights**（查看洞察）。

   通过选择 **Edit**（编辑），您可以更新 CloudWatch Events 监控的选项以及与 AWS Systems Manager OpsCenter 的集成。

   在 **Components**（组件）下，您可以选择 **Actions**（操作）菜单来创建、修改或取消分组实例组。

   您可以通过选择组件旁边的项目符号并选择 **Manage monitoring**（管理监控）来管理组件的监控，包括应用程序层、日志组、事件日志、指标和自定义告警。

## 为 Amazon ECS 和 Amazon EKS 资源监控启用 Application Insights
<a name="appinsights-container-insights"></a>

您可以启用 Application Insights，以从 Container Insights 控制台监控容器化应用程序和微服务。Application Insights 支持监控以下资源：
+ Amazon ECS 集群
+ Amazon ECS 服务
+ Amazon ECS 任务
+ Amazon EKS 集群

启用 Application Insights 后，它会提供建议的指标和日志，检测潜在问题，生成 CloudWatch Events，以及为容器化应用程序和微服务创建自动控制面板。

您可以从 Container Insights 或 Application Insights 控制台为容器化资源启用 Application Insights。

**从 Container Insights 控制台启用 Application Insights**  
在 Container Insights 控制台中的 Container Insights **Performance monitoring**（性能监控）控制面板上，选择 **Auto-configure Application Insights**（自动配置 Application Insights）。启用 Application Insights 后，它会显示有关检测到的问题的详细信息。

**从 Application Insights 控制台启用 Application Insights**  
当组件列表中出现 ECS 集群时，Application Insights 会自动使用 Container Insights 启用其他容器监控。

对于 EKS 集群，您可以通过 Container Insights 启用其他监控，提供诊断信息（如容器重启失败），以帮助您查明问题并解决问题。要为 EKS 设置 Container Insights，还需要执行其他步骤。有关详细信息，请参阅 [在 Amazon EKS 和 Kubernetes 上设置 Container Insights](deploy-container-insights-EKS.md) 了解在 EKS 上设置 Container Insights 的步骤。

使用 EKS 的 Linux 实例支持使用 Container Insights 对 EKS 进行额外监控。

有关对 ECS 和 EKS 集群的 Container Insights 支持的更多信息，请参阅 [Container Insights](ContainerInsights.md)。

## 为应用程序组件禁用监控
<a name="appinsights-disable-monitoring"></a>

要为应用程序组件禁用监控，请从应用程序详细信息页面中选择要禁用监控的组件。选择 **Actions**（操作），然后 **Remove from monitoring**（取消监控）。

## 删除应用程序
<a name="appinsights-delete-app"></a>

要删除应用程序，请在 CloudWatch 控制面板中的左侧导航窗格中选择 **Insights** 下方的 **Application Insights**。选择要删除的应用程序。在 **Actions**（操作）下选择 **Delete application**（删除应用程序）。这会删除监控，并删除为应用程序组件保存的所有监视器。不会删除应用程序资源。

# 使用命令行设置、配置和管理您的应用程序以进行监控
<a name="appinsights-setting-up-command"></a>

本节提供设置、配置和管理应用程序以使用 AWS CLI 和 AWS Tools for Windows PowerShell 进行监控的步骤。

**Topics**
+ [添加和管理应用程序](#appinsights-config-app-command)
+ [管理和更新监控](#appinsights-monitoring)
+ [针对 SQL Always On 可用性组配置监控](#configure-sql)
+ [为 MySQL RDS 配置监控](#configure-mysql-rds)
+ [为 MySQL EC2 配置监控](#configure-mysql-ec2)
+ [为 PostgreSQL RDS 配置监控](#configure-postgresql-rds)
+ [为 PostgreSQL EC2 配置监控](#configure-postgresql-ec2)
+ [为 Oracle RDS 配置监控](#configure-oracle-rds)
+ [为 Oracle EC2 配置监控](#configure-oracle-ec2)

## 添加和管理应用程序
<a name="appinsights-config-app-command"></a>

您可以使用命令行添加、管理和配置 Application Insights 应用程序以及获取有关它的信息。

**Topics**
+ [添加应用程序](#appinsights-add-app)
+ [描述应用程序](#appinsights-describe-app)
+ [列出应用程序中的组件](#appinsights-list-components)
+ [描述组件](#appinsights-describe-components)
+ [将类似资源分组到自定义组件中](#appinsights-group-resources-components)
+ [对自定义组件取消分组](#appinsights-ungroup-resources-components)
+ [更新 应用程序](#appinsights-update-app)
+ [更新自定义组件](#appinsights-update-component)

### 添加应用程序
<a name="appinsights-add-app"></a>

**使用 AWS CLI 添加应用程序**  
要使用 AWS CLI 为名为 `my-resource-group` 的资源组添加应用程序，并启用 OpsCenter 以将创建的 opsItem 传递到 SNS 主题 ARN ` arn:aws:sns:us-east-1:123456789012:MyTopic`，请使用以下命令。

```
aws application-insights create-application --resource-group-name my-resource-group --ops-center-enabled --ops-item-sns-topic-arn arn:aws:sns:us-east-1:123456789012:MyTopic
```

**使用 AWS Tools for Windows PowerShell 添加应用程序**  
要使用 AWS Tools for Windows PowerShell 为名为 `my-resource-group` 的资源组添加应用程序，并启用 OpsCenter 以将创建的 opsItem 传递到 SNS 主题 ARN `arn:aws:sns:us-east-1:123456789012:MyTopic`，请使用以下命令。

```
New-CWAIApplication -ResourceGroupName my-resource-group -OpsCenterEnabled true -OpsItemSNSTopicArn arn:aws:sns:us-east-1:123456789012:MyTopic
```

### 描述应用程序
<a name="appinsights-describe-app"></a>

**使用 AWS CLI 描述应用程序**  
要使用 AWS CLI 描述在名为 `my-resource-group` 的资源组上创建的应用程序，请使用以下命令。

```
aws application-insights describe-application --resource-group-name my-resource-group
```

**使用 AWS Tools for Windows PowerShell 描述应用程序**  
要使用 AWS Tools for Windows PowerShell 描述在名为 `my-resource-group` 的资源组上创建的应用程序，请使用以下命令。

```
Get-CWAIApplication -ResourceGroupName my-resource-group
```

### 列出应用程序中的组件
<a name="appinsights-list-components"></a>

**使用 AWS CLI 列出应用程序中的组件**  
要使用 AWS CLI 列出在名为 `my-resource-group` 的资源组上创建的组件，请使用以下命令。

```
aws application-insights list-components --resource-group-name my-resource-group
```

**使用 AWS Tools for Windows PowerShell 列出应用程序中的组件**  
要使用 AWS Tools for Windows PowerShell 列出在名为 `my-resource-group` 的资源组上创建的组件，请使用以下命令。

```
Get-CWAIComponentList -ResourceGroupName my-resource-group
```

### 描述组件
<a name="appinsights-describe-components"></a>

**使用 AWS CLI 描述组件**  
您可以使用以下 AWS CLI 命令描述属于在名为 `my-resource-group` 的资源组上创建的应用程序且名为 `my-component` 的组件。

```
aws application-insights describe-component --resource-group-name my-resource-group --component-name my-component
```

**使用 AWS Tools for Windows PowerShell 描述组件**  
您可以使用以下 AWS Tools for Windows PowerShell 命令描述属于在名为 `my-resource-group` 的资源组上创建的应用程序且名为 `my-component` 的组件。

```
Get-CWAIComponent -ComponentName my-component -ResourceGroupName my-resource-group
```

### 将类似资源分组到自定义组件中
<a name="appinsights-group-resources-components"></a>

我们建议将类似的资源（如 .NET Web 服务器实例）分组到自定义组件中，以便简化接入流程并获取更优质的监控与洞察效果。CloudWatch Application Insights 支持 EC2 实例的自定义组。

**使用 AWS CLI 将资源分组到自定义组件**  
要为名为 `my-resource-group` 的资源组创建的应用程序使用 AWS CLI 将三个实例（`arn:aws:ec2:us-east-1:123456789012:instance/i-11111`、`arn:aws:ec2:us-east-1:123456789012:instance/i-22222` 和 `arn:aws:ec2:us-east-1:123456789012:instance/i-33333`）一起分组到一个名为 `my-component` 的自定义组件，请使用以下命令。

```
aws application-insights create-component --resource-group-name my-resource-group --component-name my-component --resource-list arn:aws:ec2:us-east-1:123456789012:instance/i-11111 arn:aws:ec2:us-east-1:123456789012:instance/i-22222 arn:aws:ec2:us-east-1:123456789012:instance/i-33333
```

**使用 AWS Tools for Windows PowerShell 将资源分组到自定义组件**  
要为名为 `my-resource-group` 的资源组创建的应用程序使用 AWS Tools for Windows PowerShell 将三个实例（`arn:aws:ec2:us-east-1:123456789012:instance/i-11111`、`arn:aws:ec2:us-east-1:123456789012:instance/i-22222` 和 `arn:aws:ec2:us-east-1:123456789012:instance/i-33333`）一起分组到一个名为 `my-component` 的自定义组件，请使用以下命令。

```
New-CWAIComponent -ResourceGroupName my-resource-group -ComponentName my-component -ResourceList arn:aws:ec2:us-east-1:123456789012:instance/i-11111,arn:aws:ec2:us-east-1:123456789012:instance/i-22222,arn:aws:ec2:us-east-1:123456789012:instance/i-33333 
```

### 对自定义组件取消分组
<a name="appinsights-ungroup-resources-components"></a>

**使用 AWS CLI 对自定义组件取消分组**  
要使用 AWS CLI 对在资源组 `my-resource-group` 上创建的应用程序中名为 `my-component` 的自定义组件取消分组，请使用以下命令。

```
aws application-insights delete-component --resource-group-name my-resource-group --component-name my-new-component
```

**使用 AWS Tools for Windows PowerShell 对自定义组件取消分组**  
要使用 AWS Tools for Windows PowerShell 对在资源组 `my-resource-group` 上创建的应用程序中名为 `my-component` 的自定义组件取消分组，请使用以下命令。

```
Remove-CWAIComponent -ComponentName my-component -ResourceGroupName my-resource-group
```

### 更新 应用程序
<a name="appinsights-update-app"></a>

**使用 AWS CLI 更新应用程序**  
您可以使用 AWS CLI 更新应用程序，以针对在应用程序中检测到的问题生成 AWS Systems Manager OpsCenter OpsItem，并使用以下命令将创建的 OpsItem 与 SNS 主题 `arn:aws:sns:us-east-1:123456789012:MyTopic` 相关联。

```
aws application-insights update-application --resource-group-name my-resource-group --ops-center-enabled --ops-item-sns-topic-arn arn:aws:sns:us-east-1:123456789012:MyTopic
```

**使用 AWS Tools for Windows PowerShell 更新应用程序**  
您可以使用 AWS Tools for Windows PowerShell 更新应用程序，以针对在应用程序中检测到的问题生成 AWS SSM OpsCenter OpsItem，并使用以下命令将创建的 OpsItem 与 SNS 主题 `arn:aws:sns:us-east-1:123456789012:MyTopic` 相关联。

```
Update-CWAIApplication -ResourceGroupName my-resource-group -OpsCenterEnabled true -OpsItemSNSTopicArn arn:aws:sns:us-east-1:123456789012:MyTopic
```

### 更新自定义组件
<a name="appinsights-update-component"></a>

**使用 AWS CLI 更新自定义组件**  
您可以使用 AWS CLI，通过使用以下命令，使用新的组件名称 `my-new-component` 和更新的实例组来更新名为 `my-component` 的自定义组件。

```
aws application-insights update-component --resource-group-name my-resource-group --component-name my-component --new-component-name my-new-component --resource-list arn:aws:ec2:us-east-1:123456789012:instance/i-44444 arn:aws:ec2:us-east-1:123456789012:instance/i-55555
```

**使用 AWS Tools for Windows PowerShell 更新自定义组件**  
您可以使用 AWS Tools for Windows PowerShell，通过使用以下命令，使用新的组件名称 `my-new-component` 和更新的实例组来更新名为 `my-component` 的自定义组件。

```
Update-CWAIComponent -ComponentName my-component -NewComponentName my-new-component -ResourceGroupName my-resource-group -ResourceList arn:aws:ec2:us-east-1:123456789012:instance/i-44444,arn:aws:ec2:us-east-1:123456789012:instance/i-55555
```

## 管理和更新监控
<a name="appinsights-monitoring"></a>

您可以使用命令行管理和更新针对 Application Insights 应用程序的监控。

**Topics**
+ [列出应用程序的问题](#appinsights-list-problems-monitoring)
+ [描述应用程序问题](#appinsights-describe-app-problem)
+ [描述与问题关联的异常或错误](#appinsights-describe-anomalies)
+ [描述应用程序的异常或错误](#appinsights-describe-anomalies)
+ [描述组件的监控配置](#appinsights-describe-monitoring)
+ [描述建议的组件监控配置](#appinsights-describe-rec-monitoring)
+ [更新组件的监控配置](#update-monitoring)
+ [对指定的资源组取消 Application Insights 监控](#update-monitoring)

### 列出应用程序的问题
<a name="appinsights-list-problems-monitoring"></a>

**使用 AWS CLI 列出应用程序的问题**  
要使用 AWS CLI 列出自 Unix Epoch 以来针对在名为 `my-resource-group` 的资源组上创建的应用程序在 1000 到 10000 毫秒之间检测到的应用程序问题，请使用以下命令。

```
aws application-insights list-problems --resource-group-name my-resource-group --start-time 1000 --end-time 10000
```

**使用 AWS Tools for Windows PowerShell 列出应用程序的问题**  
要使用 AWS Tools for Windows PowerShell 列出自 Unix Epoch 以来针对在名为 `my-resource-group` 的资源组上创建的应用程序在 1000 到 10000 毫秒之间检测到的应用程序问题，请使用以下命令。

```
$startDate = "8/6/2019 3:33:00"
$endDate = "8/6/2019 3:34:00"
Get-CWAIProblemList -ResourceGroupName my-resource-group -StartTime $startDate -EndTime $endDate
```

### 描述应用程序问题
<a name="appinsights-describe-app-problem"></a>

**使用 AWS CLI 描述应用程序问题**  
要使用 AWS CLI 描述问题 ID 为 `p-1234567890` 的问题，请使用以下命令。

```
aws application-insights describe-problem —problem-id p-1234567890
```

**使用 AWS Tools for Windows PowerShell 描述应用程序问题**  
要使用 AWS Tools for Windows PowerShell 描述问题 ID 为 `p-1234567890` 的问题，请使用以下命令。

```
Get-CWAIProblem -ProblemId p-1234567890
```

### 描述与问题关联的异常或错误
<a name="appinsights-describe-anomalies"></a>

**使用 AWS CLI 描述与问题关联的异常或错误**  
要使用 AWS CLI 描述与问题 ID 为 `p-1234567890` 的问题关联的异常或错误，请使用以下命令。

```
aws application-insights describe-problem-observations --problem-id -1234567890
```

**使用 AWS Tools for Windows PowerShell 描述与问题关联的异常或错误**  
要使用 AWS Tools for Windows PowerShell 描述与问题 ID 为 `p-1234567890` 的问题关联的异常或错误，请使用以下命令。

```
Get-CWAIProblemObservation -ProblemId p-1234567890
```

### 描述应用程序的异常或错误
<a name="appinsights-describe-anomalies"></a>

**使用 AWS CLI 描述应用程序的异常或错误**  
要使用 AWS CLI 描述观察 ID 为 `o-1234567890` 的应用程序的异常或错误，请使用以下命令。

```
aws application-insights describe-observation —observation-id o-1234567890
```

**使用 AWS Tools for Windows PowerShell描述应用程序的异常或错误**  
要使用 AWS Tools for Windows PowerShell 描述观察 ID 为 `o-1234567890` 的应用程序的异常或错误，请使用以下命令。

```
Get-CWAIObservation -ObservationId o-1234567890
```

### 描述组件的监控配置
<a name="appinsights-describe-monitoring"></a>

**使用 AWS CLI 组件描述组件的监控配置**  
要使用 AWS CLI 描述在资源组 `my-resource-group` 上创建的应用程序中名为 `my-component` 的组件的监控配置，请使用以下命令。

```
aws application-insights describe-component-configuration —resource-group-name my-resource-group —component-name my-component
```

**使用 AWS Tools for Windows PowerShell 描述组件的监控配置**  
要使用 AWS Tools for Windows PowerShell 描述在资源组 `my-resource-group` 上创建的应用程序中名为 `my-component` 的组件的监控配置，请使用以下命令。

```
Get-CWAIComponentConfiguration -ComponentName my-component -ResourceGroupName my-resource-group
```

有关组件配置和示例 JSON 文件的更多信息，请参阅[使用组件配置](component-config.md)。

### 描述建议的组件监控配置
<a name="appinsights-describe-rec-monitoring"></a>

**使用 AWS CLI 描述建议的组件监控配置**  
当组件是 .NET Worker 应用程序的一部分时，您可以使用 AWS CLI，通过使用以下命令来描述在资源组 `my-resource-group` 上创建的应用程序中名为 `my-component` 的组件的建议监控配置。

```
aws application-insights describe-component-configuration-recommendation --resource-group-name my-resource-group --component-name my-component --tier DOT_NET_WORKER
```

**使用 AWS Tools for Windows PowerShell 描述建议的组件监控配置**  
当组件是 .NET Worker 应用程序的一部分时，您可以使用 AWS Tools for Windows PowerShell，通过使用以下命令来描述在资源组 `my-resource-group` 上创建的应用程序中名为 `my-component` 的组件的建议监控配置。

```
Get-CWAIComponentConfigurationRecommendation -ComponentName my-component -ResourceGroupName my-resource-group -Tier DOT_NET_WORKER
```

有关组件配置和示例 JSON 文件的更多信息，请参阅[使用组件配置](component-config.md)。

### 更新组件的监控配置
<a name="update-monitoring"></a>

**使用 AWS CLI 更新组件的监控配置**  
要使用 AWS CLI 更新在名为 `my-resource-group` 的资源组上创建的应用程序中名为 `my-component` 的组件，请使用以下命令。该命令包括以下操作：

1. 启用组件监控。

1. 将组件层设置为 `.NET Worker`。

1. 更新组件的 JSON 配置以从本地文件 `configuration.txt` 中读取。

```
aws application-insights update-component-configuration --resource-group-name my-resource-group --component-name my-component --tier DOT_NET_WORKER --monitor --component-configuration "file://configuration.txt"
```

**使用 AWS Tools for Windows PowerShell 更新组件的监控配置**  
要使用 AWS Tools for Windows PowerShell 更新在名为 `my-resource-group` 的资源组上创建的应用程序中名为 `my-component` 的组件，请使用以下命令。该命令包括以下操作：

1. 启用组件监控。

1. 将组件层设置为 `.NET Worker`。

1. 更新组件的 JSON 配置以从本地文件 `configuration.txt` 中读取。

```
[string]$config = Get-Content -Path configuration.txt
Update-CWAIComponentConfiguration -ComponentName my-component -ResourceGroupName my-resource-group -Tier DOT_NET_WORKER -Monitor 1 -ComponentConfiguration $config
```

有关组件配置和示例 JSON 文件的更多信息，请参阅[使用组件配置](component-config.md)。

### 对指定的资源组取消 Application Insights 监控
<a name="update-monitoring"></a>

**使用 AWS CLI 对指定的资源组取消 Application Insights 监控**  
要使用 AWS CLI 对在名为 `my-resource-group` 的资源组上创建的应用程序取消监控，请使用以下命令。

```
aws application-insights delete-application --resource-group-name my-resource-group
```

**使用 AWS Tools for Windows PowerShell 对指定的资源组取消 Application Insights 监控**  
要使用 AWS Tools for Windows PowerShell 对在名为 `my-resource-group` 的资源组上创建的应用程序取消监控，请使用以下命令。

```
Remove-CWAIApplication -ResourceGroupName my-resource-group
```

## 针对 SQL Always On 可用性组配置监控
<a name="configure-sql"></a>

1. 使用 SQL HA EC2 实例为资源组创建应用程序。

   ```
   aws application-insights create-application ‐-region <REGION> ‐-resource-group-name  <RESOURCE_GROUP_NAME>
   ```

1. 通过创建新的应用程序组件，定义表示 SQL HA 集群的 EC2 实例。

   ```
   aws application-insights create-component ‐-resource-group-name  "<RESOURCE_GROUP_NAME>" ‐-component-name SQL_HA_CLUSTER ‐-resource-list  "arn:aws:ec2:<REGION>:<ACCOUNT_ID>:instance/<CLUSTER_INSTANCE_1_ID>" "arn:aws:ec2:<REGION>:<ACCOUNT_ID>:instance/<CLUSTER_INSTANCE_2_ID>
   ```

1. 配置 SQL HA 组件。

   ```
   aws application-insights  update-component-configuration ‐-resource-group-name "<RESOURCE_GROUP_NAME>" ‐-region <REGION> ‐-component-name "SQL_HA_CLUSTER" ‐-monitor ‐-tier SQL_SERVER_ALWAYSON_AVAILABILITY_GROUP ‐-monitor  ‐-component-configuration '{
     "subComponents" : [ {
       "subComponentType" : "AWS::EC2::Instance",
       "alarmMetrics" : [ {
         "alarmMetricName" : "CPUUtilization",
         "monitor" : true
       }, {
         "alarmMetricName" : "StatusCheckFailed",
         "monitor" : true
       }, {
         "alarmMetricName" : "Processor % Processor Time",
         "monitor" : true
       }, {
         "alarmMetricName" : "Memory % Committed Bytes In Use",
         "monitor" : true
       }, {
         "alarmMetricName" : "Memory Available Mbytes",
         "monitor" : true
       }, {
         "alarmMetricName" : "Paging File % Usage",
         "monitor" : true
       }, {
         "alarmMetricName" : "System Processor Queue Length",
         "monitor" : true
       }, {
         "alarmMetricName" : "Network Interface Bytes Total/sec",
         "monitor" : true
       }, {
         "alarmMetricName" : "PhysicalDisk % Disk Time",
         "monitor" : true
       }, {
         "alarmMetricName" : "SQLServer:Buffer Manager Buffer cache hit ratio",
         "monitor" : true
       }, {
         "alarmMetricName" : "SQLServer:Buffer Manager Page life expectancy",
         "monitor" : true
       }, {
         "alarmMetricName" : "SQLServer:General Statistics Processes blocked",
         "monitor" : true
       }, {
         "alarmMetricName" : "SQLServer:General Statistics User Connections",
         "monitor" : true
       }, {
         "alarmMetricName" : "SQLServer:Locks Number of Deadlocks/sec",
         "monitor" : true
       }, {
         "alarmMetricName" : "SQLServer:SQL Statistics Batch Requests/sec",
         "monitor" : true
       }, {
         "alarmMetricName" : "SQLServer:Database Replica File Bytes Received/sec",
         "monitor" : true
       }, {
         "alarmMetricName" : "SQLServer:Database Replica Log Bytes Received/sec",
         "monitor" : true
       }, {
         "alarmMetricName" : "SQLServer:Database Replica Log remaining for undo",
         "monitor" : true
       }, {
         "alarmMetricName" : "SQLServer:Database Replica Log Send Queue",
         "monitor" : true
       }, {
         "alarmMetricName" : "SQLServer:Database Replica Mirrored Write Transaction/sec",
         "monitor" : true
       }, {
         "alarmMetricName" : "SQLServer:Database Replica Recovery Queue",
         "monitor" : true
       }, {
         "alarmMetricName" : "SQLServer:Database Replica Redo Bytes Remaining",
         "monitor" : true
       }, {
         "alarmMetricName" : "SQLServer:Database Replica Redone Bytes/sec",
         "monitor" : true
       }, {
         "alarmMetricName" : "SQLServer:Database Replica Total Log requiring undo",
         "monitor" : true
       }, {
         "alarmMetricName" : "SQLServer:Database Replica Transaction Delay",
         "monitor" : true
       } ],
       "windowsEvents" : [ {
         "logGroupName" : "WINDOWS_EVENTS-Application-<RESOURCE_GROUP_NAME>",
         "eventName" : "Application",
         "eventLevels" : [ "WARNING", "ERROR", "CRITICAL", "INFORMATION" ],
         "monitor" : true
       }, {
         "logGroupName" : "WINDOWS_EVENTS-System-<RESOURCE_GROUP_NAME>",
         "eventName" : "System",
         "eventLevels" : [ "WARNING", "ERROR", "CRITICAL" ],
         "monitor" : true
       }, {
         "logGroupName" : "WINDOWS_EVENTS-Security-<RESOURCE_GROUP_NAME>",
         "eventName" : "Security",
         "eventLevels" : [ "WARNING", "ERROR", "CRITICAL" ],
         "monitor" : true
       } ],
       "logs" : [ {
         "logGroupName" : "SQL_SERVER_ALWAYSON_AVAILABILITY_GROUP-<RESOURCE_GROUP_NAME>",
         "logPath" : "C:\\Program Files\\Microsoft SQL Server\\MSSQL**.MSSQLSERVER\\MSSQL\\Log\\ERRORLOG",
         "logType" : "SQL_SERVER",
         "monitor" : true,
         "encoding" : "utf-8"
       } ]
     }, {
       "subComponentType" : "AWS::EC2::Volume",
       "alarmMetrics" : [ {
         "alarmMetricName" : "VolumeReadBytes",
         "monitor" : true
       }, {
       "alarmMetricName" : "VolumeWriteBytes",
         "monitor" : true
       }, {
       "alarmMetricName" : "VolumeReadOps",
         "monitor" : true
       }, {
       "alarmMetricName" : "VolumeWriteOps",
         "monitor" : true
       }, {
       "alarmMetricName" : "VolumeQueueLength",
         "monitor" : true
       }, {
       "alarmMetricName" : "VolumeThroughputPercentage",
         "monitor" : true
       }, {
       "alarmMetricName" : "BurstBalance",
         "monitor" : true
       } ]
     } ]
   }'
   ```

**注意**  
Application Insights 必须获取应用程序事件日志（信息级别）才能检测集群活动（如故障转移）。

## 为 MySQL RDS 配置监控
<a name="configure-mysql-rds"></a>

1. 使用 RDS MySQL 数据库实例为资源组创建应用程序。

   ```
   aws application-insights create-application ‐-region <REGION> ‐-resource-group-name  <RESOURCE_GROUP_NAME>
   ```

1. 默认情况下，启用错误日志。可以使用数据参数组启用慢速查询日志。有关更多信息，请参阅[访问 MySQL 慢速查询和常规日志](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_LogAccess.Concepts.MySQL.html#USER_LogAccess.MySQL.Generallog)。
   + `set slow_query_log = 1`
   + `set log_output = FILE`

1. 将要监控的日志导出到 CloudWatch Logs 中。有关更多信息，请参阅[将 MySQL 日志发布到 CloudWatch Logs](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_LogAccess.Concepts.MySQL.html#USER_LogAccess.MySQLDB.PublishtoCloudWatchLogs)。

1. 配置 MySQL RDS 组件。

   ```
   aws application-insights  update-component-configuration ‐-resource-group-name "<RESOURCE_GROUP_NAME>" ‐-region <REGION> ‐-component-name "<DB_COMPONENT_NAME>" ‐-monitor ‐-tier DEFAULT ‐-monitor  ‐-component-configuration "{\"alarmMetrics\":[{\"alarmMetricName\":\"CPUUtilization\",\"monitor\":true}],\"logs\":[{\"logType\":\"MYSQL\",\"monitor\":true},{\"logType\": \"MYSQL_SLOW_QUERY\",\"monitor\":false}]}"
   ```

## 为 MySQL EC2 配置监控
<a name="configure-mysql-ec2"></a>

1. 使用 SQL HA EC2 实例为资源组创建应用程序。

   ```
   aws application-insights create-application ‐-region <REGION> ‐-resource-group-name  <RESOURCE_GROUP_NAME>
   ```

1. 默认情况下，启用错误日志。可以使用数据参数组启用慢速查询日志。有关更多信息，请参阅[访问 MySQL 慢速查询和常规日志](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_LogAccess.Concepts.MySQL.html#USER_LogAccess.MySQL.Generallog)。
   + `set slow_query_log = 1`
   + `set log_output = FILE`

1. 配置 MySQL EC2 组件。

   ```
   aws application-insights  update-component-configuration ‐-resource-group-name "<RESOURCE_GROUP_NAME>" ‐-region <REGION> ‐-component-name "<DB_COMPONENT_NAME>" ‐-monitor ‐-tier MYSQL ‐-monitor  ‐-component-configuration "{\"alarmMetrics\":[{\"alarmMetricName\":\"CPUUtilization\",\"monitor\":true}],\"logs\":[{\"logGroupName\":\"<UNIQUE_LOG_GROUP_NAME>\",\"logPath\":\"C:\\\\ProgramData\\\\MySQL\\\\MySQL Server **\\\\Data\\\\<FILE_NAME>.err\",\"logType\":\"MYSQL\",\"monitor\":true,\"encoding\":\"utf-8\"}]}"
   ```

## 为 PostgreSQL RDS 配置监控
<a name="configure-postgresql-rds"></a>

1. 使用 Postgre RDS 数据库实例为资源组创建应用程序。

   ```
   aws application-insights create-application ‐-region <REGION> ‐-resource-group-name  <RESOURCE_GROUP_NAME>
   ```

1. 默认情况下，没有启用将 PostgreSQL 日志发布到 CloudWatch 的功能。要启用监控，请打开 RDS 控制台并选择要监控的数据库。选择右上角的 **Modify**（修改），然后选中标注为 **PostgreSQL** 日志的复选框。选择 **Continue（继续）**以保存此设置。

1. 您的 PostgreSQL 日志将导出到 CloudWatch。

1. 配置 PostgreSQL RDS 组件。

   ```
   aws application-insights update-component-configuration --region <REGION> --resource-group-name <RESOURCE_GROUP_NAME> --component-name <DB_COMPONENT_NAME> --monitor --tier DEFAULT --component-configuration 
   "{
      \"alarmMetrics\":[
         {
            \"alarmMetricName\": \"CPUUtilization\",
            \"monitor\": true
         }
      ],
      \"logs\":[
         {
            \"logType\": \"POSTGRESQL\",
            \"monitor\": true
         }
      ]
   }"
   ```

## 为 PostgreSQL EC2 配置监控
<a name="configure-postgresql-ec2"></a>

1. 使用 PostgreSQL EC2 实例为资源组创建应用程序。

   ```
   aws application-insights create-application ‐-region <REGION> ‐-resource-group-name  <RESOURCE_GROUP_NAME>
   ```

1. 配置 PostgreSQL EC2 组件。

   ```
   aws application-insights update-component-configuration ‐-region <REGION> ‐-resource-group-name <RESOURCE_GROUP_NAME> ‐-component-name <DB_COMPONENT_NAME> ‐-monitor ‐-tier POSTGRESQL ‐-component-configuration 
   "{
      \"alarmMetrics\":[
         {
            \"alarmMetricName\":\"CPUUtilization\",
            \"monitor\":true
         }
      ],
      \"logs\":[
         {
            \"logGroupName\":\"<UNIQUE_LOG_GROUP_NAME>\",
            \"logPath\":\"/var/lib/pgsql/data/log/\",
            \"logType\":\"POSTGRESQL\",
            \"monitor\":true,
            \"encoding\":\"utf-8\"
         }
      ]
   }"
   ```

## 为 Oracle RDS 配置监控
<a name="configure-oracle-rds"></a>

1. 使用 Oracle RDS 数据库实例为资源组创建应用程序。

   ```
   aws application-insights create-application ‐-region <REGION> ‐-resource-group-name  <RESOURCE_GROUP_NAME>
   ```

1. 默认情况下，没有启用将 Oracle 日志发布到 CloudWatch 的功能。要启用监控，请打开 RDS 控制台并选择要监控的数据库。选择右上角的 **Modify**（修改），然后选中标注为 **Alert**（提示）日志和 **Listener**（侦听器）日志的复选框。选择 **Continue（继续）**以保存此设置。

1. 您的 Oracle 日志将导出到 CloudWatch。

1. 配置 Oracle RDS 组件。

   ```
   aws application-insights update-component-configuration --region <REGION> --resource-group-name <RESOURCE_GROUP_NAME> --component-name <DB_COMPONENT_NAME> --monitor --tier DEFAULT --component-configuration 
   "{
      \"alarmMetrics\":[
         {
            \"alarmMetricName\": \"CPUUtilization\",
            \"monitor\": true
         }
      ],
      \"logs\":[
         {
            \"logType\": \"ORACLE_ALERT\",
            \"monitor\": true
         },
         {
            \"logType\": \"ORACLE_LISTENER\",
            \"monitor\": true
         }
      ]
   }"
   ```

## 为 Oracle EC2 配置监控
<a name="configure-oracle-ec2"></a>

1. 使用 Oracle EC2 实例为资源组创建应用程序。

   ```
   aws application-insights create-application ‐-region <REGION> ‐-resource-group-name  <RESOURCE_GROUP_NAME>
   ```

1. 配置 Oracle EC2 组件。

   ```
   aws application-insights update-component-configuration ‐-region <REGION> ‐-resource-group-name <RESOURCE_GROUP_NAME> ‐-component-name <DB_COMPONENT_NAME> ‐-monitor ‐-tier ORACLE ‐-component-configuration 
   "{
      \"alarmMetrics\":[
         {
            \"alarmMetricName\":\"CPUUtilization\",
            \"monitor\":true
         }
      ],
      \"logs\":[
         {
            \"logGroupName\":\"<UNIQUE_LOG_GROUP_NAME>\",
            \"logPath\":\"/opt/oracle/diag/rdbms/*/*/trace\",
            \"logType\":\"ORACLE_ALERT\",
            \"monitor\":true,
         },
         {
            \"logGroupName\":\"<UNIQUE_LOG_GROUP_NAME>\",
            \"logPath\":\"/opt/oracle/diag/tnslsnr/$HOSTNAME/listener/trace/\",
            \"logType\":\"ORACLE_ALERT\",
            \"monitor\":true,
         }
      ]
   }"
   ```

# 检测到的问题的 Application Insights CloudWatch Events
<a name="appinsights-cloudwatch-events"></a>

对于添加到 CloudWatch Application Insights 的每个应用程序，将尽可能为以下事件发布 CloudWatch Events：
+ **问题创建。**在 CloudWatch Application Insights 检测到新问题时发出。
  + 详细信息类型：**“检测到 Application Insights 问题”**
  + 详细信息：
    + `problemId`：检测到的问题 ID。
    + `region`：创建问题的 AWS 区域。
    + `resourceGroupName`：检测到问题的注册应用程序的资源组。
    + `status`：问题的状态。可能的状态和定义如下：
      + `In progress`：发现了一个新问题。这个问题仍在接受观察。
      + `Recovering`：问题正在趋于稳定。当问题处于此状态时，您可以手动解决问题。
      + `Resolved`：问题已解决。关于这个问题没有新的观察结果。
      + `Recurring`：问题在过去 24 小时内得到解决。经过进一步观察，发现问题重新出现。
    + `severity`：问题的严重性。
    + `problemUrl`：问题的控制台 URL。
+ **问题更新。**使用新观察结果更新问题或更新现有观察结果并随后更新问题时发出；更新包括问题解决方案或处理措施。
  + 详细信息类型：**“已更新 Application Insights 问题”**
  + 详细信息：
    + `problemId`：创建的问题 ID。
    + `region`：创建问题的 AWS 区域。
    + `resourceGroupName`：检测到问题的注册应用程序的资源组。
    + `status`：问题的状态。
    + `severity`：问题的严重性。
    + `problemUrl`：问题的控制台 URL。

# 接收有关检测到的问题的通知
<a name="appinsights-problem-notifications"></a>

您可以使用 Amazon SNS 通知、Systems Manager OpsCenter 或 CloudWatch Events 来接收有关在应用程序中检测到的问题的通知。

**检测到的问题的 CloudWatch Application Insights Amazon SNS 通知**  
您可以使用 AWS 管理控制台 或 AWS CLI 来配置 Amazon SNS 通知。要使用 AWS 管理控制台 设置通知，您必须拥有必要的 Amazon SNS 权限，如以下示例所示。

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
      {
        "Effect": "Allow",
        "Action": [
          "sns:ListTopics",
          "sns:Subscribe",
          "sns:CreateTopic"
        ],    
        "Resource": [
          "*" 
        ]
      }
    ]    
}
```

------

设置 Amazon SNS 通知后，当问题出现或解决时，您会收到电子邮件通知。当向现有问题添加新的观测结果时，您还会收到通知。

以下示例显示电子邮件通知的内容。

```
    You are receiving this email because Problem "p-1234567" has been CREATED by Amazon CloudWatch Application Insights
    
    Problem Details: 
    Problem URL: https:////console.aws.amazon.com/cloudwatch/home?region=us-east-1#settings:AppInsightsSettings/problemDetails?problemId=p-1234567
    Problem Summary: Title of the problem
    Severity: HIGH
    Insights: Something specific is broken
    Status : RESOLVED
    AffectedResource: arn:aws:ec2:us-east-1:555555555555:host/testResource
    Region: us-east-1
    RecurringCount: 0
    StartTime: 2019-03-23T10:42:57.777Z
    LastUpdatedTime: 2019-03-23T21:49:37.777Z
    LastRecurrenceTime: 
    StopTime: 2019-03-23T21:49:37.777Z
    
    Recent Issues
    - TelemetryArn:alarm1
      StartTime: 2024-08-15T22:12:46.007Z
      StopTime:
    - TelemetryArn:log-group1
      StartTime: 2024-08-15T22:12:46.007Z
      StopTime: 2024-08-15T22:12:46.007Z
```

**如何使用 Systems Manager 接收问题通知**  
**通过 AWS Systems Manager 执行的操作。**CloudWatch Application Insights 提供与 Systems Manager OpsCenter 的内置集成。如果您选择将此集成用于您的应用程序，则会在 OpsCenter 控制台上为该应用程序检测到的每个问题创建一个 OpsItem。在 OpsCenter 控制台中，您可以查看 CloudWatch Application Insights 检测到的问题的摘要信息，并选择一个 Systems Manager Automation 运行手册来采取补救措施，或者进一步识别导致应用程序中出现资源问题的 Windows 进程。

**如何使用 CloudWatch Events 接收问题通知**  
从 CloudWatch 控制台中，选择 **Events（事件）**下左侧导航窗格中的 **Rule（规则）**。从 **Rules (规则)** 页面中，选择 **Create rule (创建规则)**。选择 **Service Name（服务名称）**下拉列表中的 **Amazon CloudWatch Application Insights**，然后选择 **Event Type（事件类型）**。然后，选择 **Add target (添加目标)**，并选择目标和参数，例如 **SNS topic (SNS 主题)** 或 **Lambda function (Lambda 函数)**。

# Application Insights 跨账户可观测性
<a name="appinsights-cross-account"></a>

借助 CloudWatch Application Insights 跨账户可观测性，您可以跨越一个区域内的多个 AWS 账户监控应用程序以及排查问题。

您可以使用 Amazon CloudWatch Observability Access Manager 将一个或多个 AWS 账户设置为监控账户。通过在监控账户中创建接收器，监控账户将能够查看源账户中的数据。您可以使用接收器来创建从源账户指向监控账户的链接。有关更多信息，请参阅 [CloudWatch 跨账户可观测性](CloudWatch-Unified-Cross-Account.md)。

**所需的资源**  
为保证 CloudWatch Application Insights 跨账户可观测性正常运行，请务必通过 CloudWatch Observability Access Manager 共享以下遥测类型。
+ CloudWatch Application Insights 中的应用程序
+ Amazon CloudWatch 中的指标
+ 在 Amazon CloudWatch Logs 中记录组
+ [AWS X-Ray](https://docs.aws.amazon.com/xray/latest/devguide/aws-xray.html) 中的跟踪记录

# 使用组件配置
<a name="component-config"></a>

组件配置是 JSON 格式的文本文件，用于描述组件的配置设置。本节提供示例模板片段、组件配置部分的说明以及组件配置示例。

**Topics**
+ [模板片段](component-config-json.md)
+ [Sections](component-config-sections.md)
+ [相关服务的示例配置](component-configuration-examples.md)

# 组件配置模板片段
<a name="component-config-json"></a>

以下示例显示 JSON 格式的模板片段。

```
{
  "alarmMetrics" : [
    list of alarm metrics
  ],
  "logs" : [
    list of logs
  ],
  "processes" : [
   list of processes
  ],
  "windowsEvents" : [
    list of windows events channels configurations
  ],
  "alarms" : [
    list of CloudWatch alarms
  ],
  "jmxPrometheusExporter": {
    JMX Prometheus Exporter configuration
  },
  "hanaPrometheusExporter": {
      SAP HANA Prometheus Exporter configuration
  },
  "haClusterPrometheusExporter": {
      HA Cluster Prometheus Exporter configuration
  },
  "netWeaverPrometheusExporter": {
      SAP NetWeaver Prometheus Exporter configuration
  },
  "subComponents" : [
    {
      "subComponentType" : "AWS::EC2::Instance" ...
      component nested instances configuration
    },
    {
      "subComponentType" : "AWS::EC2::Volume" ...
      component nested volumes configuration
    }
  ]
}
```

# 组件配置部分
<a name="component-config-sections"></a>

组件配置包括几个主要部分。组件配置的部分可以任何顺序列出。
+ **alarmMetrics（可选）**

  组件中要监控的[指标](#component-config-metric)列表。所有组件类型都可以有一个 alarmMetrics 部分。
+ **日志（可选）**

  组件中要监控的[日志](#component-configuration-log)列表。仅 EC2 实例可以具有日志部分。
+ **进程（可选）**

  要为组件监控的[进程](#component-configuration-process)的列表。仅 EC2 实例可以具有进程部分。
+ **subComponents（可选）**

  组件的嵌套实例和卷子组件配置。以下类型的组件可以具有嵌套实例和一个子组件部分：ELB、ASG、自定义分组的 EC2 实例和 EC2 实例。
+ **警报（可选）**

  要为组件监控的[警报](#component-configuration-alarms)的列表。所有组件类型都可以有一个警报部分。
+ **windowsEvents（可选）**

  要为组件监控的 [Windows 事件](#windows-events)的列表。只有 EC2 实例上的 Windows 有 `windowsEvents` 部分。
+ **JMXPrometheusExporter（可选）**

  JMXPrometheus Exporter 配置。
+ **hanaPrometheusExporter（可选）**

  SAP HANA Prometheus Exporter 配置。
+ **haClusterPrometheusExporter（可选）**

  HA Cluster Prometheus Exporter 配置。
+ **netWeaverPrometheusExporter（可选）**

  SAP NetWeaver Prometheus Exporter 配置。
+ **sapAsePrometheusExporter（可选）**

  SAP ASE Prometheus Exporter 配置。

以下示例显示 JSON 格式的 **subComponents 部分片段**的语法。

```
[
  {
    "subComponentType" : "AWS::EC2::Instance",
    "alarmMetrics" : [
      list of alarm metrics
    ],
    "logs" : [
      list of logs
    ],
    "processes": [
      list of processes
    ],
    "windowsEvents" : [
      list of windows events channels configurations
    ]
  },
  {
    "subComponentType" : "AWS::EC2::Volume",
    "alarmMetrics" : [
      list of alarm metrics
    ]
  }
]
```

## 组件配置部分属性
<a name="component-config-properties"></a>

这部分描述各部件配置部分的属性。

**Topics**
+ [指标](#component-config-metric)
+ [Log](#component-configuration-log)
+ [流程](#component-configuration-process)
+ [JMX Prometheus Exporter](#component-configuration-prometheus)
+ [HANA Prometheus Exporter](#component-configuration-hana-prometheus)
+ [HA Cluster Prometheus Exporter](#component-configuration-ha-cluster-prometheus)
+ [NetWeaver Prometheus Exporter](#component-configuration-netweaver-prometheus)
+ [SAP ASE Prometheus Exporter](#component-configuration-sap-ase-prometheus)
+ [Windows 事件](#windows-events)
+ [警报](#component-configuration-alarms)

### 指标
<a name="component-config-metric"></a>

定义组件中要监控的指标。

**JSON** 

```
{
  "alarmMetricName" : "monitoredMetricName",
  "monitor" : true/false
}
```

**属性**
+ **alarmMetricName（必需）**

  组件中待监控指标的名称。有关 Application Insights 支持的指标的信息，请参阅 [Amazon CloudWatch Application Insights 支持的日志和指标](appinsights-logs-and-metrics.md)。
+ **监控（可选）**

  布尔值，指示是否监控指标。默认值为 `true`。

### Log
<a name="component-configuration-log"></a>

定义组件中要监控的日志。

**JSON** 

```
{
  "logGroupName" : "logGroupName",
  "logPath" : "logPath",
  "logType" : "logType",
  "encoding" : "encodingType",
  "monitor" : true/false
}
```

**属性**
+ **logGroupName（必需）**

  要与监控日志关联的 CloudWatch 日志组名称。对于日志组名称约束的信息，请参阅 [CreateLogGroup](https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_CreateLogGroup.html)。
+ **logPath（EC2 实例组件需要；不使用 CloudWatch 代理的组件不需要，例如 AWS Lambda）**

  要监控的日志路径。日志路径必须是 Windows 系统文件绝对路径。有关更多信息，请参阅 [CloudWatch 代理配置文件：日志部分](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Agent-Configuration-File-Details.html#CloudWatch-Agent-Configuration-File-Logssection)。
+ **logType（必需）**

  日志类型决定 Application Insights 分析日志时所依据的日志模式。从以下选项中选择日志类型：
  + `SQL_SERVER`
  + `MYSQL`
  + `MYSQL_SLOW_QUERY`
  + `POSTGRESQL`
  + `ORACLE_ALERT`
  + `ORACLE_LISTENER`
  + `IIS`
  + `APPLICATION`
  + `WINDOWS_EVENTS`
  + `WINDOWS_EVENTS_ACTIVE_DIRECTORY`
  + `WINDOWS_EVENTS_DNS`
  + `WINDOWS_EVENTS_IIS`
  + `WINDOWS_EVENTS_SHAREPOINT`
  + `SQL_SERVER_ALWAYSON_AVAILABILITY_GROUP`
  + `SQL_SERVER_FAILOVER_CLUSTER_INSTANCE`
  + `DEFAULT`
  + `CUSTOM`
  + `STEP_FUNCTION`
  + `API_GATEWAY_ACCESS`
  + `API_GATEWAY_EXECUTION`
  + `SAP_HANA_LOGS`
  + `SAP_HANA_TRACE`
  + `SAP_HANA_HIGH_AVAILABILITY`
  + `SAP_NETWEAVER_DEV_TRACE_LOGS`
  + `PACEMAKER_HIGH_AVAILABILITY`
+ **编码（可选）**

  要监控的日志的编码类型。指定的编码应包含在 [CloudWatch 代理支持的编码](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AgentReference.html)列表中。如果未提供，CloudWatch Application Insights 将对 utf-8 类型使用默认编码，以下除外：
  +  `SQL_SERVER`：utf-16 编码
  +  `IIS`：ascii 编码
+ **监控（可选）**

  布尔值，用于指示是否监控日志。默认值为 `true`。

### 流程
<a name="component-configuration-process"></a>

定义组件待监控的过程。

**JSON** 

```
{
  "processName" : "monitoredProcessName",
  "alarmMetrics" : [
      list of alarm metrics
  ] 
}
```

**属性**
+ **processName（必需）**

  组件待监控的过程名称。进程名称不能包含进程主干，如 `sqlservr` 或 `sqlservr.exe`。
+ **alarmMetrics（必需）**

  此进程要监控的[指标](#component-config-metric)的列表。要查看 CloudWatch Application Insights 支持的进程指标，请参阅 [Amazon Elastic Compute Cloud (EC2)](appinsights-metrics-ec2.md)。

### JMX Prometheus Exporter
<a name="component-configuration-prometheus"></a>

定义 JMX Prometheus Exporter 设置。

**JSON** 

```
"JMXPrometheusExporter": {
  "jmxURL" : "JMX URL",
  "hostPort" : "The host and port",
  "prometheusPort" : "Target port to emit Prometheus metrics"
}
```

**属性**
+ **jmxURL（可选）**

  要连接到的完整 JMX URL。
+ **hostPort（可选）**

  要通过远程 JMX 连接的主机和端口。只能指定 `jmxURL` 和 `hostPort` 中的一个。
+ **prometheusPort（可选）**

  要向其发送 Prometheus 指标的目标端口。如果未指定，则使用默认端口 9404。

### HANA Prometheus Exporter
<a name="component-configuration-hana-prometheus"></a>

定义 HANA Prometheus Exporter 设置。

**JSON** 

```
"hanaPrometheusExporter": {
    "hanaSid": "SAP HANA  SID",
    "hanaPort": "HANA database port",
    "hanaSecretName": "HANA secret name",
    "prometheusPort": "Target port to emit Prometheus metrics"
}
```

**属性**
+ **hanaSid**

  SAP HANA 系统由三个字符组成的 SAP 系统 ID (SID)。
+ **hanaPort**

  导出程序将用于查询 HANA 指标的 HANA 数据库端口。
+ **HanaSecretName**

  存储 HANA 监控用户凭证的 AWS Secrets Manager 密钥。HANA Prometheus Exporter 使用这些凭证连接到数据库并查询 HANA 指标。
+ **prometheusPort（可选）**

  Prometheus 向其发送指标的目标端口。如果未指定，则使用默认端口 9668。

### HA Cluster Prometheus Exporter
<a name="component-configuration-ha-cluster-prometheus"></a>

定义 HA Cluster Prometheus Exporter 设置。

**JSON** 

```
"haClusterPrometheusExporter": {
    "prometheusPort": "Target port to emit Prometheus metrics"
}
```

**属性**
+ **prometheusPort（可选）**

  Prometheus 向其发送指标的目标端口。如果未指定，则使用默认端口 9664。

### NetWeaver Prometheus Exporter
<a name="component-configuration-netweaver-prometheus"></a>

定义 NetWeaver Prometheus Exporter 设置。

**JSON** 

```
"netWeaverPrometheusExporter": {
    "sapSid": "SAP NetWeaver  SID",
    "instanceNumbers": [ "Array of instance Numbers of SAP NetWeaver system "],
"prometheusPort": "Target port to emit Prometheus metrics"
}
```

**属性**
+ **sapSid**

  SAP NetWeaver 系统的 3 字符 SAP 系统 ID (SID)。
+ **instanceNumbers**

  SAP NetWeaver 系统的实例号数组。

  **示例：**`"instanceNumbers": [ "00", "01"]`
+ **prometheusPort（可选）**

  发送 Prometheus 指标的目标端口。如果未指定，则使用默认端口 `9680`。

### SAP ASE Prometheus Exporter
<a name="component-configuration-sap-ase-prometheus"></a>

定义 SAP ASE Prometheus Exporter 设置。

**JSON** 

```
"sapASEPrometheusExporter": {
    "sapAseSid": "SAP ASE SID",
    "sapAsePort": "SAP ASE database port",
    "sapAseSecretName": "SAP ASE secret name",
    "prometheusPort": "Target port to emit Prometheus metrics",
    "agreeToEnableASEMonitoring": true
}
```

**属性**
+ **sapAseSid**

  SAP ASE 系统由三个字符组成的 SAP 系统 ID（SID）。
+ **sapAsePort**

  导出程序将用于查询 ASE 指标的 SAP ASE 数据库端口。
+ **sapAseSecretName**

  存储 ASE 监控用户凭证的 AWS Secrets Manager 密钥。SAP ASE Prometheus 导出程序使用这些凭证连接到数据库并查询 ASE 指标。
+ **prometheusPort（可选）**

  Prometheus 向其发送指标的目标端口。如果未指定，则使用默认端口 9399。如果有另一个 ASE 数据库使用默认端口，则我们使用端口 9499。

### Windows 事件
<a name="windows-events"></a>

定义要记录的 Windows 事件。

**JSON** 

```
{
  "logGroupName" : "logGroupName",
  "eventName" : "eventName",
  "eventLevels" : ["ERROR","WARNING","CRITICAL","INFORMATION","VERBOSE"],
  "monitor" : true/false
}
```

**属性**
+ **logGroupName（必需）**

  要与监控日志关联的 CloudWatch 日志组名称。对于日志组名称约束的信息，请参阅 [CreateLogGroup](https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_CreateLogGroup.html)。
+ **eventName（必需）**

  要记录的 Windows 事件的类型。这等同于 Windows 事件日志通道名称。例如，系统、安全、CustomEventName 等。要记录的每种类型的 Windows 事件需要使用该字段。
+ **eventLevels（必需）**

  要记录的事件级别。您必须指定要录入的每个级别。可能的值包括 `INFORMATION`、`WARNING`、`ERROR`、`CRITICAL` 和 `VERBOSE`。要记录的每种类型的 Windows 事件需要使用该字段。
+ **监控（可选）**

  布尔值，用于指示是否监控日志。默认值为 `true`。

### 警报
<a name="component-configuration-alarms"></a>

定义要为组件监控的 CloudWatch 告警。

**JSON** 

```
{
  "alarmName" : "monitoredAlarmName",
  "severity" : HIGH/MEDIUM/LOW
}
```

**属性**
+ **alarmName（必需）**

  要为组件监控的 CloudWatch 告警的名称。
+ **严重性（可选）**

  指示告警关闭时的中断程度。

# 组件配置示例
<a name="component-configuration-examples"></a>

以下示例以 JSON 格式显示了相关服务的组件配置。

**Topics**
+ [Amazon DynamoDB 表](component-configuration-examples-dynamo.md)
+ [Amazon EC2 Auto Scaling (ASG)](component-configuration-examples-asg.md)
+ [Amazon EKS 集群](component-configuration-examples-eks-cluster.md)
+ [Amazon Elastic Compute Cloud（EC2）实例](component-configuration-examples-ec2.md)
+ [Amazon Elastic Container Service（Amazon ECS）](component-configuration-examples-ecs.md)
+ [Amazon ECS 服务](component-configuration-examples-ecs-service.md)
+ [Amazon ECS 任务](component-configuration-examples-ecs-task.md)
+ [Amazon Elastic File System (Amazon EFS)](component-configuration-examples-efs.md)
+ [Amazon FSx](component-configuration-examples-fsx.md)
+ [Amazon Relational Database Service (RDS) Aurora MySQL](component-configuration-examples-rds-aurora.md)
+ [Amazon Relational Database Service（RDS）实例](component-configuration-examples-rds.md)
+ [Amazon Route 53 运行状况检查](component-configuration-examples-health-check.md)
+ [Amazon Route 53 托管区](component-configuration-examples-hosted-zone.md)
+ [Amazon Route 53 Resolver 端点](component-configuration-examples-resolver-endpoint.md)
+ [Amazon Route 53 Resolver 查询日志记录配置](component-configuration-examples-resolver-query-logging.md)
+ [Amazon S3 存储桶](component-configuration-examples-s3.md)
+ [Amazon Simple Queue Service (SQS)](component-configuration-examples-sqs.md)
+ [Amazon SNS 主题](component-configuration-examples-sns.md)
+ [Amazon Virtual Private Cloud (Amazon VPC)](component-configuration-examples-vpc.md)
+ [Amazon VPC 网络地址转换（NAT）网关](component-configuration-examples-nat-gateway.md)
+ [API Gateway REST API 阶段](component-configuration-examples-api-gateway.md)
+ [Application Elastic Load Balancing](component-configuration-examples-application-elb.md)
+ [AWS Lambda 函数](component-configuration-examples-lambda.md)
+ [AWS Network Firewall 规则组](component-configuration-examples-firewall-rule-group.md)
+ [AWS Network Firewall 规则组关联](component-configuration-examples-firewall-rule-group-assoc.md)
+ [AWS Step Functions](component-configuration-examples-step-functions.md)
+ [客户分组的 Amazon EC2 实例](component-configuration-examples-grouped-ec2.md)
+ [Elastic Load Balancing](component-configuration-examples-elb.md)
+ [Java](component-configuration-examples-java.md)
+ [Amazon EC2 上的 Kubernetes](component-configuration-examples-kubernetes-ec2.md)
+ [RDS MariaDB 和 RDS MySQL](component-configuration-examples-mysql.md)
+ [RDS Oracle](component-configuration-examples-oracle.md)
+ [RDS PostgreSQL](component-configuration-examples-rds-postgre-sql.md)
+ [Amazon EC2 上的 SAP ASE](component-configuration-examples-sap-ase.md)
+ [Amazon EC2 上的 SAP ASE 高可用性](component-configuration-examples-sap-ase-ha.md)
+ [Amazon EC2 上的 SAP HANA](component-configuration-examples-hana.md)
+ [Amazon EC2 上的 SAP HANA 高可用性](component-configuration-examples-hana-ha.md)
+ [Amazon EC2 上的 SAP NetWeaver](component-configuration-examples-netweaver.md)
+ [Amazon EC2 上的 SAP NetWeaver 高可用性](component-configuration-examples-netweaver-ha.md)
+ [SQL Always On 可用性组](component-configuration-examples-sql.md)
+ [SQL 故障转移集群实例](component-configuration-examples-sql-failover-cluster.md)

# Amazon DynamoDB 表
<a name="component-configuration-examples-dynamo"></a>

以下示例演示适用于 Amazon DynamoDB 表的 JSON 格式组件配置。

```
{
  "alarmMetrics": [
    {
      "alarmMetricName": "SystemErrors",
      "monitor": false
    },
    {
      "alarmMetricName": "UserErrors",
      "monitor": false
    },
    {
      "alarmMetricName": "ConsumedReadCapacityUnits",
      "monitor": false
    },
    {
      "alarmMetricName": "ConsumedWriteCapacityUnits",
      "monitor": false
    },
    {
      "alarmMetricName": "ReadThrottleEvents",
      "monitor": false
    },
    {
      "alarmMetricName": "WriteThrottleEvents",
      "monitor": false
    },
    {
      "alarmMetricName": "ConditionalCheckFailedRequests",
      "monitor": false
    },
    {
      "alarmMetricName": "TransactionConflict",
      "monitor": false
    }
  ],
  "logs": []
}
```

# Amazon EC2 Auto Scaling (ASG)
<a name="component-configuration-examples-asg"></a>

以下示例演示适用于 Amazon EC2 Auto Scaling (ASG) 的 JSON 格式组件配置。

```
{
    "alarmMetrics" : [
      {
        "alarmMetricName" : "CPUCreditBalance"
      }, {
        "alarmMetricName" : "EBSIOBalance%"
      }
    ],
    "subComponents" : [
      {
        "subComponentType" : "AWS::EC2::Instance",
        "alarmMetrics" : [
          {
            "alarmMetricName" : "CPUUtilization"
          }, {
            "alarmMetricName" : "StatusCheckFailed"
          }
        ],
        "logs" : [
          {
            "logGroupName" : "my_log_group",
            "logPath" : "C:\\LogFolder\\*",
            "logType" : "APPLICATION"
          }
        ],
        "processes" : [
          {
            "processName" : "my_process",
            "alarmMetrics" : [
              {
                  "alarmMetricName" : "procstat cpu_usage",
                  "monitor" : true
              }, {
                  "alarmMetricName" : "procstat memory_rss",
                  "monitor" : true
              }
          ]
      }
  ],
        "windowsEvents" : [
          {
            "logGroupName" : "my_log_group_2",
            "eventName" : "Application",
            "eventLevels" : [ "ERROR", "WARNING", "CRITICAL" ]
          }
        ]
      }, {
        "subComponentType" : "AWS::EC2::Volume",
        "alarmMetrics" : [
          {
            "alarmMetricName" : "VolumeQueueLength"
          }, {
            "alarmMetricName" : "BurstBalance"
          }
        ]
      }
    ],
    "alarms" : [
      {
        "alarmName" : "my_asg_alarm",
        "severity" : "LOW"
      }
    ]
  }
```

# Amazon EKS 集群
<a name="component-configuration-examples-eks-cluster"></a>

以下示例演示适用于 Amazon EKS 集群的 JSON 格式组件配置。

```
{
    "alarmMetrics":[
       {
          "alarmMetricName": "cluster_failed_node_count",
          "monitor":true
       },
       {
          "alarmMetricName": "node_cpu_reserved_capacity",
          "monitor":true
       },
       {
          "alarmMetricName": "node_cpu_utilization",
          "monitor":true
       },
       {
          "alarmMetricName": "node_filesystem_utilization",
          "monitor":true
       },
       {
          "alarmMetricName": "node_memory_reserved_capacity",
          "monitor":true
       },
       {
          "alarmMetricName": "node_memory_utilization",
          "monitor":true
       },
       {
          "alarmMetricName": "node_network_total_bytes",
          "monitor":true
       },
       {
          "alarmMetricName": "pod_cpu_reserved_capacity",
          "monitor":true
       },
       {
          "alarmMetricName": "pod_cpu_utilization",
          "monitor":true
       },
       {
          "alarmMetricName": "pod_cpu_utilization_over_pod_limit",
          "monitor":true
       },
       {
          "alarmMetricName": "pod_memory_reserved_capacity",
          "monitor":true
       },
       {
          "alarmMetricName": "pod_memory_utilization",
          "monitor":true
       },
       {
          "alarmMetricName": "pod_memory_utilization_over_pod_limit",
          "monitor":true
       },
       {
          "alarmMetricName": "pod_network_rx_bytes",
          "monitor":true
       },
       {
          "alarmMetricName": "pod_network_tx_bytes",
          "monitor":true
       }
    ],
    "logs":[
       {
          "logGroupName": "/aws/containerinsights/kubernetes/application",
          "logType":"APPLICATION",
          "monitor":true,
          "encoding":"utf-8"
       }
    ],
    "subComponents":[
       {
          "subComponentType":"AWS::EC2::Instance",
          "alarmMetrics":[
             {
                "alarmMetricName":"CPUUtilization",
                "monitor":true
             },
             {
                "alarmMetricName":"StatusCheckFailed",
                "monitor":true
             },
             {
                "alarmMetricName":"disk_used_percent",
                "monitor":true
             },
             {
                "alarmMetricName":"mem_used_percent",
                "monitor":true
             }
          ],
          "logs":[
             {
                "logGroupName":"APPLICATION-KubernetesClusterOnEC2-IAD",
                "logPath":"",
                "logType":"APPLICATION",
                "monitor":true,
                "encoding":"utf-8"
             }
          ],
          "processes" : [
            {
                "processName" : "my_process",
                "alarmMetrics" : [
                    {
                        "alarmMetricName" : "procstat cpu_usage",
                        "monitor" : true
                    }, {
                        "alarmMetricName" : "procstat memory_rss",
                        "monitor" : true
                    }
                ]
            }
        ],
          "windowsEvents":[
             {
                "logGroupName":"my_log_group_2",
                "eventName":"Application",
                "eventLevels":[
                   "ERROR",
                   "WARNING",
                   "CRITICAL"
                ],
                "monitor":true
             }
          ]
       },
       {
          "subComponentType":"AWS::AutoScaling::AutoScalingGroup",
          "alarmMetrics":[
             {
                "alarmMetricName":"CPUCreditBalance",
                "monitor":true
             },
             {
                "alarmMetricName":"EBSIOBalance%",
                "monitor":true
             }
          ]
       },
       {
          "subComponentType":"AWS::EC2::Volume",
          "alarmMetrics":[
             {
                "alarmMetricName":"VolumeReadBytes",
                "monitor":true
             },
             {
                "alarmMetricName":"VolumeWriteBytes",
                "monitor":true
             },
             {
                "alarmMetricName":"VolumeReadOps",
                "monitor":true
             },
             {
                "alarmMetricName":"VolumeWriteOps",
                "monitor":true
             },
             {
                "alarmMetricName":"VolumeQueueLength",
                "monitor":true
             },
             {
                "alarmMetricName":"BurstBalance",
                "monitor":true
             }
          ]
       }
    ]
 }
```

**注意**  
`AWS::EC2::Instance`、`AWS::EC2::Volume` 和 `AWS::AutoScaling::AutoScalingGroup` 的 `subComponents` 部分仅适用于在 EC2 启动类型上运行的 Amazon EKS 集群。
`AWS::EC2::Instance` 在 `subComponents` 的 `windowsEvents` 部分仅适用于 Amazon EC2 实例上运行的 Windows。

# Amazon Elastic Compute Cloud（EC2）实例
<a name="component-configuration-examples-ec2"></a>

以下示例演示适用于 Amazon EC2 实例的 JSON 格式组件配置。

**重要**  
当 Amazon EC2 实例进入 `stopped` 状态时，表示已将它从监控中移除。当它恢复为 `running` 状态时，会将它添加到 CloudWatch Application Insights 控制台 **Application details**（应用程序详细信息）页面上的 **Unmonitored components**（未监控组件）列表中。如果为应用程序启用了自动监控新资源，则会将该实例添加到 **Monitored components**（已监控组件）列表中。但会将日志和指标设置为工作负载的默认值。不会保存之前的日志和指标配置。

```
{
    "alarmMetrics" : [
      {
        "alarmMetricName" : "CPUUtilization",
        "monitor" : true
      }, {
        "alarmMetricName" : "StatusCheckFailed"
      }
    ],
    "logs" : [
      {
        "logGroupName" : "my_log_group",
        "logPath" : "C:\\LogFolder\\*",
        "logType" : "APPLICATION",
        "monitor" : true
      },
      {
        "logGroupName" : "my_log_group_2",
        "logPath" : "C:\\LogFolder2\\*",
        "logType" : "IIS",
        "encoding" : "utf-8"
      }
    ],
    "processes" : [
        {
            "processName" : "my_process",
            "alarmMetrics" : [
                {
                    "alarmMetricName" : "procstat cpu_usage",
                    "monitor" : true
                }, {
                    "alarmMetricName" : "procstat memory_rss",
                    "monitor" : true
                }
            ]
        }
    ],
    "windowsEvents" : [
      {
        "logGroupName" : "my_log_group_3",
        "eventName" : "Application",
        "eventLevels" : [ "ERROR", "WARNING", "CRITICAL" ],
        "monitor" : true
      }, {
        "logGroupName" : "my_log_group_4",
        "eventName" : "System",
        "eventLevels" : [ "ERROR", "WARNING", "CRITICAL" ],
        "monitor" : true
    }],
     "alarms" : [
      {
        "alarmName" : "my_instance_alarm_1",
        "severity" : "HIGH"
      },
      {
        "alarmName" : "my_instance_alarm_2",
        "severity" : "LOW"
      }
    ],
     "subComponents" : [
     {
       "subComponentType" : "AWS::EC2::Volume",
       "alarmMetrics" : [
       {
         "alarmMetricName" : "VolumeQueueLength",
         "monitor" : "true"
       },
       {
         "alarmMetricName" : "VolumeThroughputPercentage",
         "monitor" : "true"
       },
       {
         "alarmMetricName" : "BurstBalance",
         "monitor" : "true"
       }]
    }]
  }
```

# Amazon Elastic Container Service（Amazon ECS）
<a name="component-configuration-examples-ecs"></a>

以下示例演示适用于 Amazon Elastic Container Service (Amazon ECS) 的 JSON 格式组件配置。

```
{
    "alarmMetrics":[
       {
          "alarmMetricName":"CpuUtilized",
          "monitor":true
       },
       {
          "alarmMetricName":"MemoryUtilized",
          "monitor":true
       },
       {
          "alarmMetricName":"NetworkRxBytes",
          "monitor":true
       },
       {
          "alarmMetricName":"NetworkTxBytes",
          "monitor":true
       },
       {
          "alarmMetricName":"RunningTaskCount",
          "monitor":true
       },
       {
          "alarmMetricName":"PendingTaskCount",
          "monitor":true
       },
       {
          "alarmMetricName":"StorageReadBytes",
          "monitor":true
       },
       {
          "alarmMetricName":"StorageWriteBytes",
          "monitor":true
       }
    ],
    "logs":[
       {
          "logGroupName":"/ecs/my-task-definition",
          "logType":"APPLICATION",
          "monitor":true
       }
    ],
    "subComponents":[
       {
          "subComponentType":"AWS::ElasticLoadBalancing::LoadBalancer",
          "alarmMetrics":[
             {
                "alarmMetricName":"HTTPCode_Backend_4XX",
                "monitor":true
             },
             {
                "alarmMetricName":"HTTPCode_Backend_5XX",
                "monitor":true
             },
             {
                "alarmMetricName":"Latency",
                "monitor":true
             },
             {
                "alarmMetricName":"SurgeQueueLength",
                "monitor":true
             },
             {
                "alarmMetricName":"UnHealthyHostCount",
                "monitor":true
             }
          ]
       },
       {
          "subComponentType":"AWS::ElasticLoadBalancingV2::LoadBalancer",
          "alarmMetrics":[
             {
                "alarmMetricName":"HTTPCode_Target_4XX_Count",
                "monitor":true
             },
             {
                "alarmMetricName":"HTTPCode_Target_5XX_Count",
                "monitor":true
             },
             {
                "alarmMetricName":"TargetResponseTime",
                "monitor":true
             },
             {
                "alarmMetricName":"UnHealthyHostCount",
                "monitor":true
             }
          ]
       },
       {
          "subComponentType":"AWS::EC2::Instance",
          "alarmMetrics":[
             {
                "alarmMetricName":"CPUUtilization",
                "monitor":true
             },
             {
                "alarmMetricName":"StatusCheckFailed",
                "monitor":true
             },
             {
                "alarmMetricName":"disk_used_percent",
                "monitor":true
             },
             {
                "alarmMetricName":"mem_used_percent",
                "monitor":true
             }
          ],
          "logs":[
             {
                "logGroupName":"my_log_group",
                "logPath":"/mylog/path",
                "logType":"APPLICATION",
                "monitor":true
             }
          ],
          "processes" : [
             {
                "processName" : "my_process",
                "alarmMetrics" : [
                    {
                        "alarmMetricName" : "procstat cpu_usage",
                        "monitor" : true
                    }, {
                        "alarmMetricName" : "procstat memory_rss",
                        "monitor" : true
                    }
                 ]
             }
          ],
          "windowsEvents":[
             {
                "logGroupName":"my_log_group_2",
                "eventName":"Application",
                "eventLevels":[
                   "ERROR",
                   "WARNING",
                   "CRITICAL"
                ],
                "monitor":true
             }
          ]
       },
       {
          "subComponentType":"AWS::EC2::Volume",
          "alarmMetrics":[
             {
                "alarmMetricName":"VolumeQueueLength",
                "monitor":"true"
             },
             {
                "alarmMetricName":"VolumeThroughputPercentage",
                "monitor":"true"
             },
             {
                "alarmMetricName":"BurstBalance",
                "monitor":"true"
             }
          ]
       }
    ]
 }
```

**注意**  
`AWS::EC2::Instance` 和 `AWS::EC2::Volume` 的 `subComponents` 部分仅适用于 ECS 服务或 ECS 任务在 EC2 启动类型上运行的 Amazon ECS 集群。
`AWS::EC2::Instance` 在 `subComponents` 的 `windowsEvents` 部分仅适用于 Amazon EC2 实例上运行的 Windows。

# Amazon ECS 服务
<a name="component-configuration-examples-ecs-service"></a>

以下示例演示了一个 JSON 格式的 Amazon ECS 服务组件配置。

```
{
    "alarmMetrics":[
       {
          "alarmMetricName":"CPUUtilization",
          "monitor":true
       },
       {
          "alarmMetricName":"MemoryUtilization",
          "monitor":true
       },
       {
          "alarmMetricName":"CpuUtilized",
          "monitor":true
       },
       {
          "alarmMetricName":"MemoryUtilized",
          "monitor":true
       },
       {
          "alarmMetricName":"NetworkRxBytes",
          "monitor":true
       },
       {
          "alarmMetricName":"NetworkTxBytes",
          "monitor":true
       },
       {
          "alarmMetricName":"RunningTaskCount",
          "monitor":true
       },
       {
          "alarmMetricName":"PendingTaskCount",
          "monitor":true
       },
       {
          "alarmMetricName":"StorageReadBytes",
          "monitor":true
       },
       {
          "alarmMetricName":"StorageWriteBytes",
          "monitor":true
       }
    ],
    "logs":[
       {
          "logGroupName":"/ecs/my-task-definition",
          "logType":"APPLICATION",
          "monitor":true
       }
    ],
    "subComponents":[
       {
          "subComponentType":"AWS::ElasticLoadBalancing::LoadBalancer",
          "alarmMetrics":[
             {
                "alarmMetricName":"HTTPCode_Backend_4XX",
                "monitor":true
             },
             {
                "alarmMetricName":"HTTPCode_Backend_5XX",
                "monitor":true
             },
             {
                "alarmMetricName":"Latency",
                "monitor":true
             },
             {
                "alarmMetricName":"SurgeQueueLength",
                "monitor":true
             },
             {
                "alarmMetricName":"UnHealthyHostCount",
                "monitor":true
             }
          ]
       },
       {
          "subComponentType":"AWS::ElasticLoadBalancingV2::LoadBalancer",
          "alarmMetrics":[
             {
                "alarmMetricName":"HTTPCode_Target_4XX_Count",
                "monitor":true
             },
             {
                "alarmMetricName":"HTTPCode_Target_5XX_Count",
                "monitor":true
             },
             {
                "alarmMetricName":"TargetResponseTime",
                "monitor":true
             },
             {
                "alarmMetricName":"UnHealthyHostCount",
                "monitor":true
             }
          ]
       },
       {
          "subComponentType":"AWS::EC2::Instance",
          "alarmMetrics":[
             {
                "alarmMetricName":"CPUUtilization",
                "monitor":true
             },
             {
                "alarmMetricName":"StatusCheckFailed",
                "monitor":true
             },
             {
                "alarmMetricName":"disk_used_percent",
                "monitor":true
             },
             {
                "alarmMetricName":"mem_used_percent",
                "monitor":true
             }
          ],
          "logs":[
             {
                "logGroupName":"my_log_group",
                "logPath":"/mylog/path",
                "logType":"APPLICATION",
                "monitor":true
             }
          ],
          "processes" : [
             {
                "processName" : "my_process",
                "alarmMetrics" : [
                {
                    "alarmMetricName" : "procstat cpu_usage",
                    "monitor" : true
                }, {
                    "alarmMetricName" : "procstat memory_rss",
                    "monitor" : true
                }
            ]
        }
    ],
          "windowsEvents":[
             {
                "logGroupName":"my_log_group_2",
                "eventName":"Application",
                "eventLevels":[
                   "ERROR",
                   "WARNING",
                   "CRITICAL"
                ],
                "monitor":true
             }
          ]
       },
       {
          "subComponentType":"AWS::EC2::Volume",
          "alarmMetrics":[
             {
                "alarmMetricName":"VolumeQueueLength",
                "monitor":"true"
             },
             {
                "alarmMetricName":"VolumeThroughputPercentage",
                "monitor":"true"
             },
             {
                "alarmMetricName":"BurstBalance",
                "monitor":"true"
             }
          ]
       }
    ]
 }
```

**注意**  
`AWS::EC2::Instance` 和 `AWS::EC2::Volume` 的 `subComponents` 部分仅适用于在 EC2 启动类型上运行的 Amazon ECS。
`AWS::EC2::Instance` 在 `subComponents` 的 `windowsEvents` 部分仅适用于 Amazon EC2 实例上运行的 Windows。

# Amazon ECS 任务
<a name="component-configuration-examples-ecs-task"></a>

以下示例演示了一个 JSON 格式的 Amazon ECS 任务组件配置。

```
{
    "logs":[
       {
          "logGroupName":"/ecs/my-task-definition",
          "logType":"APPLICATION",
          "monitor":true
       }
    ],
    "processes" : [
        {
            "processName" : "my_process",
            "alarmMetrics" : [
                {
                    "alarmMetricName" : "procstat cpu_usage",
                    "monitor" : true
                }, {
                    "alarmMetricName" : "procstat memory_rss",
                    "monitor" : true
                }
            ]
        }
    ]
 }
```

# Amazon Elastic File System (Amazon EFS)
<a name="component-configuration-examples-efs"></a>

以下示例演示了一个 JSON 格式的 Amazon EFS 组件配置。

```
{
   "alarmMetrics": [
     {
       "alarmMetricName": "BurstCreditBalance",
       "monitor": true
     },
     {
       "alarmMetricName": "PercentIOLimit",
       "monitor": true
     },
     {
       "alarmMetricName": "PermittedThroughput",
       "monitor": true
     },
     {
       "alarmMetricName": "MeteredIOBytes",
       "monitor": true
     },
     {
       "alarmMetricName": "TotalIOBytes",
       "monitor": true
     },
     {
       "alarmMetricName": "DataWriteIOBytes",
       "monitor": true
     },
     {
       "alarmMetricName": "DataReadIOBytes",
       "monitor": true
     },
     {
       "alarmMetricName": "MetadataIOBytes",
       "monitor": true
     },
     {
       "alarmMetricName": "ClientConnections",
       "monitor": true
     },
     {
       "alarmMetricName": "TimeSinceLastSync",
       "monitor": true
     },
     {
       "alarmMetricName": "Throughput",
       "monitor": true
     },
     {
       "alarmMetricName": "PercentageOfPermittedThroughputUtilization",
       "monitor": true
     },
     {
       "alarmMetricName": "ThroughputIOPS",
       "monitor": true
     },
     {
       "alarmMetricName": "PercentThroughputDataReadIOBytes",
       "monitor": true
     },
     {
       "alarmMetricName": "PercentThroughputDataWriteIOBytes",
       "monitor": true
     },
     {
       "alarmMetricName": "PercentageOfIOPSDataReadIOBytes",
       "monitor": true
     },
     {
       "alarmMetricName": "PercentageOfIOPSDataWriteIOBytes",
       "monitor": true
     },
     {
       "alarmMetricName": "AverageDataReadIOBytesSize",
       "monitor": true
     },
     {
       "alarmMetricName": "AverageDataWriteIOBytesSize",
       "monitor": true
     }
   ],
   "logs": [
    {
    "logGroupName": "/aws/efs/utils",
    "logType": "EFS_MOUNT_STATUS",
    "monitor": true,
    }
   ]
 }
```

# Amazon FSx
<a name="component-configuration-examples-fsx"></a>

以下示例演示适用于 Amazon FSx 的 JSON 格式组件配置。

```
{
  "alarmMetrics": [
    {
      "alarmMetricName": "DataReadBytes",
      "monitor": true
    },
    {
      "alarmMetricName": "DataWriteBytes",
      "monitor": true
    },
    {
      "alarmMetricName": "DataReadOperations",
      "monitor": true
    },
    {
      "alarmMetricName": "DataWriteOperations",
      "monitor": true
    },
    {
      "alarmMetricName": "MetadataOperations",
      "monitor": true
    },
    {
      "alarmMetricName": "FreeStorageCapacity",
      "monitor": true
    }
  ]
}
```

# Amazon Relational Database Service (RDS) Aurora MySQL
<a name="component-configuration-examples-rds-aurora"></a>

以下示例演示适用于 Amazon RDS Aurora MySQL 的 JSON 格式组件配置。

```
{
  "alarmMetrics": [
    {
      "alarmMetricName": "CPUUtilization",
      "monitor": true
    },
    {
      "alarmMetricName": "CommitLatency",
      "monitor": true
    }
  ],
  "logs": [
    {
      "logType": "MYSQL",
      "monitor": true,
    },
    {
      "logType": "MYSQL_SLOW_QUERY",
      "monitor": false
    }
  ]
}
```

# Amazon Relational Database Service（RDS）实例
<a name="component-configuration-examples-rds"></a>

以下示例演示适用于 Amazon RDS 实例的 JSON 格式组件配置。

```
{
  "alarmMetrics" : [
    {
      "alarmMetricName" : "BurstBalance",
      "monitor" : true
    }, {
      "alarmMetricName" : "WriteThroughput",
      "monitor" : false
    }
  ],

  "alarms" : [
    {
      "alarmName" : "my_rds_instance_alarm",
      "severity" : "MEDIUM"
    }
  ]
}
```

# Amazon Route 53 运行状况检查
<a name="component-configuration-examples-health-check"></a>

以下示例演示了一个 JSON 格式的 Amazon Route 53 运行状况检查。

```
{
  "alarmMetrics": [
    {
      "alarmMetricName": "ChildHealthCheckHealthyCount",
      "monitor": true
    },
    {
      "alarmMetricName": "ConnectionTime",
      "monitor": true
    },
    {
      "alarmMetricName": "HealthCheckPercentageHealthy",
      "monitor": true
    },
    {
      "alarmMetricName": "HealthCheckStatus",
      "monitor": true
    },
    {
      "alarmMetricName": "SSLHandshakeTime",
      "monitor": true
    },
    {
      "alarmMetricName": "TimeToFirstByte",
      "monitor": true
    }
  ]  
}
```

# Amazon Route 53 托管区
<a name="component-configuration-examples-hosted-zone"></a>

以下示例演示了一个 JSON 格式的 Amazon Route 53 托管区。

```
{
  "alarmMetrics": [
    {
      "alarmMetricName": "DNSQueries",
      "monitor": true
    },
    {
      "alarmMetricName": "DNSSECInternalFailure",
      "monitor": true
    },
    {
      "alarmMetricName": "DNSSECKeySigningKeysNeedingAction",
      "monitor": true
    },
    {
      "alarmMetricName": "DNSSECKeySigningKeyMaxNeedingActionAge",
      "monitor": true
    },
    {
      "alarmMetricName": "DNSSECKeySigningKeyAge",
      "monitor": true
    }
  ],
  "logs": [
    {
      "logGroupName":"/hosted-zone/logs",
      "logType": "ROUTE53_DNS_PUBLIC_QUERY_LOGS",
      "monitor": true
    }
  ]
}
```

# Amazon Route 53 Resolver 端点
<a name="component-configuration-examples-resolver-endpoint"></a>

以下示例演示适用于 Amazon Route 53 Resolver 端点的 JSON 格式组件配置。

```
{
  "alarmMetrics": [
    {
      "alarmMetricName": "EndpointHealthyENICount",
      "monitor": true
    },
    {
      "alarmMetricName": "EndpointUnHealthyENICount",
      "monitor": true
    },
    {
      "alarmMetricName": "InboundQueryVolume",
      "monitor": true
    },
    {
      "alarmMetricName": "OutboundQueryVolume",
      "monitor": true
    },
    {
      "alarmMetricName": "OutboundQueryAggregateVolume",
      "monitor": true
    }
  ]  
}
```

# Amazon Route 53 Resolver 查询日志记录配置
<a name="component-configuration-examples-resolver-query-logging"></a>

下面的例子演示了适用于 Amazon Route 53 Resolver 查询日志记录配置的 JSON 格式的组件配置。

```
{
  "logs": [
    {
      "logGroupName": "/resolver-query-log-config/logs",
      "logType": "ROUTE53_RESOLVER_QUERY_LOGS",
      "monitor": true
    }
  ]  
}
```

# Amazon S3 存储桶
<a name="component-configuration-examples-s3"></a>

以下示例演示适用于 Amazon S3 存储桶的 JSON 格式组件配置。

```
{
    "alarmMetrics" : [
        {
            "alarmMetricName" : "ReplicationLatency",
            "monitor" : true
        }, {
            "alarmMetricName" : "5xxErrors",
            "monitor" : true
        }, {
            "alarmMetricName" : "BytesDownloaded"
            "monitor" : true
        }
    ]
}
```

# Amazon Simple Queue Service (SQS)
<a name="component-configuration-examples-sqs"></a>

以下示例演示适用于 Amazon Simple Queue Service 的 JSON 格式组件配置。

```
{
  "alarmMetrics" : [
    {
      "alarmMetricName" : "ApproximateAgeOfOldestMessage"
    }, {
      "alarmMetricName" : "NumberOfEmptyReceives"
    }
  ],
  "alarms" : [
    {
      "alarmName" : "my_sqs_alarm",
      "severity" : "MEDIUM"
    }
  ]
}
```

# Amazon SNS 主题
<a name="component-configuration-examples-sns"></a>

以下示例演示适用于 Amazon SNS 主题的 JSON 格式组件配置。

```
{
  "alarmMetrics": [
    {
      "alarmMetricName": "NumberOfNotificationsFailed",
      "monitor": true
    },
    {
      "alarmMetricName": "NumberOfNotificationsFilteredOut-InvalidAttributes",
      "monitor": true
    },
    {
      "alarmMetricName": "NumberOfNotificationsFilteredOut-NoMessageAttributes",
      "monitor": true
    },
    {
      "alarmMetricName": "NumberOfNotificationsFailedToRedriveToDlq",
      "monitor": true
    }
  ]
}
```

# Amazon Virtual Private Cloud (Amazon VPC)
<a name="component-configuration-examples-vpc"></a>

以下示例演示了适用于 Amazon VPC 的 JSON 格式的组件配置。

```
{
  "alarmMetrics": [
    {
      "alarmMetricName": "NetworkAddressUsage",
      "monitor": true
    },
    {
      "alarmMetricName": "NetworkAddressUsagePeered",
      "monitor": true
    },
    {
      "alarmMetricName": "VPCFirewallQueryVolume",
      "monitor": true
    }
  ]
}
```

# Amazon VPC 网络地址转换（NAT）网关
<a name="component-configuration-examples-nat-gateway"></a>

以下示例演示了适用于 NAT 网关的 JSON 格式的组件配置。

```
{
  "alarmMetrics": [
    {
      "alarmMetricName": "ErrorPortAllocation",
      "monitor": true
    },
    {
      "alarmMetricName": "IdleTimeoutCount",
      "monitor": true
    }
  ]
}
```

# API Gateway REST API 阶段
<a name="component-configuration-examples-api-gateway"></a>

以下示例演示适用于 API Gateway REST API 阶段的 JSON 格式组件配置。

```
{ 
     "alarmMetrics" : [ 
         {
             "alarmMetricName" : "4XXError",   
             "monitor" : true
         }, 
         {
             "alarmMetricName" : "5XXError",   
             "monitor" : true
         } 
     ],
    "logs" : [
        { 
            "logType" : "API_GATEWAY_EXECUTION",   
            "monitor" : true  
        },
        { 
            "logType" : "API_GATEWAY_ACCESS",   
            "monitor" : true  
        }
    ]
}
```

# Application Elastic Load Balancing
<a name="component-configuration-examples-application-elb"></a>

以下示例演示适用于 Application Elastic Load Balancing 的 JSON 格式组件配置。

```
{
  "alarmMetrics": [
    {
      "alarmMetricName": "ActiveConnectionCount",
    }, {
      "alarmMetricName": "TargetResponseTime"
    }
  ],  
  "subComponents": [
    {
      "subComponentType": "AWS::EC2::Instance",
      "alarmMetrics": [
        {
          "alarmMetricName": "CPUUtilization",
        }, {
          "alarmMetricName": "StatusCheckFailed"
        }
      ],
      "logs": [
        {
          "logGroupName": "my_log_group",
          "logPath": "C:\\LogFolder\\*",
          "logType": "APPLICATION",
        }
      ],
      "windowsEvents": [
        {
          "logGroupName": "my_log_group_2",
          "eventName": "Application",
          "eventLevels": [ "ERROR", "WARNING", "CRITICAL" ]
        }
      ]
    }, {
      "subComponentType": "AWS::EC2::Volume",
      "alarmMetrics": [
        {
          "alarmMetricName": "VolumeQueueLength",
        }, {
          "alarmMetricName": "BurstBalance"
        }
      ]
    }
  ],

  "alarms": [
    {
      "alarmName": "my_alb_alarm",
      "severity": "LOW"
    }
  ]
}
```

# AWS Lambda 函数
<a name="component-configuration-examples-lambda"></a>

以下示例演示适用于 AWS Lambda Function 的 JSON 格式组件配置。

```
{
  "alarmMetrics": [
    {
      "alarmMetricName": "Errors",
      "monitor": true
    },
    {
      "alarmMetricName": "Throttles",
      "monitor": true
    },
    {
      "alarmMetricName": "IteratorAge",
      "monitor": true
    },
    {
      "alarmMetricName": "Duration",
      "monitor": true
    }
  ],
  "logs": [
    {
      "logType": "DEFAULT",
      "monitor": true
    }
  ]
}
```

# AWS Network Firewall 规则组
<a name="component-configuration-examples-firewall-rule-group"></a>

以下示例演示了适用于 AWS Network Firewall 规则组的 JSON 格式的组件配置。

```
{
  "alarmMetrics": [
    {
      "alarmMetricName": "FirewallRuleGroupQueryVolume",
      "monitor": true
    }
  ]
}
```

# AWS Network Firewall 规则组关联
<a name="component-configuration-examples-firewall-rule-group-assoc"></a>

以下示例演示了适用于 AWS Network Firewall 规则组关联的 JSON 格式的组件配置。

```
{
  "alarmMetrics": [
    {
      "alarmMetricName": "FirewallRuleGroupQueryVolume",
      "monitor": true
    }
  ]
}
```

# AWS Step Functions
<a name="component-configuration-examples-step-functions"></a>

以下示例演示适用于 AWS Step Functions 的 JSON 格式组件配置。

```
{
  "alarmMetrics": [
    {
      "alarmMetricName": "ExecutionsFailed",
      "monitor": true
    },
    {
      "alarmMetricName": "LambdaFunctionsFailed",
      "monitor": true
    },
    {
      "alarmMetricName": "ProvisionedRefillRate",
      "monitor": true
    }
  ],
  "logs": [
    {
     "logGroupName": "/aws/states/HelloWorld-Logs",
      "logType": "STEP_FUNCTION",
      "monitor": true,
    }
  ]
}
```

# 客户分组的 Amazon EC2 实例
<a name="component-configuration-examples-grouped-ec2"></a>

以下示例演示适用于客户分组的 Amazon EC2 实例的 JSON 格式组件配置。

```
{
    "subComponents": [
      {
        "subComponentType": "AWS::EC2::Instance",
        "alarmMetrics": [
          {
            "alarmMetricName": "CPUUtilization",
          }, 
          {
            "alarmMetricName": "StatusCheckFailed"
          }
        ],
        "logs": [
          {
            "logGroupName": "my_log_group",
            "logPath": "C:\\LogFolder\\*",
            "logType": "APPLICATION",
          }
        ],
        "processes": [
            {
                "processName": "my_process",
                "alarmMetrics": [
                    {
                        "alarmMetricName": "procstat cpu_usage",
                        "monitor": true
                    }, {
                        "alarmMetricName": "procstat memory_rss",
                        "monitor": true
                    }
                ]
            }
        ],
        "windowsEvents": [
          {
            "logGroupName": "my_log_group_2",
            "eventName": "Application",
            "eventLevels": [ "ERROR", "WARNING", "CRITICAL" ]
          }
        ]
      }, {
        "subComponentType": "AWS::EC2::Volume",
        "alarmMetrics": [
          {
            "alarmMetricName": "VolumeQueueLength",
          }, {
            "alarmMetricName": "BurstBalance"
          }
        ]
      }
    ],
    "alarms": [
      {
        "alarmName": "my_alarm",
        "severity": "MEDIUM"
      }
    ]
  }
```

# Elastic Load Balancing
<a name="component-configuration-examples-elb"></a>

以下示例演示适用于 Elastic Load Balancing 的 JSON 格式组件配置。

```
{
    "alarmMetrics": [
      {
        "alarmMetricName": "EstimatedALBActiveConnectionCount"
      }, {
        "alarmMetricName": "HTTPCode_Backend_5XX"
      }
    ],
    "subComponents": [
      {
        "subComponentType": "AWS::EC2::Instance",
        "alarmMetrics": [
          {
            "alarmMetricName": "CPUUtilization"
          }, {
            "alarmMetricName": "StatusCheckFailed"
          }
        ],
        "logs": [
          {
            "logGroupName": "my_log_group",
            "logPath": "C:\\LogFolder\\*",
            "logType": "APPLICATION"
          }
        ],
        "processes": [
          {
            "processName": "my_process",
            "alarmMetrics": [
                {
                  "alarmMetricName": "procstat cpu_usage",
                  "monitor": true
                }, {
                  "alarmMetricName": "procstat memory_rss",
                  "monitor": true
                }
              ]
          }
        ],
        "windowsEvents": [
          {
            "logGroupName": "my_log_group_2",
            "eventName": "Application",
            "eventLevels": [ "ERROR", "WARNING", "CRITICAL" ],
            "monitor": true
          }
        ]
      }, {
        "subComponentType": "AWS::EC2::Volume",
        "alarmMetrics": [
          {
            "alarmMetricName": "VolumeQueueLength"
          }, {
            "alarmMetricName": "BurstBalance"
          }
        ]
      }
    ],
  
    "alarms": [
      {
        "alarmName": "my_elb_alarm",
        "severity": "HIGH"
      }
    ]
  }
```

# Java
<a name="component-configuration-examples-java"></a>

以下示例演示适用于 Java 的 JSON 格式组件配置。

```
{
  "alarmMetrics": [ {
    "alarmMetricName": "java_lang_threading_threadcount",
    "monitor": true
  },
  {
    "alarmMetricName": "java_lang_memory_heapmemoryusage_used",
    "monitor": true
  },
  {
    "alarmMetricName": "java_lang_memory_heapmemoryusage_committed",
    "monitor": true
  }],
  "logs": [ ],
  "JMXPrometheusExporter": {
      "hostPort": "8686",
      "prometheusPort": "9404"
  }
}
```

**注意**  
Application Insights 不支持为 Prometheus JMX Exporter 配置身份验证。有关如何设置身份验证的信息，请参阅 [Prometheus JMX Exporter 示例配置](https://github.com/prometheus/jmx_exporter#configuration)。

# Amazon EC2 上的 Kubernetes
<a name="component-configuration-examples-kubernetes-ec2"></a>

以下示例演示适用于 Amazon EC2 上 Kubernetes 的 JSON 格式组件配置。

```
{
    "alarmMetrics":[
       {
          "alarmMetricName":"cluster_failed_node_count",
          "monitor":true
       },
       {
          "alarmMetricName":"node_cpu_reserved_capacity",
          "monitor":true
       },
       {
          "alarmMetricName":"node_cpu_utilization",
          "monitor":true
       },
       {
          "alarmMetricName":"node_filesystem_utilization",
          "monitor":true
       },
       {
          "alarmMetricName":"node_memory_reserved_capacity",
          "monitor":true
       },
       {
          "alarmMetricName":"node_memory_utilization",
          "monitor":true
       },
       {
          "alarmMetricName":"node_network_total_bytes",
          "monitor":true
       },
       {
          "alarmMetricName":"pod_cpu_reserved_capacity",
          "monitor":true
       },
       {
          "alarmMetricName":"pod_cpu_utilization",
          "monitor":true
       },
       {
          "alarmMetricName":"pod_cpu_utilization_over_pod_limit",
          "monitor":true
       },
       {
          "alarmMetricName":"pod_memory_reserved_capacity",
          "monitor":true
       },
       {
          "alarmMetricName":"pod_memory_utilization",
          "monitor":true
       },
       {
          "alarmMetricName":"pod_memory_utilization_over_pod_limit",
          "monitor":true
       },
       {
          "alarmMetricName":"pod_network_rx_bytes",
          "monitor":true
       },
       {
          "alarmMetricName":"pod_network_tx_bytes",
          "monitor":true
       }
    ],
    "logs":[
       {
          "logGroupName":"/aws/containerinsights/kubernetes/application",
          "logType":"APPLICATION",
          "monitor":true,
          "encoding":"utf-8"
       }
    ],
    "subComponents":[
       {
          "subComponentType":"AWS::EC2::Instance",
          "alarmMetrics":[
             {
                "alarmMetricName":"CPUUtilization",
                "monitor":true
             },
             {
                "alarmMetricName":"StatusCheckFailed",
                "monitor":true
             },
             {
                "alarmMetricName":"disk_used_percent",
                "monitor":true
             },
             {
                "alarmMetricName":"mem_used_percent",
                "monitor":true
             }
          ],
          "logs":[
             {
                "logGroupName":"APPLICATION-KubernetesClusterOnEC2-IAD",
                "logPath":"",
                "logType":"APPLICATION",
                "monitor":true,
                "encoding":"utf-8"
             }
          ],
          "processes" : [
            {
                "processName" : "my_process",
                "alarmMetrics" : [
                    {
                        "alarmMetricName" : "procstat cpu_usage",
                        "monitor" : true
                    }, {
                        "alarmMetricName" : "procstat memory_rss",
                        "monitor" : true
                    }
                ]
            }
        ]
       },
       {
          "subComponentType":"AWS::EC2::Volume",
          "alarmMetrics":[
             {
                "alarmMetricName":"VolumeReadBytes",
                "monitor":true
             },
             {
                "alarmMetricName":"VolumeWriteBytes",
                "monitor":true
             },
             {
                "alarmMetricName":"VolumeReadOps",
                "monitor":true
             },
             {
                "alarmMetricName":"VolumeWriteOps",
                "monitor":true
             },
             {
                "alarmMetricName":"VolumeQueueLength",
                "monitor":true
             },
             {
                "alarmMetricName":"BurstBalance",
                "monitor":true
             }
          ]
       }
    ]
 }
```

# RDS MariaDB 和 RDS MySQL
<a name="component-configuration-examples-mysql"></a>

以下示例演示适用于 RDS MariaDB 和 RDS MySQL 的 JSON 格式组件配置。

```
{
  "alarmMetrics": [
    {
      "alarmMetricName": "CPUUtilization",
      "monitor": true
    }
  ],
  "logs": [
    {
      "logType": "MYSQL",
      "monitor": true,
    },
    {
      "logType": "MYSQL_SLOW_QUERY",
      "monitor": false
    }
  ]
}
```

# RDS Oracle
<a name="component-configuration-examples-oracle"></a>

以下示例演示适用于 RDS Oracle 的 JSON 格式组件配置。

```
{
  "alarmMetrics": [
    {
      "alarmMetricName": "CPUUtilization",
      "monitor": true
    }
  ],
  "logs": [
    {
      "logType": "ORACLE_ALERT",
      "monitor": true,
    },
    {
      "logType": "ORACLE_LISTENER",
      "monitor": false
    }
  ]
}
```

# RDS PostgreSQL
<a name="component-configuration-examples-rds-postgre-sql"></a>

以下示例演示适用于 RDS PostgreSQL 的 JSON 格式组件配置。

```
{
  "alarmMetrics": [
    {
      "alarmMetricName": "CPUUtilization",
      "monitor": true
    }
  ],
  "logs": [
    {
      "logType": "POSTGRESQL",
      "monitor": true
    }
  ]
}
```

# Amazon EC2 上的 SAP ASE
<a name="component-configuration-examples-sap-ase"></a>

以下示例显示了适用于 Amazon EC2 上 SAP ASE 的 JSON 格式组件配置。

```
{
  "subComponents": [
    {
      "subComponentType": "AWS::EC2::Instance",
      "alarmMetrics": [
        {
          "alarmMetricName": "asedb_database_availability",
          "monitor": true
        },
        {
          "alarmMetricName": "asedb_trunc_log_on_chkpt_enabled",
          "monitor": true
        },
        {
          "alarmMetricName": "asedb_last_db_backup_age_in_days",
          "monitor": true
        },
        {
          "alarmMetricName": "asedb_last_transaction_log_backup_age_in_hours",
          "monitor": true
        },
        {
          "alarmMetricName": "asedb_suspected_database",
          "monitor": true
        },
        {
          "alarmMetricName": "asedb_db_space_usage_percent",
          "monitor": true
        },
        {
          "alarmMetricName": "asedb_db_log_space_usage_percent",
          "monitor": true
        },
        {
          "alarmMetricName": "asedb_locked_login",
          "monitor": true
        },
        {
          "alarmMetricName": "asedb_data_cache_hit_ratio",
          "monitor": true
        }
      ],
      "logs": [
        {
          "logGroupName": "SAP_ASE_SERVER_LOGS-my-resource-group",
          "logPath": "/sybase/SY2/ASE-*/install/SY2.log",
          "logType": "SAP_ASE_SERVER_LOGS",
          "monitor": true,
          "encoding": "utf-8"
        },
        {
          "logGroupName": "SAP_ASE_BACKUP_SERVER_LOGS-my-resource-group",
          "logPath": "/sybase/SY2/ASE-*/install/SY2_BS.log",
          "logType": "SAP_ASE_BACKUP_SERVER_LOGS",
          "monitor": true,
          "encoding": "utf-8"
        }
  ],
  "sapAsePrometheusExporter": {
    "sapAseSid": "ASE",
    "sapAsePort": "4901",
    "sapAseSecretName": "ASE_DB_CREDS",
    "prometheusPort": "9399",
    "agreeToEnableASEMonitoring": true
}
```

# Amazon EC2 上的 SAP ASE 高可用性
<a name="component-configuration-examples-sap-ase-ha"></a>

以下示例显示了适用于 Amazon EC2 上 SAP ASE 高可用性的 JSON 格式组件配置。

```
{
  "subComponents": [
    {
      "subComponentType": "AWS::EC2::Instance",
      "alarmMetrics": [
        {
          "alarmMetricName": "asedb_database_availability",
          "monitor": true
        },
        {
          "alarmMetricName": "asedb_trunc_log_on_chkpt_enabled",
          "monitor": true
        },
        {
          "alarmMetricName": "asedb_last_db_backup_age_in_days",
          "monitor": true
        },
        {
          "alarmMetricName": "asedb_last_transaction_log_backup_age_in_hours",
          "monitor": true
        },
        {
          "alarmMetricName": "asedb_suspected_database",
          "monitor": true
        },
        {
          "alarmMetricName": "asedb_db_space_usage_percent",
          "monitor": true
        },
        {
          "alarmMetricName": "asedb_ha_replication_state",
          "monitor": true
        },
        {
          "alarmMetricName": "asedb_ha_replication_mode",
          "monitor": true
        },
        {
          "alarmMetricName": "asedb_ha_replication_latency_in_minutes",
          "monitor": true
        }
      ],
      "logs": [
        {
          "logGroupName": "SAP_ASE_SERVER_LOGS-my-resource-group",
          "logPath": "/sybase/SY2/ASE-*/install/SY2.log",
          "logType": "SAP_ASE_SERVER_LOGS",
          "monitor": true,
          "encoding": "utf-8"
        },
        {
          "logGroupName": "SAP_ASE_BACKUP_SERVER_LOGS-my-resource-group",
          "logPath": "/sybase/SY2/ASE-*/install/SY2_BS.log",
          "logType": "SAP_ASE_BACKUP_SERVER_LOGS",
          "monitor": true,
          "encoding": "utf-8"
        },
        {
          "logGroupName": "SAP_ASE_REP_SERVER_LOGS-my-resource-group",
          "logPath": "/sybase/SY2/DM/repservername/repservername.log",
          "logType": "SAP_ASE_REP_SERVER_LOGS",
          "monitor": true,
          "encoding": "utf-8"
        },
        {
          "logGroupName": "SAP_ASE_RMA_AGENT_LOGS-my-resource-group",
          "logPath": "/sybase/SY2/DM/RMA-*/instances/AgentContainer/logs/",
          "logType": "SAP_ASE_RMA_AGENT_LOGS",
          "monitor": true,
          "encoding": "utf-8"
        },
        {
          "logGroupName": "SAP_ASE_FAULT_MANAGER_LOGS-my-resource-group",
          "logPath": "/opt/sap/FaultManager/dev_sybdbfm",
          "logType": "SAP_ASE_FAULT_MANAGER_LOGS",
          "monitor": true,
          "encoding": "utf-8"
        }
  ],
  "sapAsePrometheusExporter": {
    "sapAseSid": "ASE",
    "sapAsePort": "4901",
    "sapAseSecretName": "ASE_DB_CREDS",
    "prometheusPort": "9399",
    "agreeToEnableASEMonitoring": true
}
```

# Amazon EC2 上的 SAP HANA
<a name="component-configuration-examples-hana"></a>

以下示例演示适用于 Amazon EC2 上 SAP HANA 的 JSON 格式组件配置。

```
{
  "subComponents": [
    {
      "subComponentType": "AWS::EC2::Instance",
      "alarmMetrics": [
        {
          "alarmMetricName": "hanadb_server_startup_time_variations_seconds",
          "monitor": true
        },
        {
          "alarmMetricName": "hanadb_level_5_alerts_count",
          "monitor": true
        },
        {
          "alarmMetricName": "hanadb_level_4_alerts_count",
          "monitor": true
        },
        {
          "alarmMetricName": "hanadb_out_of_memory_events_count",
          "monitor": true
        },
        {
          "alarmMetricName": "hanadb_max_trigger_read_ratio_percent",
          "monitor": true
        },
        {
          "alarmMetricName": "hanadb_table_allocation_limit_used_percent",
          "monitor": true
        },
        {
          "alarmMetricName": "hanadb_cpu_usage_percent",
          "monitor": true
        },
        {
          "alarmMetricName": "hanadb_plan_cache_hit_ratio_percent",
          "monitor": true
        },
        {
          "alarmMetricName": "hanadb_last_data_backup_age_days",
          "monitor": true
        }
      ],
      "logs": [
        {
          "logGroupName": "SAP_HANA_TRACE-my-resourge-group",
          "logPath": "/usr/sap/HDB/HDB00/*/trace/*.trc",
          "logType": "SAP_HANA_TRACE",
          "monitor": true,
          "encoding": "utf-8"
        },
        {
          "logGroupName": "SAP_HANA_LOGS-my-resource-group",
          "logPath": "/usr/sap/HDB/HDB00/*/trace/*.log",
          "logType": "SAP_HANA_LOGS",
          "monitor": true,
          "encoding": "utf-8"
        }
      ]
    }
  ],
  "hanaPrometheusExporter": {
    "hanaSid": "HDB",
    "hanaPort": "30013",
    "hanaSecretName": "HANA_DB_CREDS",
    "prometheusPort": "9668"
  }
}
```

# Amazon EC2 上的 SAP HANA 高可用性
<a name="component-configuration-examples-hana-ha"></a>

以下示例演示适用于 Amazon EC2 上 SAP HANA 高可用性的 JSON 格式组件配置。

```
{
  "subComponents": [
    {
      "subComponentType": "AWS::EC2::Instance",
      "alarmMetrics": [
        {
          "alarmMetricName": "hanadb_server_startup_time_variations_seconds",
          "monitor": true
        },
        {
          "alarmMetricName": "hanadb_level_5_alerts_count",
          "monitor": true
        },
        {
          "alarmMetricName": "hanadb_level_4_alerts_count",
          "monitor": true
        },
        {
          "alarmMetricName": "hanadb_out_of_memory_events_count",
          "monitor": true
        },
        {
          "alarmMetricName": "ha_cluster_pacemaker_stonith_enabled",
          "monitor": true
        }
      ],
      "logs": [
        {
          "logGroupName": "SAP_HANA_TRACE-my-resourge-group",
          "logPath": "/usr/sap/HDB/HDB00/*/trace/*.trc",
          "logType": "SAP_HANA_TRACE",
          "monitor": true,
          "encoding": "utf-8"
        },
        {
          "logGroupName": "SAP_HANA_HIGH_AVAILABILITY-my-resource-group",
          "logPath": "/var/log/pacemaker/pacemaker.log",
          "logType": "SAP_HANA_HIGH_AVAILABILITY",
          "monitor": true,
          "encoding": "utf-8"
        }
      ]
    }
  ],
  "hanaPrometheusExporter": {
    "hanaSid": "HDB",
    "hanaPort": "30013",
    "hanaSecretName": "HANA_DB_CREDS",
    "prometheusPort": "9668"
  },
  "haClusterPrometheusExporter": {
    "prometheusPort": "9664"
  }
}
```

# Amazon EC2 上的 SAP NetWeaver
<a name="component-configuration-examples-netweaver"></a>

以下示例显示了适用于 Amazon EC2 上的 SAP NetWeaver 的 JSON 格式组件配置。

```
{
  "subComponents": [
    {
      "subComponentType": "AWS::EC2::Instance",
      "alarmMetrics": [
        {
          "alarmMetricName": "CPUUtilization",
          "monitor": true
        },
        {
          "alarmMetricName": "StatusCheckFailed",
          "monitor": true
        },
        {
          "alarmMetricName": "disk_used_percent",
          "monitor": true
        },
        {
          "alarmMetricName": "mem_used_percent",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_alerts_ResponseTime",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_alerts_ResponseTimeDialog",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_alerts_ResponseTimeDialogRFC",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_alerts_DBRequestTime",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_alerts_LongRunners",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_alerts_AbortedJobs",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_alerts_BasisSystem",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_alerts_Database",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_alerts_Security",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_alerts_System",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_alerts_QueueTime",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_alerts_Availability",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_start_service_processes",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_dispatcher_queue_now",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_dispatcher_queue_max",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_enqueue_server_locks_max",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_enqueue_server_locks_now",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_enqueue_server_locks_state",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_enqueue_server_replication_state",
          "monitor": true
        }
      ],
      "logs": [
        {
          "logGroupName": "SAP_NETWEAVER_DEV_TRACE_LOGS-NetWeaver-ML4",
          "logPath": "/usr/sap/ML4/*/work/dev_w*",
          "logType": "SAP_NETWEAVER_DEV_TRACE_LOGS",
          "monitor": true,
          "encoding": "utf-8"
        }
      ]
    }
  ],
  "netWeaverPrometheusExporter": {
    "sapSid": "ML4",
    "instanceNumbers": [
      "00",
      "11"
    ],
    "prometheusPort": "9680"
  }
}
```

# Amazon EC2 上的 SAP NetWeaver 高可用性
<a name="component-configuration-examples-netweaver-ha"></a>

以下示例显示了适用于 Amazon EC2 上的 SAP NetWeaver 高可用性的 JSON 格式组件配置。

```
{
  "subComponents": [
    {
      "subComponentType": "AWS::EC2::Instance",
      "alarmMetrics": [
        {
          "alarmMetricName": "ha_cluster_corosync_ring_errors",
          "monitor": true
        },
        {
          "alarmMetricName": "ha_cluster_pacemaker_fail_count",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_HA_check_failover_config_state",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_HA_get_failover_config_HAActive",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_alerts_AbortedJobs",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_alerts_Availability",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_alerts_BasisSystem",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_alerts_DBRequestTime",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_alerts_Database",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_alerts_FrontendResponseTime",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_alerts_LongRunners",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_alerts_QueueTime",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_alerts_ResponseTime",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_alerts_ResponseTimeDialog",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_alerts_ResponseTimeDialogRFC",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_alerts_Security",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_alerts_Shortdumps",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_alerts_SqlError",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_alerts_System",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_enqueue_server_replication_state",
          "monitor": true
        },
        {
          "alarmMetricName": "sap_start_service_processes",
          "monitor": true
        }
      ],
      "logs": [
        {
          "logGroupName": "SAP_NETWEAVER_DEV_TRACE_LOGS-NetWeaver-PR1",
          "logPath": "/usr/sap/<SID>/D*/work/dev_w*",
          "logType": "SAP_NETWEAVER_DEV_TRACE_LOGS",
          "monitor": true,
          "encoding": "utf-8"
        }
      ]
    }
  ],
  "haClusterPrometheusExporter": {
    "prometheusPort": "9664"
  },
  "netWeaverPrometheusExporter": {
    "sapSid": "PR1",
    "instanceNumbers": [
      "11",
      "12"
    ],
    "prometheusPort": "9680"
  }
}
```

# SQL Always On 可用性组
<a name="component-configuration-examples-sql"></a>

以下示例演示适用于 SQL Always On 可用性组的 JSON 格式组件配置。

```
{
  "subComponents" : [ {
    "subComponentType" : "AWS::EC2::Instance",
    "alarmMetrics" : [ {
      "alarmMetricName" : "CPUUtilization",
      "monitor" : true
    }, {
      "alarmMetricName" : "StatusCheckFailed",
      "monitor" : true
    }, {
      "alarmMetricName" : "Processor % Processor Time",
      "monitor" : true
    }, {
      "alarmMetricName" : "Memory % Committed Bytes In Use",
      "monitor" : true
    }, {
      "alarmMetricName" : "Memory Available Mbytes",
      "monitor" : true
    }, {
      "alarmMetricName" : "Paging File % Usage",
      "monitor" : true
    }, {
      "alarmMetricName" : "System Processor Queue Length",
      "monitor" : true
    }, {
      "alarmMetricName" : "Network Interface Bytes Total/sec",
      "monitor" : true
    }, {
      "alarmMetricName" : "PhysicalDisk % Disk Time",
      "monitor" : true
    }, {
      "alarmMetricName" : "SQLServer:Buffer Manager Buffer cache hit ratio",
      "monitor" : true
    }, {
      "alarmMetricName" : "SQLServer:Buffer Manager Page life expectancy",
      "monitor" : true
    }, {
      "alarmMetricName" : "SQLServer:General Statistics Processes blocked",
      "monitor" : true
    }, {
      "alarmMetricName" : "SQLServer:General Statistics User Connections",
      "monitor" : true
    }, {
      "alarmMetricName" : "SQLServer:Locks Number of Deadlocks/sec",
      "monitor" : true
    }, {
      "alarmMetricName" : "SQLServer:SQL Statistics Batch Requests/sec",
      "monitor" : true
    }, {
      "alarmMetricName" : "SQLServer:Database Replica File Bytes Received/sec",
      "monitor" : true
    }, {
      "alarmMetricName" : "SQLServer:Database Replica Log Bytes Received/sec",
      "monitor" : true
    }, {
      "alarmMetricName" : "SQLServer:Database Replica Log remaining for undo",
      "monitor" : true
    }, {
      "alarmMetricName" : "SQLServer:Database Replica Log Send Queue",
      "monitor" : true
    }, {
      "alarmMetricName" : "SQLServer:Database Replica Mirrored Write Transaction/sec",
      "monitor" : true
    }, {
      "alarmMetricName" : "SQLServer:Database Replica Recovery Queue",
      "monitor" : true
    }, {
      "alarmMetricName" : "SQLServer:Database Replica Redo Bytes Remaining",
      "monitor" : true
    }, {
      "alarmMetricName" : "SQLServer:Database Replica Redone Bytes/sec",
      "monitor" : true
    }, {
      "alarmMetricName" : "SQLServer:Database Replica Total Log requiring undo",
      "monitor" : true
    }, {
      "alarmMetricName" : "SQLServer:Database Replica Transaction Delay",
      "monitor" : true
    } ],
    "windowsEvents" : [ {
      "logGroupName" : "WINDOWS_EVENTS-Application-<RESOURCE_GROUP_NAME>",
      "eventName" : "Application",
      "eventLevels" : [ "WARNING", "ERROR", "CRITICAL", "INFORMATION" ],
      "monitor" : true
    }, {
      "logGroupName" : "WINDOWS_EVENTS-System-<RESOURCE_GROUP_NAME>",
      "eventName" : "System",
      "eventLevels" : [ "WARNING", "ERROR", "CRITICAL" ],
      "monitor" : true
    }, {
      "logGroupName" : "WINDOWS_EVENTS-Security-<RESOURCE_GROUP_NAME>",
      "eventName" : "Security",
      "eventLevels" : [ "WARNING", "ERROR", "CRITICAL" ],
      "monitor" : true
    } ],
    "logs" : [ {
      "logGroupName" : "SQL_SERVER_ALWAYSON_AVAILABILITY_GROUP-<RESOURCE_GROUP_NAME>",
      "logPath" : "C:\\Program Files\\Microsoft SQL Server\\MSSQL**.MSSQLSERVER\\MSSQL\\Log\\ERRORLOG",
      "logType" : "SQL_SERVER",
      "monitor" : true,
      "encoding" : "utf-8"
    } ]
  }, {
    "subComponentType" : "AWS::EC2::Volume",
    "alarmMetrics" : [ {
      "alarmMetricName" : "VolumeReadBytes",
      "monitor" : true
    }, {
    "alarmMetricName" : "VolumeWriteBytes",
      "monitor" : true
    }, {
    "alarmMetricName" : "VolumeReadOps",
      "monitor" : true
    }, {
    "alarmMetricName" : "VolumeWriteOps",
      "monitor" : true
    }, {
    "alarmMetricName" : "VolumeQueueLength",
      "monitor" : true
    }, {
    "alarmMetricName" : "VolumeThroughputPercentage",
      "monitor" : true
    }, {
    "alarmMetricName" : "BurstBalance",
      "monitor" : true
    } ]
  } ]
}
```

# SQL 故障转移集群实例
<a name="component-configuration-examples-sql-failover-cluster"></a>

以下示例演示适用于 SQL 故障转移集群实例的 JSON 格式组件配置。

```
{
  "subComponents" : [ {
    "subComponentType" : "AWS::EC2::Instance",
    "alarmMetrics" : [ {
      "alarmMetricName" : "CPUUtilization",
      "monitor" : true
    }, {
      "alarmMetricName" : "StatusCheckFailed",
      "monitor" : true
    }, {
      "alarmMetricName" : "Processor % Processor Time",
      "monitor" : true
    }, {
      "alarmMetricName" : "Memory % Committed Bytes In Use",
      "monitor" : true
    }, {
      "alarmMetricName" : "Memory Available Mbytes",
      "monitor" : true
    }, {
      "alarmMetricName" : "Paging File % Usage",
      "monitor" : true
    }, {
      "alarmMetricName" : "System Processor Queue Length",
      "monitor" : true
    }, {
      "alarmMetricName" : "Network Interface Bytes Total/sec",
      "monitor" : true
    }, {
      "alarmMetricName" : "PhysicalDisk % Disk Time",
      "monitor" : true
    }, {
      "alarmMetricName" : "Bytes Received/sec",
      "monitor" : true
    }, {
      "alarmMetricName" : "Normal Messages Queue Length/sec",
      "monitor" : true
    }, {
      "alarmMetricName" : "Urgent Message Queue Length/se",
      "monitor" : true
    }, {
      "alarmMetricName" : "Reconnect Count",
      "monitor" : true
    }, {
      "alarmMetricName" : "Unacknowledged Message Queue Length/sec",
      "monitor" : true
    }, {
      "alarmMetricName" : "Messages Outstanding",
      "monitor" : true
    }, {
      "alarmMetricName" : "Messages Sent/sec",
      "monitor" : true
    }, {
      "alarmMetricName" : "Database Update Messages/sec",
      "monitor" : true
    }, {
      "alarmMetricName" : "Update Messages/sec",
      "monitor" : true
    }, {
      "alarmMetricName" : "Flushes/sec",
      "monitor" : true
    }, {
      "alarmMetricName" : "Crypto Checkpoints Saved/sec",
      "monitor" : true
    }, {
      "alarmMetricName" : "Crypto Checkpoints Restored/sec",
      "monitor" : true
    }, {
      "alarmMetricName" : "Registry Checkpoints Restored/sec",
      "monitor" : true
    }, {
      "alarmMetricName" : "Registry Checkpoints Saved/sec",
      "monitor" : true
    }, {
      "alarmMetricName" : "Cluster API Calls/sec",
      "monitor" : true
    }, {
      "alarmMetricName" : "Resource API Calls/sec",
      "monitor" : true
    }, {
      "alarmMetricName" : "Cluster Handles/sec",
      "monitor" : true
    }, {
      "alarmMetricName" : "Resource Handles/sec",
      "monitor" : true
    } ],
    "windowsEvents" : [ {
      "logGroupName" : "WINDOWS_EVENTS-Application-<RESOURCE_GROUP_NAME>",
      "eventName" : "Application",
      "eventLevels" : [ "WARNING", "ERROR", "CRITICAL"],
      "monitor" : true
    }, {
      "logGroupName" : "WINDOWS_EVENTS-System-<RESOURCE_GROUP_NAME>",
      "eventName" : "System",
      "eventLevels" : [ "WARNING", "ERROR", "CRITICAL", "INFORMATION" ],
      "monitor" : true
    }, {
      "logGroupName" : "WINDOWS_EVENTS-Security-<RESOURCE_GROUP_NAME>",
      "eventName" : "Security",
      "eventLevels" : [ "WARNING", "ERROR", "CRITICAL" ],
      "monitor" : true
    } ],
    "logs" : [ {
      "logGroupName" : "SQL_SERVER_FAILOVER_CLUSTER_INSTANCE-<RESOURCE_GROUP_NAME>",
      "logPath" : "\\\\amznfsxjmzbykwn.mydomain.aws\\SQLDB\\MSSQL**.MSSQLSERVER\\MSSQL\\Log\\ERRORLOG",
      "logType" : "SQL_SERVER",
      "monitor" : true,
      "encoding" : "utf-8"
    } ]
  }, {
    "subComponentType" : "AWS::EC2::Volume",
    "alarmMetrics" : [ {
      "alarmMetricName" : "VolumeReadBytes",
      "monitor" : true
    }, {
    "alarmMetricName" : "VolumeWriteBytes",
      "monitor" : true
    }, {
    "alarmMetricName" : "VolumeReadOps",
      "monitor" : true
    }, {
    "alarmMetricName" : "VolumeWriteOps",
      "monitor" : true
    }, {
    "alarmMetricName" : "VolumeQueueLength",
      "monitor" : true
    }, {
    "alarmMetricName" : "VolumeThroughputPercentage",
      "monitor" : true
    }, {
    "alarmMetricName" : "BurstBalance",
      "monitor" : true
    } ]
  } ]
}
```

# 使用 CloudFormation 模板创建和配置 CloudWatch Application Insights 监控
<a name="appinsights-cloudformation"></a>

您可以直接从 AWS CloudFormation 模板中将 Application Insights 监控（包括关键指标和遥测）添加到应用程序、数据库和 Web 服务器。

此部分提供 JSON 和 YAML 格式的示例 CloudFormation 模板，以帮助您创建和配置 Application Insights 监控。

要查看 *CloudFormation 用户指南*中的 Application Insights 资源和属性参考，请参阅 [ApplicationInsights 资源类型参考](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/AWS_ApplicationInsights.html)。

**Topics**
+ [为整个 CloudFormation 堆栈创建 Application Insights 应用程序](#appinsights-cloudformation-apply-to-stack)
+ [创建具有详细设置的 Application Insights 应用程序](#appinsights-cloudformation-apply-detailed)
+ [使用 `CUSTOM` 模式组件配置创建 Application Insights 应用程序](#appinsights-cloudformation-custom)
+ [使用 `DEFAULT` 模式组件配置创建 Application Insights 应用程序](#appinsights-cloudformation-default)
+ [使用 `DEFAULT_WITH_OVERWRITE` 模式组件配置创建 Application Insights 应用程序](#appinsights-cloudformation-default-with-overwrite)

## 为整个 CloudFormation 堆栈创建 Application Insights 应用程序
<a name="appinsights-cloudformation-apply-to-stack"></a>

要应用以下模板，必须创建 AWS 资源和一个或多个资源组，用于创建 Application Insights 应用程序以监控这些资源。有关更多信息，请参阅 [AWS Resource Groups 入门](https://docs.aws.amazon.com/ARG/latest/userguide/gettingstarted.html)。

以下模板的前两部分指定资源和资源组。模板的最后一部分为资源组创建 Application Insights 应用程序，但不配置应用程序或应用监控。有关更多信息，请参阅 *Amazon CloudWatch Application Insights API 参考*中的 [CreateApplication](https://docs.aws.amazon.com/cloudwatch/latest/APIReference/API_CreateApplication.html) 命令详细信息。

**JSON 格式的模板**

```
{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Description": "Test Resource Group stack",
    "Resources": {
        "EC2Instance": {
            "Type": "AWS::EC2::Instance",
            "Properties": {
                "ImageId" : "ami-abcd1234efgh5678i",
                "SecurityGroupIds" : ["sg-abcd1234"]
            }
        },
        ...
        "ResourceGroup": {
            "Type": "AWS::ResourceGroups::Group",
            "Properties": {
                "Name": "my_resource_group"
            }
        },
        "AppInsightsApp": {
            "Type": "AWS::ApplicationInsights::Application",
            "Properties": {
                "ResourceGroupName": "my_resource_group"
            },
            "DependsOn" : "ResourceGroup"
        }
    }
}
```

**YAML 格式的模板**

```
---
AWSTemplateFormatVersion: '2010-09-09'
Description: Test Resource Group stack
Resources:
  EC2Instance:
    Type: AWS::EC2::Instance
    Properties:
      ImageId: ami-abcd1234efgh5678i
      SecurityGroupIds:
      - sg-abcd1234
  ...
  ResourceGroup:
    Type: AWS::ResourceGroups::Group
    Properties:
      Name: my_resource_group
  AppInsightsApp:
    Type: AWS::ApplicationInsights::Application
    Properties:
      ResourceGroupName: my_resource_group
    DependsOn: ResourceGroup
```

以下模板部分将默认监控配置应用于 Application Insights 应用程序。有关更多信息，请参阅 *Amazon CloudWatch Application Insights API 参考*中的 [CreateApplication](https://docs.aws.amazon.com/cloudwatch/latest/APIReference/API_CreateApplication.html) 命令详细信息。

当 `AutoConfigurationEnabled` 设置为 `true` 时，将使用 `DEFAULT` 应用程序层的建议监控设置来配置应用程序的所有组件。有关这些设置和层的更多信息，请参阅 *Amazon CloudWatch Application Insights API 参考*中的 [DescribeComponentConfigurationRecommendation](https://docs.aws.amazon.com/cloudwatch/latest/APIReference/API_DescribeComponentConfigurationRecommendation.html) 和 [UpdateComponentConfiguration](https://docs.aws.amazon.com/cloudwatch/latest/APIReference/API_UpdateComponentConfiguration.html)。

**JSON 格式的模板**

```
{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Description": "Test Application Insights Application stack",
    "Resources": {
        "AppInsightsApp": {
            "Type": "AWS::ApplicationInsights::Application",
            "Properties": {
                "ResourceGroupName": "my_resource_group",
                "AutoConfigurationEnabled": true
            }
        }
    }
}
```

**YAML 格式的模板**

```
---
AWSTemplateFormatVersion: '2010-09-09'
Description: Test Application Insights Application stack
Resources:
  AppInsightsApp:
    Type: AWS::ApplicationInsights::Application
    Properties:
      ResourceGroupName: my_resource_group
      AutoConfigurationEnabled: true
```

## 创建具有详细设置的 Application Insights 应用程序
<a name="appinsights-cloudformation-apply-detailed"></a>

以下模板执行以下操作：
+ 创建启用了 CloudWatch Events 通知并启用 OpsCenter 的 Application Insights 应用程序。有关更多信息，请参阅 *Amazon CloudWatch Application Insights API 参考*中的 [CreateApplication](https://docs.aws.amazon.com/cloudwatch/latest/APIReference/API_CreateApplication.html) 命令详细信息。
+ 使用两个标签来标记应用程序，其中一个标签没有标签值。有关更多信息，请参阅 *Amazon CloudWatch Application Insights API 参考*中的 [TagResource](https://docs.aws.amazon.com/cloudwatch/latest/APIReference/API_TagResource.html)。
+ 创建两个自定义实例组组件。有关更多信息，请参阅 *Amazon CloudWatch Application Insights API 参考*中的 [CreateComponent](https://docs.aws.amazon.com/cloudwatch/latest/APIReference/API_CreateComponent.html)。
+ 创建两个日志模式集。有关更多信息，请参阅 *Amazon CloudWatch Application Insights API 参考*中的 [CreateLogPattern](https://docs.aws.amazon.com/cloudwatch/latest/APIReference/API_CreateLogPattern.html)。
+ 将 `AutoConfigurationEnabled` 设置为 `true`，这会使用 `DEFAULT` 层的建议监控设置来配置应用程序的所有组件。有关更多信息，请参阅 *Amazon CloudWatch Application Insights API 参考*中的 [DescribeComponentConfigurationRecommendation](https://docs.aws.amazon.com/cloudwatch/latest/APIReference/API_DescribeComponentConfigurationRecommendation.html)。

**JSON 格式的模板**

```
{
    "Type": "AWS::ApplicationInsights::Application",
    "Properties": {
        "ResourceGroupName": "my_resource_group",
        "CWEMonitorEnabled": true,
        "OpsCenterEnabled": true,
        "OpsItemSNSTopicArn": "arn:aws:sns:us-east-1:123456789012:my_topic",
        "AutoConfigurationEnabled": true,
        "Tags": [
            {
                "Key": "key1",
                "Value": "value1"
            },
            {
                "Key": "key2",
                "Value": ""
            }
        ],
        "CustomComponents": [
            {
                "ComponentName": "test_component_1",
                "ResourceList": [
                    "arn:aws:ec2:us-east-1:123456789012:instance/i-abcd1234efgh5678i"
                ]
            },
            {
                "ComponentName": "test_component_2",
                "ResourceList": [
                    "arn:aws:ec2:us-east-1:123456789012:instance/i-abcd1234efgh5678i",
                    "arn:aws:ec2:us-east-1:123456789012:instance/i-abcd1234efgh5678i"
                ]
            }
        ],
        "LogPatternSets": [
            {
                "PatternSetName": "pattern_set_1",
                "LogPatterns": [
                    {
                        "PatternName": "deadlock_pattern",
                        "Pattern": ".*\\sDeadlocked\\sSchedulers(([^\\w].*)|($))",
                        "Rank": 1
                    }
                ]    
            },
            {
                "PatternSetName": "pattern_set_2",
                "LogPatterns": [
                    {
                        "PatternName": "error_pattern",
                        "Pattern": ".*[\\s\\[]ERROR[\\s\\]].*",
                        "Rank": 1
                    },
                    {
                        "PatternName": "warning_pattern",
                        "Pattern": ".*[\\s\\[]WARN(ING)?[\\s\\]].*",
                        "Rank": 10
                    }
                ]
            }
        ]
    }
}
```

**YAML 格式的模板**

```
---
Type: AWS::ApplicationInsights::Application
Properties:
  ResourceGroupName: my_resource_group
  CWEMonitorEnabled: true
  OpsCenterEnabled: true
  OpsItemSNSTopicArn: arn:aws:sns:us-east-1:123456789012:my_topic
  AutoConfigurationEnabled: true
  Tags:
  - Key: key1
    Value: value1
  - Key: key2
    Value: ''
  CustomComponents:
  - ComponentName: test_component_1
    ResourceList:
    - arn:aws:ec2:us-east-1:123456789012:instance/i-abcd1234efgh5678i
  - ComponentName: test_component_2
    ResourceList:
    - arn:aws:ec2:us-east-1:123456789012:instance/i-abcd1234efgh5678i
    - arn:aws:ec2:us-east-1:123456789012:instance/i-abcd1234efgh5678i
  LogPatternSets:
  - PatternSetName: pattern_set_1
    LogPatterns:
    - PatternName: deadlock_pattern
      Pattern: ".*\\sDeadlocked\\sSchedulers(([^\\w].*)|($))"
      Rank: 1
  - PatternSetName: pattern_set_2
    LogPatterns:
    - PatternName: error_pattern
      Pattern: ".*[\\s\\[]ERROR[\\s\\]].*"
      Rank: 1
    - PatternName: warning_pattern
      Pattern: ".*[\\s\\[]WARN(ING)?[\\s\\]].*"
      Rank: 10
```

## 使用 `CUSTOM` 模式组件配置创建 Application Insights 应用程序
<a name="appinsights-cloudformation-custom"></a>

以下模板执行以下操作：
+ 创建 Application Insights 应用程序。有关更多信息，请参阅 *Amazon CloudWatch Application Insights API 参考*中的 [CreateApplication](https://docs.aws.amazon.com/cloudwatch/latest/APIReference/API_CreateApplication.html)。
+ 组件 `my_component` 将 `ComponentConfigurationMode` 设置为 `CUSTOM`，这将导致按照 `CustomComponentConfiguration` 中指定的配置来配置此组件。有关更多信息，请参阅 *Amazon CloudWatch Application Insights API 参考*中的 [UpdateComponentConfiguration](https://docs.aws.amazon.com/cloudwatch/latest/APIReference/API_UpdateComponentConfiguration.html)。

**JSON 格式的模板**

```
{
    "Type": "AWS::ApplicationInsights::Application",
    "Properties": {
        "ResourceGroupName": "my_resource_group,
        "ComponentMonitoringSettings": [
            {
                "ComponentARN": "my_component",
                "Tier": "SQL_SERVER",
                "ComponentConfigurationMode": "CUSTOM",
                "CustomComponentConfiguration": {
                    "ConfigurationDetails": {
                        "AlarmMetrics": [
                            {
                                "AlarmMetricName": "StatusCheckFailed"
                            },
                            ...
                        ],
                        "Logs": [
                            {       
                                "LogGroupName": "my_log_group_1",
                                "LogPath": "C:\\LogFolder_1\\*",
                                "LogType": "DOT_NET_CORE",
                                "Encoding": "utf-8",
                                "PatternSet": "my_pattern_set_1"
                            },      
                            ...     
                        ],      
                        "WindowsEvents": [
                            {       
                                "LogGroupName": "my_windows_event_log_group_1",
                                "EventName": "Application",
                                "EventLevels": [
                                    "ERROR",
                                    "WARNING",
                                    ...     
                                ],       
                                "Encoding": "utf-8",
                                "PatternSet": "my_pattern_set_2"
                            },      
                            ...     
                        ],
                        "Alarms": [
                            {
                                "AlarmName": "my_alarm_name",
                                "Severity": "HIGH"
                            },
                            ...
                        ]
                    },
                    "SubComponentTypeConfigurations": [
                        {
                            "SubComponentType": "EC2_INSTANCE",
                            "SubComponentConfigurationDetails": {
                                "AlarmMetrics": [
                                    {
                                        "AlarmMetricName": "DiskReadOps"
                                    },
                                    ...
                                ],
                                "Logs": [
                                    {
                                        "LogGroupName": "my_log_group_2",
                                        "LogPath": "C:\\LogFolder_2\\*",
                                        "LogType": "IIS",
                                        "Encoding": "utf-8",
                                        "PatternSet": "my_pattern_set_3"
                                    },
                                    ...
                                ],
                                "processes" : [
                                    {
                                        "processName" : "my_process",
                                        "alarmMetrics" : [
                                    {
                                        "alarmMetricName" : "procstat cpu_usage",
                                        "monitor" : true
                                    }, {
                                        "alarmMetricName" : "procstat memory_rss",
                                        "monitor" : true
                                    }
                                ]
                            }
                        ],
                                "WindowsEvents": [
                                    {
                                        "LogGroupName": "my_windows_event_log_group_2",
                                        "EventName": "Application",
                                        "EventLevels": [
                                            "ERROR",
                                            "WARNING",
                                            ...
                                        ],
                                        "Encoding": "utf-8",
                                        "PatternSet": "my_pattern_set_4"
                                    },
                                    ...
                                ]
                            }
                        }   
                    ]
                }
            }
        ]
    }
}
```

**YAML 格式的模板**

```
---
Type: AWS::ApplicationInsights::Application
Properties:
  ResourceGroupName: my_resource_group
  ComponentMonitoringSettings:
  - ComponentARN: my_component
    Tier: SQL_SERVER
    ComponentConfigurationMode: CUSTOM
    CustomComponentConfiguration:
      ConfigurationDetails:
        AlarmMetrics:
        - AlarmMetricName: StatusCheckFailed
        ...
        Logs:
        - LogGroupName: my_log_group_1
          LogPath: C:\LogFolder_1\*
          LogType: DOT_NET_CORE
          Encoding: utf-8
          PatternSet: my_pattern_set_1
        ...
        WindowsEvents:
        - LogGroupName: my_windows_event_log_group_1
          EventName: Application
          EventLevels:
          - ERROR
          - WARNING
          ...
          Encoding: utf-8
          PatternSet: my_pattern_set_2
        ...
        Alarms:
        - AlarmName: my_alarm_name
          Severity: HIGH
        ...
      SubComponentTypeConfigurations:
      - SubComponentType: EC2_INSTANCE
        SubComponentConfigurationDetails:
          AlarmMetrics:
          - AlarmMetricName: DiskReadOps
          ...
          Logs:
          - LogGroupName: my_log_group_2
            LogPath: C:\LogFolder_2\*
            LogType: IIS
            Encoding: utf-8
            PatternSet: my_pattern_set_3
          ...
          Processes:
          - ProcessName: my_process
            AlarmMetrics:
            - AlarmMetricName: procstat cpu_usage
              ...
            ...
          WindowsEvents:
          - LogGroupName: my_windows_event_log_group_2
            EventName: Application
            EventLevels:
            - ERROR
            - WARNING
            ...
            Encoding: utf-8
            PatternSet: my_pattern_set_4
          ...
```

## 使用 `DEFAULT` 模式组件配置创建 Application Insights 应用程序
<a name="appinsights-cloudformation-default"></a>

以下模板执行以下操作：
+ 创建 Application Insights 应用程序。有关更多信息，请参阅 *Amazon CloudWatch Application Insights API 参考*中的 [CreateApplication](https://docs.aws.amazon.com/cloudwatch/latest/APIReference/API_CreateApplication.html)。
+ 组件 `my_component` 将 `ComponentConfigurationMode` 设置为 `DEFAULT`，并将 `Tier` 设置为 `SQL_SERVER`，这将导致使用 Application Insights 为 `SQL_Server` 层推荐的配置设置来配置此组件。有关更多信息，请参阅 *Amazon CloudWatch Application Insights API 参考*中的 [DescribeComponentConfiguration](https://docs.aws.amazon.com/cloudwatch/latest/APIReference/API_DescribeComponentConfiguration.html) 和 [UpdateComponentConfiguration](https://docs.aws.amazon.com/cloudwatch/latest/APIReference/API_UpdateComponentConfiguration.html)。

**JSON 格式的模板**

```
{
    "Type": "AWS::ApplicationInsights::Application",
    "Properties": {
        "ResourceGroupName": "my_resource_group",
        "ComponentMonitoringSettings": [
            {
                "ComponentARN": "my_component",
                "Tier": "SQL_SERVER",
                "ComponentConfigurationMode": "DEFAULT"
            }
        ]
    }
}
```

**YAML 格式的模板**

```
---
Type: AWS::ApplicationInsights::Application
Properties:
  ResourceGroupName: my_resource_group
  ComponentMonitoringSettings:
  - ComponentARN: my_component
    Tier: SQL_SERVER
    ComponentConfigurationMode: DEFAULT
```

## 使用 `DEFAULT_WITH_OVERWRITE` 模式组件配置创建 Application Insights 应用程序
<a name="appinsights-cloudformation-default-with-overwrite"></a>

以下模板执行以下操作：
+ 创建 Application Insights 应用程序。有关更多信息，请参阅 *Amazon CloudWatch Application Insights API 参考*中的 [CreateApplication](https://docs.aws.amazon.com/cloudwatch/latest/APIReference/API_CreateApplication.html)。
+ 组件 `my_component` 将 `ComponentConfigurationMode` 设置为 `DEFAULT_WITH_OVERWRITE`，并将 `tier` 设置为 `DOT_NET_CORE`，这将导致使用 Application Insights 为 `DOT_NET_CORE` 层推荐的配置设置来配置此组件。覆盖的配置设置在 `DefaultOverwriteComponentConfiguration` 中指定：
  + 在组件级别，`AlarmMetrics` 设置将被覆盖。
  + 在子组件级别，对于 `EC2_Instance` 类型的子组件，将覆盖 `Logs` 设置。

  有关更多信息，请参阅 *Amazon CloudWatch Application Insights API 参考*中的 [UpdateComponentConfiguration](https://docs.aws.amazon.com/cloudwatch/latest/APIReference/API_UpdateComponentConfiguration.html)。

**JSON 格式的模板**

```
{
    "Type": "AWS::ApplicationInsights::Application",
    "Properties": {
        "ResourceGroupName": "my_resource_group",
        "ComponentMonitoringSettings": [
            {
                "ComponentName": "my_component",
                "Tier": "DOT_NET_CORE",
                "ComponentConfigurationMode": "DEFAULT_WITH_OVERWRITE",
                "DefaultOverwriteComponentConfiguration": {
                    "ConfigurationDetails": {
                        "AlarmMetrics": [
                            {
                                "AlarmMetricName": "StatusCheckFailed"
                            }
                        ]
                    },
                    "SubComponentTypeConfigurations": [
                        {
                            "SubComponentType": "EC2_INSTANCE",
                            "SubComponentConfigurationDetails": {
                                "Logs": [
                                    {
                                        "LogGroupName": "my_log_group",
                                        "LogPath": "C:\\LogFolder\\*",
                                        "LogType": "IIS",
                                        "Encoding": "utf-8",
                                        "PatternSet": "my_pattern_set"
                                    }
                                ]
                            }
                        }   
                    ] 
                } 
            }
        ]
    }
}
```

**YAML 格式的模板**

```
---
Type: AWS::ApplicationInsights::Application
Properties:
  ResourceGroupName: my_resource_group
  ComponentMonitoringSettings:
  - ComponentName: my_component
    Tier: DOT_NET_CORE
    ComponentConfigurationMode: DEFAULT_WITH_OVERWRITE
    DefaultOverwriteComponentConfiguration:
      ConfigurationDetails:
        AlarmMetrics:
        - AlarmMetricName: StatusCheckFailed
      SubComponentTypeConfigurations:
      - SubComponentType: EC2_INSTANCE
        SubComponentConfigurationDetails:
          Logs:
          - LogGroupName: my_log_group
            LogPath: C:\LogFolder\*
            LogType: IIS
            Encoding: utf-8
            PatternSet: my_pattern_set
```

# 教程：为 SAP ASE 设置监控
<a name="appinsights-tutorial-sap-ase"></a>

本教程演示了如何配置 CloudWatch Application Insights 来为 SAP ASE 数据库设置监控。您可以使用 CloudWatch Application Insights 自动控制面板可视化问题详细信息、加快问题排查速度，并缩短 SAP ASE 数据库的平均解决时间（MTTR）。

**Topics**
+ [支持的环境](#appinsights-tutorial-sap-ase-supported-environments)
+ [支持的操作系统](#appinsights-tutorial-sap-ase-supported-os)
+ [功能](#appinsights-tutorial-sap-ase-features)
+ [先决条件](#appinsights-tutorial-sap-ase-prerequisites)
+ [设置监控](#appinsights-tutorial-sap-ase-set-up)
+ [管理监控](#appinsights-tutorial-sap-ase-manage)
+ [配置告警阈值](#appinsights-tutorial-sap-hana-configure-alarm-threshold)
+ [查看和排查 Application Insights 检测到的 SAP ASE 问题](#appinsights-tutorial-sap-ase-troubleshooting-problems)
+ [排查 Application Insights 的问题](#appinsights-tutorial-sap-ase-troubleshooting-health-dashboard)

## 支持的环境
<a name="appinsights-tutorial-sap-ase-supported-environments"></a>

CloudWatch Application Insights 支持部署用于以下系统和模式的 AWS 资源。您需提供并安装 SAP ASE 数据库软件和支持的 SAP 应用程序软件。
+ **单个 Amazon EC2 实例上有一个或多个 SAP ASE 数据库** – 采用单节点、纵向扩展架构的 SAP ASE。
+ **跨可用区 SAP ASE 数据库高可用性设置** – 使用 SUSE/RHEL 集群在两个可用区中配置了高可用性的 SAP ASE。

**注意**  
CloudWatch Application Insights 仅支持单个 SAP 系统（SID）ASE HA 环境。如果附加了多个 ASE HA SID，则只会为检测到的第一个 SID 设置监控。

## 支持的操作系统
<a name="appinsights-tutorial-sap-ase-supported-os"></a>

CloudWatch Application Insights for SAP ASE 在以下操作系统中支持 x86-64 架构：
+ SuSE Linux 12 SP4
+ SuSE Linux 12 SP5
+ SUSE Linux 15
+ SuSE Linux 15 SP1
+ SuSE Linux 15 SP2
+ SuSE Linux 15 SP3
+ SuSE Linux 15 SP4
+ SuSE Linux 15 SP1 For SAP
+ SuSE Linux 15 SP2 For SAP
+ SuSE Linux 15 SP3 For SAP
+ SuSE Linux 15 SP4 For SAP
+ SuSE Linux 12 SP4 For SAP
+ SuSE Linux 12 SP5 For SAP
+ RedHat Linux 7.6
+ RedHat Linux 7.7
+ RedHat Linux 7.9
+ RedHat Linux 8.1
+ RedHat Linux 8.4
+ RedHat Linux 8.6

## 功能
<a name="appinsights-tutorial-sap-ase-features"></a>

CloudWatch Application Insights for SAP ASE 具有以下功能：
+ 自动检测 SAP ASE 工作负载 
+ 基于静态阈值自动创建 SAP ASE 警告
+ 基于异常检测自动创建 SAP ASE 警告 
+ 自动识别 SAP ASE 日志模式 
+ SAP ASE 运行状况控制面板
+ SAP ASE 问题控制面板

## 先决条件
<a name="appinsights-tutorial-sap-ase-prerequisites"></a>

您必须完成以下必需任务才能使用 CloudWatch Application Insights 配置 SAP ASE 数据库：
+ **SAP ASE 配置参数** – 必须在 ASE 数据库上启用以下配置参数：`"enable monitoring"`、`"sql text pipe max messages"`、`"sql text pipe active"`。这让 CloudWatch Application Insights 可以为您的数据库提供全面的监控功能。如果您的 ASE 数据库未启用这些设置，Application Insights 将自动启用它们，以收集所需指标来进行监控。
+ **SAP ASE 数据库用户** – Application Insights 添加资源期间提供的数据库用户必须具有访问以下各项的权限：
  + 主数据库和用户（租户）数据库中的系统表
  + 监控表
+ **SAPHostCtrl** – 在 Amazon EC2 实例上安装和设置 SAPHostCtrl。
+ **Amazon CloudWatch 代理** – 确保 Amazon EC2 实例上没有运行预先已有的 CloudWatch 代理。如果您安装了 CloudWatch 代理，请确保从现有 CloudWatch 代理配置文件中删除您在 CloudWatch Application Insights 中使用的资源的配置，以避免合并冲突。有关更多信息，请参阅 [手动创建或编辑 CloudWatch 代理配置文件](CloudWatch-Agent-Configuration-File-Details.md)。
+ **AWS Systems Manager 启用** – 在实例上安装 SSM Agent，并启用要为 SSM 启用的实例。有关如何安装 SSM Agent 的信息，请参阅 *AWS Systems Manager 用户指南*中的[使用 SSM Agent](https://docs.aws.amazon.com/systems-manager/latest/userguide/ssm-agent.html)。
+ **Amazon EC2 实例角色** – 要配置数据库，您必须附加以下 Amazon EC2 实例角色。
  + 要启用 Systems Manager，您必须附加 `AmazonSSMManagedInstanceCore` 角色。有关更多信息，请参阅 [AWS Systems Manager 基于身份的策略示例](https://docs.aws.amazon.com/systems-manager/latest/userguide/auth-and-access-control-iam-identity-based-access-control.html)。
  + 要启用通过 CloudWatch 发出实例指标和日志，您必须附加 `CloudWatchAgentServerPolicy`。有关更多信息，请参阅[创建 IAM 角色和用户以用于 Amazon CloudWatch 代理](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/create-iam-roles-for-cloudwatch-agent.html)。
  + 要读取存储在 AWS Secrets Manager 中的密码，您必须将以下 IAM 内联策略附加到 Amazon EC2 实例角色。有关内联策略的更多信息，请参阅 *AWS Identity and Access Management 用户指南*中的[内联策略](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html)。

------
#### [ JSON ]

****  

    ```
    {
        "Version":"2012-10-17",		 	 	 
        "Statement": [
            {
                "Sid": "VisualEditor0",
                "Effect": "Allow",
                "Action": [
                    "secretsmanager:GetSecretValue"
                ],
                "Resource": "arn:aws:secretsmanager:*:*:secret:ApplicationInsights-*"
            }
        ]
    }
    ```

------
+ **AWS Resource Groups** – 要将应用程序添加到 CloudWatch Application Insights，您必须创建一个包含应用程序堆栈所用的所有相关 AWS 资源的资源组。这包括运行 SAP ASE 数据库的 Amazon EC2 实例和 Amazon EBS 卷。如果每个账户有多个数据库，我们建议您创建一个资源组，且该资源组包含每个 SAP ASE 数据库系统的 AWS 资源。
+ **IAM 权限** – 对于非管理员用户：
  +  您必须创建允许 Application Insights 创建服务相关角色的 AWS Identity and Access Management（IAM）policy，并将其附加到您的用户身份。有关附加策略的步骤，请参阅 [CloudWatch Application Insights 的 IAM 策略](appinsights-iam.md)。
  + 用户必须有在 AWS Secrets Manager 中创建密钥的权限，以存储数据库用户凭证。有关更多信息，请参阅[示例：创建密钥的权限](https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access_examples.html#auth-and-access_examples_create)。

------
#### [ JSON ]

****  

    ```
    {
      "Version":"2012-10-17",		 	 	 
      "Statement": [
        {
          "Effect": "Allow",
          "Action": [
            "secretsmanager:CreateSecret"
          ],
          "Resource": "arn:aws:secretsmanager:*:*:secret:ApplicationInsights-*"
        }
      ]
    }
    ```

------
+ **服务相关角色** – Application Insights 使用 AWS Identity and Access Management（IAM）服务相关角色。当您在 Application Insights 控制台中创建首个 Application Insights 应用程序时，将会为您创建服务相关角色。有关更多信息，请参阅 [在 CloudWatch Application Insights 中使用服务相关角色](CHAP_using-service-linked-roles-appinsights.md)。

## 设置针对 SAP ASE 数据库的监控
<a name="appinsights-tutorial-sap-ase-set-up"></a>

使用以下步骤设置针对 SAP HANA 数据库的监控

1. 打开 [CloudWatch 控制台](https://console.aws.amazon.com/cloudwatch)。

1. 从左侧导航窗格中，选择 **Insights** 下的 **Application Insights**。

1. **Application Insights** 页面会显示使用 Application Insights 监控的应用程序列表以及每个应用程序的监控状态。在右上角，选择 **Add an application**（添加应用程序）。

1. 在**指定应用程序详细信息**页面上，从**资源组**下的下拉列表中选择包含 SAP ASE 数据库资源的 AWS 资源组。如果尚未为应用程序创建资源组，则可以在 **Resource group**（资源组）下拉列表下选择 **Create new resource group**（创建新资源组）来创建一个资源组。有关创建资源组的更多信息，请参阅 [https://docs.aws.amazon.com/ARG/latest/userguide/resource-groups.html](https://docs.aws.amazon.com/ARG/latest/userguide/resource-groups.html)

1. 在 **Monitor CloudWatch Events**（监控 CloudWatch Events）下，选中复选框将 Application Insights 监控与 CloudWatch Events 集成，以获取 Amazon EBS、Amazon EC2、AWS CodeDeploy、Amazon ECS、AWS Health API 和通知、Amazon RDS、Amazon S3 和 AWS Step Functions 中的洞察。

1. 在 **Integrate with AWS Systems Manager OpsCenter**（与 OpsCenter 集成）下，选中 **Generate AWS Systems Manager OpsCenter OpsItems for remedial actions**（生成 OpsCenter OpsItems 以采取修复措施）旁边的复选框，以在检测到所选应用程序的问题时查看问题及接收通知。要跟踪为解析与 AWS 资源相关的操作工作项 (OpsItem) 而执行的操作，请提供 SNS 主题 ARN。

1. 您可以选择输入标签以帮助您标识和整理资源。CloudWatch Application Insights 支持基于标签和基于 CloudFormation 堆栈的资源组（Application Auto Scaling 组除外）。有关更多信息，请参阅 *AWS Resource Groups 和标签用户指南*中的[标签编辑器](https://docs.aws.amazon.com/ARG/latest/userguide/tag-editor.html)。

1. 选择 **Next**（下一步）继续设置监控。

1. **查看检测到的组件**页面上列出了 CloudWatch Application Insights 自动检测到的受监控组件及其工作负载。
**注意**  
包含检测到的 SAP ASE 高可用性工作负载的组件仅支持一个组件上一个工作负载。包含检测到的 SAP ASE 单节点工作负载的组件支持多个工作负载，但您无法添加或删除工作负载。所有自动检测到的工作负载都将受到监控。

1. 选择**下一步**。

1. 在**指定组件详细信息**页面上，输入 SAP ASE 数据库的用户名和密码。

1. 查看应用程序监控配置，然后选择 **Submit**（提交）。

1. 此时将打开应用程序详细信息页面，您可以在该页面中查看**应用程序摘要**、**受监控组件和工作负载**的列表以及**未受监控的组件和工作负载**。如果您选择组件或工作负载旁边的单选按钮，还可以查看**配置历史记录**、**日志模式**和已创建的任何**标签**。提交配置时，您的账户会为 SAP ASE 系统部署所有指标和警告，这最多可能需要 2 个小时。

## 管理 SAP HANA 数据库的监控
<a name="appinsights-tutorial-sap-ase-manage"></a>

您可以执行以下步骤来管理 SAP ASE 数据库的用户凭证、指标和日志路径：

1. 打开 [CloudWatch 控制台](https://console.aws.amazon.com/cloudwatch)。

1. 从左侧导航窗格中，选择 **Insights** 下的 **Application Insights**。

1. **Application Insights** 页面会显示使用 Application Insights 监控的应用程序列表以及每个应用程序的监控状态。

1. 在 **Monitored components**（已监控组件）下，选择组件名称旁边的单选按钮。然后，选择 **Manage monitoring**（管理监控）。

1. 在 **EC2 instance group logs**（EC2 实例组日志）下，您可以更新现有的日志路径、日志模式集和日志组名称。此外，您可以额外添加最多三个 **Application logs**（应用程序日志）。

1. 在**指标**下，您可以根据自己的要求选择 SAP ASE 指标。SAP ASE 指标名称的前缀是 `asedb`。每个组件可以添加最多 60 个指标。

1. 在 **ASE 配置**下，输入 SAP ASE 数据库的用户名和密码。即 Amazon CloudWatch 代理连接到 SAP ASE 数据库时使用的用户名和密码。

1. 在**Custom alarms**（自定义告警）下，您可以添加可由 CloudWatch Application Insights 监控的额外告警。

1. 查看应用程序监控配置并选择 **Submit**（提交）。提交配置时，您的账户会为 SAP HANA 系统更新所有指标和告警，这最多可能需要 2 个小时。

## 配置告警阈值
<a name="appinsights-tutorial-sap-hana-configure-alarm-threshold"></a>

CloudWatch Application Insights 会自动创建由告警监控的 Amazon CloudWatch 指标，以及该指标的阈值。当该指标在指定数量的评估期内超出阈值，告警将变为 `ALARM `（告警）状态。请注意，Application Insights 不会保留这些设置。

要编辑单个指标的告警，请按以下步骤操作：

1. 打开 [CloudWatch 控制台](https://console.aws.amazon.com/cloudwatch)。

1. 在左侧导航窗格中，依次选择 **Alarms**（告警）和 **All alarms**（所有告警）。

1. 选择 CloudWatch Application Insights 自动创建的告警旁边的单选按钮。然后选择 **Actions**（操作），并选择下拉菜单中的 **Edit**（编辑）。

1. 编辑 **Metric**（指标）下的以下参数。

   1. 在 **Statistic**（统计数据）下，选择其中一个统计数据或预定义百分比值，或指定一个自定义百分比值。例如 `p95.45`。

   1. 在 **Period**（时间段）下，选择告警的评估期。评估告警时，每个时间段都聚合到一个数据点。

1. 编辑 **Conditions**（条件）下的以下参数。

   1. 选择指标是否必须大于、小于或等于阈值。

   1. 指定阈值。

1. 在 **Additional configuration**（其他配置）下，编辑以下参数：

   1. 在 **Datapoints to alarm**（触发告警的数据点数）下，指定必须处于 `ALARM`（告警）状态以启动告警的数据点数或评估期。当两个值匹配时，如果超过指定的连续评估期数，将创建一个告警并进入 `ALARM`（告警）状态。要创建“`m`（最大为 `n`）”告警，则为第一个数据点指定的值应小于为第二个数据点指定的值。有关评估告警的更多信息，请参阅[评估告警](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Alarms.html#alarm-evaluation)。

   1. 在 **Missing data treatment**（缺失数据处理）下，选择在缺失某些数据点时的告警行为。有关缺失数据处理的更多信息，请参阅[配置 CloudWatch 告警处理缺失数据的方式](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Alarms.html#alarms-and-missing-data)。

   1. 如果警报将百分比值作为监控的统计数据，将显示**样本数少的百分比**框。选择是评估还是忽略采样率较低的案例。如果选择**忽略 (保持警报状态)**，在样本大小太小时，将始终保持当前警报状态。有关采样较低的百分位数的更多信息，请参阅 [基于百分位数的告警和小数据样本](percentiles-with-low-samples.md)。

1. 选择**下一步**。

1. 在**通知**下面，选择一个在警报处于 `ALARM`、`OK` 或 `INSUFFICIENT_DATA` 状态时通知的 SNS 主题。

1. 选择 **Update alarm**（更新告警）。

## 查看和排查 Application Insights 检测到的 SAP ASE 问题
<a name="appinsights-tutorial-sap-ase-troubleshooting-problems"></a>

本节可帮助您解决在 Application Insights 上针对 SAP ASE 配置监控时出现的常见问题。

**SAP ASE Backup 服务器错误**  
您可以通过检查动态创建的控制面板来识别错误消息。控制面板会显示 SAP ASE Backup 服务器中报告的错误消息。有关 SAP ASE Backup Server 日志的更多详细信息，请参阅 [SAP 文档“Backup Server 错误记录”](https://help.sap.com/docs/SAP_ASE/aa939a27edb34f019f71cc47b9c0fd9a/a7aeb8b1bc2b10149ccf99b95687a64c.html)。

**SAP ASE 长时间运行的事务**  
确定长时间运行的事务，并确认是否可以将其停止或运行时间是否有意设置的。有关更多详细信息，请参阅 [2180410 – How to display transaction log records for long running transactions? – SAP ASE](https://userapps.support.sap.com/sap/support/knowledge/en/2180410)。

**SAP ASE 用户连接**  
检查您的 SAP ASE 数据库的大小是否与您打算在数据库上运行的工作负载相匹配。有关更多详细信息，请参阅 SAP 文档中的 [Configuring User Connections](https://help.sap.com/docs/help/061ec8a5739842df9e505d8944fae8e2/9ea258fceaaa496eb80e17d3d5694ff6.html)。

**SAP ASE 磁盘空间**  
您可以检查动态创建的控制面板，找出导致问题的数据库层。控制面板会显示相关指标和日志文件片段。请务必了解磁盘扩容的原因，并在适用情况下增加物理磁盘大小、分配的磁盘空间或同时增加两者。有关更多详细信息，请参阅 SAP 文档中的 [disk resize](https://help.sap.com/docs/SAP_ASE/e0d4539d39c34f52ae9ef822c2060077/ab22db00bc2b1014ad3ce047bbf117d7.html)。

## 利用 Application Insights 排查 SAP ASE 的问题
<a name="appinsights-tutorial-sap-ase-troubleshooting-health-dashboard"></a>

本节提供了帮助您解决 Application Insights 控制面板返回的常见错误的步骤。


| 错误 | 返回的错误 | 根本原因 | 解决方案 | 
| --- | --- | --- | --- | 
|  无法添加超过 60 个监控指标。  |  `Component cannot have more than 60 monitored metric`  |  当前的指标限制为每个组件 60 个受监控指标。  |  删除不必要的指标以符合限制。  | 
|  添加过程之后未显示 SAP 指标或警告  |  `run` 上的 `AWS-ConfigureAWSPackage` 命令在 AWS Systems Manager 中失败了。输出显示错误：`CT-LIBRARY error:``ct_connect(): protocol specific layer: external error: The attempt to connect to the server failed`  |  用户名和密码可能不正确。  |  验证用户名和密码是否有效，然后重新运行添加过程。  | 

# 教程：为 SAP HANA 设置监控
<a name="appinsights-tutorial-sap-hana"></a>

本教程演示了如何配置 CloudWatch Application Insights 来为 SAP HANA 数据库设置监控。您可以使用 CloudWatch Application Insights 自动控制面板可视化呈现问题详细信息、加快故障排除速度及缩短 SAP HANA 数据库的平均解决时间 (MTTR)。

**Topics**
+ [支持的环境](#appinsights-tutorial-sap-hana-supported-environments)
+ [支持的操作系统](#appinsights-tutorial-sap-hana-supported-os)
+ [功能](#appinsights-tutorial-sap-hana-features)
+ [先决条件](#appinsights-tutorial-sap-hana-prerequisites)
+ [设置监控](#appinsights-tutorial-sap-hana-set-up)
+ [管理监控](#appinsights-tutorial-sap-hana-manage)
+ [排查检测到的问题](#appinsights-tutorial-sap-hana-troubleshooting)
+ [异常检测](#appinsights-tutorial-sap-hana-troubleshooting-anomaly-detection)
+ [排查 Application Insights 的问题](#appinsights-tutorial-sap-hana-troubleshooting-health-dashboard)

## 支持的环境
<a name="appinsights-tutorial-sap-hana-supported-environments"></a>

CloudWatch Application Insights 支持部署用于以下系统和模式的 AWS 资源。您提供并安装 SAP HANA 数据库软件和支持的 SAP 应用程序软件。
+ **单个 Amazon EC2 实例上的 SAP HANA 数据库** – 采用单节点、纵向扩展架构的 SAP HANA，内存高达 24TB。
+ **多个 Amazon EC2 实例上的 SAP HANA 数据库** – 采用多节点、横向扩展架构的 SAP HANA。
+ **跨可用区 SAP HANA 数据库高可用性设置** – 使用 SUSE/RHEL 集群在两个可用区中配置了高可用性的 SAP HANA。

**注意**  
CloudWatch Application Insights 仅支持单个 SID HANA 环境。如果连接了多个 HANA SID，则只会为第一个检测到的 SID 设置监控。

## 支持的操作系统
<a name="appinsights-tutorial-sap-hana-supported-os"></a>

CloudWatch Application Insights for SAP HANA 在以下操作系统中支持 x86-64 架构：
+ SuSE Linux 12 SP4 For SAP
+ SuSE Linux 12 SP5 For SAP
+ SUSE Linux 15
+ SuSE Linux 15 SP1
+ SuSE Linux 15 SP2
+ SuSE Linux 15 For SAP
+ SuSE Linux 15 SP1 For SAP
+ SuSE Linux 15 SP2 For SAP
+ SuSE Linux 15 SP3 For SAP
+ SuSE Linux 15 SP4 For SAP
+ SuSE Linux 15 SP5 For SAP
+ 适用于 SAP 的 RedHat Linux 8.6（包含高可用性和更新服务）
+ 适用于 SAP 的 RedHat Linux 8.5（包含高可用性和更新服务）
+ 适用于 SAP 的 RedHat Linux 8.4（包含高可用性和更新服务）
+ 适用于 SAP 的 RedHat Linux 8.3（包含高可用性和更新服务）
+ RedHat Linux 8.2 For SAP（包含高可用性和更新服务）
+ RedHat Linux 8.1 For SAP（包含高可用性和更新服务）
+ RedHat Linux 7.9 For SAP（包含高可用性和更新服务）

## 功能
<a name="appinsights-tutorial-sap-hana-features"></a>

CloudWatch Application Insights for SAP HANA 具有以下功能：
+ SAP HANA 工作负载自动检测 
+ 基于静态阈值自动创建 SAP HANA 告警
+ 基于异常检测自动创建 SAP HANA 告警
+ 自动识别 SAP HANA 日志模式 
+ SAP HANA 健康控制面板
+ SAP HANA 问题控制面板

## 先决条件
<a name="appinsights-tutorial-sap-hana-prerequisites"></a>

您必须完成以下必需任务才能使用 CloudWatch Application Insights 配置 SAP HANA 数据库：
+ **SAP HANA** – 在 Amazon EC2 实例上安装处于运行状态且可访问的 SAP HANA 数据库 2.0 SPS05。
+ **SAP HANA 数据库用户** – 必须在 SYSTEM 数据库和所有租户中创建具有监控角色的数据库用户。

**示例**  
以下 SQL 命令将创建具有监控角色的用户。

  ```
  su - <sid>adm
  hdbsql -u SYSTEM -p <SYSTEMDB password> -d SYSTEMDB
  CREATE USER CW_HANADB_EXPORTER_USER PASSWORD <Monitoring user password> NO FORCE_FIRST_PASSWORD_CHANGE;
  CREATE ROLE CW_HANADB_EXPORTER_ROLE;
  GRANT MONITORING TO CW_HANADB_EXPORTER_ROLE;
  GRANT CW_HANADB_EXPORTER_ROLE TO CW_HANADB_EXPORTER_USER;
  ```
+ **Python 3.8** – 在操作系统上安装 Python 3.8 或更高版本。使用最新的 Python 版本。如果未在操作系统中检测到 Python3，则将安装 Python 3.6。

  有关更多信息，请参阅[installation example](#install)。
**注意**  
SuSE Linux 15 SP4、RedHat Linux 8.6 及更高版本的操作系统需要手动安装 Python 3.8 或更高版本。
+ **Pip3** – 在操作系统中安装安装程序 pip3。如果未在操作系统中检测到 pip3，则安装该程序。
+ **hdbclient** – CloudWatch Application Insights 使用 python 驱动连接到 SAP HANA 数据库。如果未在 python3 下安装客户端，则请确保 `/hana/shared/SID/hdbclient/` 下有 hdbclient tar 文件版本 `2.10 or later`。
+ **Amazon CloudWatch 代理** – 确保 Amazon EC2 实例上没有运行预先已有的 CloudWatch 代理。如果您安装了 CloudWatch 代理，请确保从现有 CloudWatch 代理配置文件中删除您在 CloudWatch Application Insights 中使用的资源的配置，以避免合并冲突。有关更多信息，请参阅 [手动创建或编辑 CloudWatch 代理配置文件](CloudWatch-Agent-Configuration-File-Details.md)。
+ **AWS Systems Manager 启用** – 在实例上安装 SSM Agent，并且实例必须启用了 SSM。有关如何安装 SSM Agent 的信息，请参阅《AWS Systems Manager 用户指南》**中的[使用 SSM Agent](https://docs.aws.amazon.com/systems-manager/latest/userguide/ssm-agent.html)。
+ **Amazon EC2 实例角色** – 要配置数据库，您必须附加以下 Amazon EC2 实例角色。
  + 要启用 Systems Manager，您必须附加 `AmazonSSMManagedInstanceCore` 角色。有关更多信息，请参阅 [AWS Systems Manager 基于身份的策略示例](https://docs.aws.amazon.com/systems-manager/latest/userguide/auth-and-access-control-iam-identity-based-access-control.html)。
  + 要启用通过 CloudWatch 发出实例指标和日志，您必须附加 `CloudWatchAgentServerPolicy`。有关更多信息，请参阅[创建用于 CloudWatch 代理的 IAM 角色和用户](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/create-iam-roles-for-cloudwatch-agent.html)
  + 要读取存储在 AWS Secrets Manager 中的密码，您必须将以下 IAM 内联策略附加到 Amazon EC2 实例角色。有关内联策略的更多信息，请参阅 *AWS Identity and Access Management 用户指南*中的[内联策略](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html)。

------
#### [ JSON ]

****  

    ```
    {
        "Version":"2012-10-17",		 	 	 
        "Statement": [
            {
                "Sid": "VisualEditor0",
                "Effect": "Allow",
                "Action": [
                    "secretsmanager:GetSecretValue"
                ],
                "Resource": "arn:aws:secretsmanager:*:*:secret:ApplicationInsights-*"
            }
        ]
    }
    ```

------
+ **AWS Resource Groups** – 要将应用程序添加到 CloudWatch Application Insights，您必须创建一个包含应用程序堆栈所用的所有相关 AWS 资源的资源组。这包括运行 SAP HANA 数据库的 Amazon EC2 实例和 Amazon EBS 卷。如果每个账户有多个数据库，我们建议您创建一个资源组，而且该资源组包含每个 SAP HANA 数据库系统的 AWS 资源。
+ **IAM 权限** – 对于非管理员用户：
  +  您必须创建允许 Application Insights 创建服务相关角色的 AWS Identity and Access Management（IAM）policy，并将其附加到您的用户身份。有关附加策略的步骤，请参阅 [CloudWatch Application Insights 的 IAM 策略](appinsights-iam.md)。
  + 用户必须有在 AWS Secrets Manager 中创建密钥的权限，以存储数据库用户凭证。有关更多信息，请参阅[示例：创建密钥的权限](https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access_examples.html#auth-and-access_examples_create)。

------
#### [ JSON ]

****  

    ```
    {
      "Version":"2012-10-17",		 	 	 
      "Statement": [
        {
          "Effect": "Allow",
          "Action": [
            "secretsmanager:CreateSecret"
          ],
          "Resource": "arn:aws:secretsmanager:*:*:secret:ApplicationInsights-*"
        }
      ]
    }
    ```

------
+ **服务相关角色** – Application Insights 使用 AWS Identity and Access Management（IAM）服务相关角色。当您在 Application Insights 控制台中创建首个 Application Insights 应用程序时，将会为您创建服务相关角色。有关更多信息，请参阅 [在 CloudWatch Application Insights 中使用服务相关角色](CHAP_using-service-linked-roles-appinsights.md)。

## 设置 SAP HANA 数据库以进行监控
<a name="appinsights-tutorial-sap-hana-set-up"></a>

要为 SAP HANA 数据库设置监控，请执行以下步骤

1. 打开 [CloudWatch 控制台](https://console.aws.amazon.com/cloudwatch)。

1. 从左侧导航窗格中，选择 **Insights** 下的 **Application Insights**。

1. **Application Insights** 页面会显示使用 Application Insights 监控的应用程序列表以及每个应用程序的监控状态。在右上角，选择 **Add an application**（添加应用程序）。

1. 在 **Specify application details**（指定应用程序详细信息）页面上，从 **Resource group**（资源组）下的下拉列表中选择包含 SAP HANA 数据库资源的 AWS 资源组。如果尚未为应用程序创建资源组，则可以在 **Resource group**（资源组）下拉列表下选择 **Create new resource group**（创建新资源组）来创建一个资源组。有关创建资源组的更多信息，请参阅 [https://docs.aws.amazon.com/ARG/latest/userguide/resource-groups.html](https://docs.aws.amazon.com/ARG/latest/userguide/resource-groups.html)

1. 在 **Monitor CloudWatch Events**（监控 CloudWatch Events）下，选中复选框将 Application Insights 监控与 CloudWatch Events 集成，以获取 Amazon EBS、Amazon EC2、AWS CodeDeploy、Amazon ECS、AWS Health API 和通知、Amazon RDS、Amazon S3 和 AWS Step Functions 中的洞察。

1. 在 **Integrate with AWS Systems Manager OpsCenter**（与 OpsCenter 集成）下，选中 **Generate AWS Systems Manager OpsCenter OpsItems for remedial actions**（生成 OpsCenter OpsItems 以采取修复措施）旁边的复选框，以在检测到所选应用程序的问题时查看问题及接收通知。要跟踪为解析与 AWS 资源相关的操作工作项 (OpsItem) 而执行的操作，请提供 SNS 主题 ARN。

1. 您可以选择输入标签以帮助您标识和整理资源。CloudWatch Application Insights 支持基于标签和基于 CloudFormation 堆栈的资源组（Application Auto Scaling 组除外）。有关更多信息，请参阅 *AWS Resource Groups 和标签用户指南*中的[标签编辑器](https://docs.aws.amazon.com/ARG/latest/userguide/tag-editor.html)。

1. 选择 **Next**（下一步）继续设置监控。

1. **查看检测到的组件**页面上列出了 CloudWatch Application Insights 自动检测到的受监控组件及其工作负载。

   1. 要将工作负载添加到包含检测到的 SAP HANA 单节点工作负载的组件，请选择该组件，然后选择**编辑组件**。
**注意**  
包含检测到的 SAP HANA 多节点或 HANA 高可用性工作负载的组件仅支持一个组件上一个工作负载。  
![\[CloudWatch Application Insights 控制台的“查看要监控的组件”页面：选择要编辑的组件。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/appinsights-multiapp-hana-review.png)

   1. 要添加新的工作负载，请选择**添加新工作负载**。  
![\[CloudWatch Application Insights 控制台的“编辑组件”部分：选择用于添加工作负载的左下角按钮。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/appinsights-multiapp-hana-edit.png)

   1. 编辑工作负载完成后，选择**保存更改**。

1. 选择**下一步**。

1. 在**指定组件详细信息**页面上，输入用户名和密码。

1. 查看应用程序监控配置，然后选择 **Submit**（提交）。

1. 此时将打开应用程序详细信息页面，您可以在该页面中查看**应用程序摘要**、**受监控组件和工作负载**的列表以及**未受监控的组件和工作负载**。如果您选择组件或工作负载旁边的单选按钮，还可以查看**配置历史记录**、**日志模式**和已创建的任何**标签**。提交配置时，您的账户会为 SAP HANA 系统部署所有指标和告警，这最多可能需要 2 个小时。

## 管理对 SAP HANA 数据库的监控
<a name="appinsights-tutorial-sap-hana-manage"></a>

您可以执行以下步骤来管理 SAP HANA 数据库的用户凭证、指标和日志路径：

1. 打开 [CloudWatch 控制台](https://console.aws.amazon.com/cloudwatch)。

1. 从左侧导航窗格中，选择 **Insights** 下的 **Application Insights**。

1. **Application Insights** 页面会显示使用 Application Insights 监控的应用程序列表以及每个应用程序的监控状态。

1. 在 **Monitored components**（已监控组件）下，选择组件名称旁边的单选按钮。然后，选择 **Manage monitoring**（管理监控）。

1. 在 **EC2 instance group logs**（EC2 实例组日志）下，您可以更新现有的日志路径、日志模式集和日志组名称。此外，您可以额外添加最多三个 **Application logs**（应用程序日志）。

1. 在 **Metrics**（指标）下，您可以根据自己的要求选择 SAP HANA 指标。SAP HANA 指标名称的前缀是 `hanadb`。每个组件可以添加最多 40 个指标。

1. 在 **HANA configuration**（HANA 配置）下，输入 SAP HANA 数据库的密码和用户名，即 Amazon CloudWatch 代理连接到 SAP HANA 数据库时使用的用户名和密码。

1. 在**Custom alarms**（自定义告警）下，您可以添加可由 CloudWatch Application Insights 监控的额外告警。

1. 查看应用程序监控配置并选择 **Submit**（提交）。提交配置时，您的账户会为 SAP HANA 系统更新所有指标和告警，这最多可能需要 2 个小时。

## 查看和排查 CloudWatch Application Insights 检测到的问题
<a name="appinsights-tutorial-sap-hana-troubleshooting"></a>

以下各节提供了一些步骤，可帮助您解决在 Application Insights 上为 SAP HANA 配置监控时出现的常见问题排查情况。

**Topics**
+ [SAP HANA 数据库达到内存分配限制](#appinsights-tutorial-sap-hana-troubleshooting-memory)
+ [磁盘已满事件](#appinsights-tutorial-sap-hana-troubleshooting-disk-full)
+ [SAP HANA 备份停止运行](#appinsights-tutorial-sap-hana-troubleshooting-backup-stopped)

### SAP HANA 数据库达到内存分配限制
<a name="appinsights-tutorial-sap-hana-troubleshooting-memory"></a>

**说明**  
由于内存压力过大，由 SAP HANA 数据库提供支持的 SAP 应用程序发生故障，导致应用程序性能下降。

**解决方案**  
您可以检查动态创建的控制面板（显示相关指标和日志文件片段），找出导致问题的应用程序层。在以下示例中，问题可能是 SAP HANA 系统中数据负载过大。

![\[超出内存分配。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/appinsights-memory-allocation-1.png)


已用内存分配超过总内存分配限制的 80% 的阈值。

![\[日志组显示内存不足。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/appinsights-memory-allocation-2.png)


日志组显示方案 `BNR-DATA` 和表 `IMDBMASTER_30003` 内存不足。此外，日志组会显示问题发生的确切时间、当前全局位置限制、共享内存、代码大小和 OOM 预留分配大小。

![\[日志组文本。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/appinsights-memory-allocation-3.png)


### 磁盘已满事件
<a name="appinsights-tutorial-sap-hana-troubleshooting-disk-full"></a>

**说明**  
由 SAP HANA 数据库提供支持的 SAP 应用程序停止响应，导致无法访问数据库。

**解决方案**  
您可以检查动态创建的控制面板（显示相关指标和日志文件片段），找出导致问题的数据库层。在以下示例中，问题可能是管理员无法启用自动日志备份，导致 sap/hana/log 目录填满。

![\[日志组显示内存不足。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/appinsights-disk-full-1.png)


问题控制面板中的日志组小组件显示 `DISKFULL` 事件。

![\[日志组显示内存不足。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/appinsights-disk-full-2.png)


### SAP HANA 备份停止运行
<a name="appinsights-tutorial-sap-hana-troubleshooting-backup-stopped"></a>

**说明**  
由 SAP HANA 数据库提供支持的 SAP 应用程序已停止工作。

**解决方案**  
您可以检查动态创建的控制面板（显示相关指标和日志文件片段），找出导致问题的数据库层。

问题控制面板中的日志组小组件显示 `ACCESS DENIED` 事件。其中包括其他信息，如 S3 存储桶、S3 存储桶文件夹和 S3 存储桶区域。

![\[日志组显示内存不足。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/appinsights-backup-stopped-2.png)


## SAP HANA 的异常检测
<a name="appinsights-tutorial-sap-hana-troubleshooting-anomaly-detection"></a>

对于特定的 SAP HANA 指标（例如线程数量），CloudWatch 应用统计和机器学习算法来定义阈值。这些算法只需最少的用户干预，即可持续分析 SAP HANA 数据库的指标，确定正常基线和表面异常。算法会生成一个异常检测模型，该模型生成表示正常指标行为的预期值范围。

异常检测算法将指标的季节性变化和趋势变化考虑在内。季节性变化可以是每小时、每天或每周，如以下 SAP HANA CPU 使用率示例所示。

![\[日志组显示内存不足。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/appinsights-anomaly-detection.png)


创建模型后，CloudWatch 异常检测会持续评估模型并对其进行调整，以确保模型尽可能准确。这包括重新训练模型，以便模型在指标值随着时间的推移而变化或突然发生变化时作出调整。此外还包括用于改进季节性、峰值或稀疏指标模型的预测器。

## 排查 Application Insights for SAP HANA 的问题
<a name="appinsights-tutorial-sap-hana-troubleshooting-health-dashboard"></a>

本节提供了帮助您解决 Application Insights 控制面板返回的常见错误的步骤。

### 无法添加超过 60 个监控的指标
<a name="cant-add-greater-sixty-metrics"></a>

输出内容显示以下错误。

```
Component cannot have more than 60 monitored metrics
```

**根本原因** – 当前的指标限制为每个组件 60 个受监控指标。

**解决方法** – 要保持在限制以下，请删除不必要的指标。

### 载入过程之后未显示 SAP 指标
<a name="no-sap-metrics-appear"></a>

使用以下信息了解 SAP 指标在载入过程后未显示在控制面板上的原因。第一步是使用 AWS 管理控制台 或 Amazon EC2 实例的导出程序日志来排查 SAP 指标不显示的原因。接下来，查看错误输出以找到解决方法。

#### 排查载入后 SAP 指标不显示的原因
<a name="w2aac26c20c27c27b7b5"></a>

您可以使用 AWS 管理控制台 或 Amazon EC2 实例的导出程序日志进行问题排查。

------
#### [ AWS 管理控制台 ]

**使用控制台排查载入后不显示 SAP 指标的问题**

1. 访问 [https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/)，打开 AWS Systems Manager 控制台。

1. 在左侧导航窗格中，选择**状态管理器**。

1. 在**关联**下，检查文档 `AWSEC2-ApplicationInsightsCloudwatchAgentInstallAndConfigure` 的状态。如果状态为 `Failed`，则在**执行 ID** 下，选择失败的 ID 并查看输出。

1. 在**关联**下，检查文档 `AWS-ConfigureAWSPackage` 的状态。如果状态为 `Failed`，则在**执行 ID** 下，选择失败的 ID 并查看输出。

------
#### [ Exporter logs from Amazon EC2 instance ]

**使用导出程序日志排查载入后不显示 SAP 指标的问题**

1. 连接到运行 SAP HANA 数据库的 Amazon EC2 实例。

1. <a name="step-find-short-name"></a>使用以下命令查找用于 `WORKLOAD_SHORT_NAME` 的正确命名约定。您将在以下两个步骤中使用此短名称。

   ```
   sudo systemctl | grep exporter
   ```
**注意**  
Application Insights 根据正在运行的工作负载在服务名称中添加后缀 `WORKLOAD_SHORT_NAME`。SAP HANA 单节点、多节点和高可用性部署的短名称为 `HANA_SN`、`HANA_MN` 和 `HANA_HA`。

1. 要检查导出器管理器服务日志中是否存在错误，请运行以下命令，将 `WORKLOAD_SHORT_NAME` 替换为您在 [Step 2](#step-find-short-name) 中找到的短名称。

   ```
   sudo journalctl -e --unit=prometheus-hanadb_exporter_manager_WORKLOAD_SHORT_NAME.service
   ```

1. 如果导出程序管理器服务日志未显示错误，则请运行以下命令检查导出程序服务日志中是否存在错误。

   ```
   sudo journalctl -e --unit=prometheus-hanadb_exporter_WORKLOAD_SHORT_NAME.service
   ```

------

#### 解决载入后 SAP 指标未显示的常见根本原因
<a name="resolve-root-causes-sap-metrics"></a>

以下示例描述了如何解决载入后 SAP 指标未显示的常见根本原因。
+ 输出内容显示以下错误。

  ```
  Reading json config file path: /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.d/default ...
  Reading json config file path: /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.d/ssm_AmazonCloudWatch-ApplicationInsights-SSMParameterForTESTCWEC2INSTANCEi0d88867f1f3e36285.tmp ...
  2023/11/30 22:25:17 Failed to merge multiple json config files.
  2023/11/30 22:25:17 Failed to merge multiple json config files.
  2023/11/30 22:25:17 Under path : /metrics/append_dimensions | Error : Different values are specified for append_dimensions
  2023/11/30 22:25:17 Under path : /metrics/metrics_collected/disk | Error : Different values are specified for disk
  2023/11/30 22:25:17 Under path : /metrics/metrics_collected/mem | Error : Different values are specified for mem
  2023/11/30 22:25:17 Configuration validation first phase failed. Agent version: 1.0. Verify the JSON input is only using features supported by this version.
  ```

  **解决方案** – Application Insights 尝试配置与现有 CloudWatch 代理配置文件中预配置指标相同的指标。删除 `/opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.d/` 下现有的文件，或从现有 CloudWatch 代理配置文件中删除导致冲突的指标。
+ 输出内容显示以下错误。

  ```
  Unable to find a host with system database, for more info rerun using -v
  ```

  **解决方案** – 用户名、密码或数据库端口可能不正确。验证用户名、密码和端口是否有效，然后重新运行载入过程。
+ 输出内容显示以下错误。

  ```
  This hdbcli installer is not compatible with your Python interpreter
  ```

  **分辨率** – 升级 pip3 和 wheel，如以下 Python 3.6 示例所示。

  ```
  python3.6 -m pip install --upgrade pip setuptools wheel
  ```
+ 输出内容显示以下错误。

  ```
  Unable to install hdbcli using pip3. Please try to install it
  ```

  **解决方案** – 确保您已遵循 `hdbclient` 先决条件或在 pip3 下手动安装 `hdbclient`。
+ 输出内容显示以下错误。

  ```
  Package 'boto3' requires a different Python: 3.6.15 not in '>= 3.7'
  ```

  **解决方案** – 此操作系统版本需要 Python 3.8 或更高版本。检查 Python 3.8 的先决条件并进行安装。
+ 输出内容显示以下安装错误之一。

  ```
  Can not execute `setup.py` since setuptools is not available in the build environment
  ```

  或者

  ```
  [SSL: CERTIFICATE_VERIFY_FAILED]
  ```

  **解决方法** – 使用 SUSE Linux 命令安装 Python，如以下示例所示。以下示例安装了最新版本的 [Python 3.8](https://www.python.org/downloads/)。

  ```
  wget https://www.python.org/ftp/python/3.8.<LATEST_RELEASE>/Python-3.8.<LATEST_RELEASE>.tgz
  tar xf Python-3.*
  cd Python-3.*/
  sudo zypper install make gcc-c++ gcc automake autoconf libtool
  sudo zypper install zlib-devel
  sudo zypper install libopenssl-devel libffi-devel
  ./configure --with-ensurepip=install 
  sudo make
  sudo make install
  sudo su 
  python3.8 -m pip install --upgrade pip setuptools wheel
  ```

# 教程：为 SAP NetWeaver 设置监控
<a name="appinsights-tutorial-sap-netweaver"></a>

本教程演示了如何配置 Amazon CloudWatch Application Insights，以便为 SAP NetWeaver 设置监控。您可以使用 CloudWatch Application Insights 自动控制面板可视化问题详细信息、加快故障排除并缩短 SAP NetWeaver 应用程序服务器的平均解决时间（MTTR）。

**Topics**
+ [支持的环境](#appinsights-tutorial-sap-netweaver-supported-environments)
+ [支持的操作系统](#appinsights-tutorial-sap-netweaver-supported-os)
+ [功能](#appinsights-tutorial-sap-netweaver-features)
+ [先决条件](#appinsights-tutorial-sap-netweaver-prerequisites)
+ [设置监控](#appinsights-tutorial-sap-netweaver-set-up)
+ [管理监控](#appinsights-tutorial-sap-netweaver-manage)
+ [排查问题](#appinsights-tutorial-sap-netweaver-troubleshooting)
+ [排查 Application Insights 的问题](#appinsights-tutorial-sap-netweaver-troubleshooting-health-dashboard)

## 支持的环境
<a name="appinsights-tutorial-sap-netweaver-supported-environments"></a>

CloudWatch Application Insights 支持部署用于以下系统和模式的 AWS 资源。
+ **SAP NetWeaver 标准系统部署。**
+ **SAP NetWeaver 在多个 Amazon EC2 实例上的分布式部署。**
+ **跨可用区 SAP NetWeaver 高可用性设置** – 使用 SUSE/RHEL 集群在两个可用区之间配置高可用性的 SAP NetWeaver。

## 支持的操作系统
<a name="appinsights-tutorial-sap-netweaver-supported-os"></a>

以下操作系统支持 CloudWatch Application Insights for SAP NetWeaver：
+ Oracle Linux 8
+ Red Hat Enterprise Linux 7.6
+ Red Hat Enterprise Linux 7.7
+ Red Hat Enterprise Linux 7.9
+ Red Hat Enterprise Linux 8.1
+ Red Hat Enterprise Linux 8.2
+ Red Hat Enterprise Linux 8.4
+ Red Hat Enterprise Linux 8.6
+ SUSE Linux Enterprise Server 15 for SAP
+ SUSE Linux Enterprise Server 15 SP1 for SAP
+ SUSE Linux Enterprise Server 15 SP2 for SAP
+ SUSE Linux Enterprise Server 15 SP3 for SAP
+ SUSE Linux Enterprise Server 15 SP4 for SAP
+ SUSE Linux Enterprise Server 12 SP4 for SAP
+ SUSE Linux Enterprise Server 12 SP5 for SAP
+ SUSE Linux Enterprise Server 15（高可用性模式除外）
+ SUSE Linux Enterprise Server 15 SP1（高可用性模式除外）
+ SUSE Linux Enterprise Server 15 SP2（高可用性模式除外）
+ SUSE Linux Enterprise Server 15 SP3（高可用性模式除外）
+ SUSE Linux Enterprise Server 15 SP4（高可用性模式除外）
+ SUSE Linux Enterprise Server 12 SP4（高可用性模式除外）
+ SUSE Linux Enterprise Server 12 SP5（高可用性模式除外）

## 功能
<a name="appinsights-tutorial-sap-netweaver-features"></a>

CloudWatch Application Insights for SAP NetWeaver 7.0x–7.5x（包括 ABAP 平台）提供了以下功能：
+ SAP NetWeaver 工作负载自动检测 
+ 基于静态阈值自动创建 SAP NetWeaver 告警
+ 自动识别 SAP NetWeaver 日志模式 
+ SAP NetWeaver 运行状况控制面板
+ SAP NetWeaver 问题控制面板

## 先决条件
<a name="appinsights-tutorial-sap-netweaver-prerequisites"></a>

您须完成以下必需任务才能使用 CloudWatch Application Insights 配置 SAP NetWeaver：
+ **AWS Systems Manager 启用** – 在 Amazon EC2 实例上安装 SSM Agent，并启用 SSM 实例。有关如何安装 SSM Agent 的信息，请参阅 *AWS Systems Manager 用户指南*中的[设置 AWS Systems Manager](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-setting-up.html)。
+ **Amazon EC2 实例角色** – 要配置 SAP NetWeaver 监控，您必须附加以下 Amazon EC2 实例角色。
  + 要启用 Systems Manager，您必须附加 `AmazonSSMManagedInstanceCore` 角色。有关更多信息，请参阅 [AWS Systems Manager 基于身份的策略示例](https://docs.aws.amazon.com/systems-manager/latest/userguide/auth-and-access-control-iam-identity-based-access-control.html)。
  + 要使实例指标和日志通过 CloudWatch 发出，您必须附加 `CloudWatchAgentServerPolicy` 策略。有关更多信息，请参阅[创建用于 CloudWatch 代理的 IAM 角色和用户](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/create-iam-roles-for-cloudwatch-agent.html)
+ **AWS Resource Groups** – 要将应用程序添加到 CloudWatch Application Insights，您必须创建一个包含应用程序堆栈所用的所有相关 AWS 资源的资源组。这包括运行 SAP NetWeaver 应用程序服务器的 Amazon EC2 实例、Amazon EFS 和 Amazon EBS 卷。如果每个账户有多个 SAP NetWeaver 系统，我们建议您创建一个资源组，且该资源组包含每个 SAP NetWeaver 系统的 AWS 资源。有关创建资源组的更多信息，请参阅 *[AWS 资源组和标签用户指南](https://docs.aws.amazon.com/ARG/latest/userguide/resource-groups.html)*。
+ **IAM 权限** – 对于没有管理访问权限的用户，必须创建允许 Application Insights 创建服务相关角色的 AWS Identity and Access Management（IAM）policy，并将其附加到用户身份。有关如何创建 IAM policy 的更多信息，请参阅 [IAM policy](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/appinsights-iam.html)。
+ **服务相关角色** – Application Insights 使用 AWS Identity and Access Management（IAM）服务相关角色。当您在 Application Insights 控制台中创建首个 Application Insights 应用程序时，将会为您创建服务相关角色。有关更多信息，请参阅 [在 CloudWatch Application Insights 中使用服务相关角色](CHAP_using-service-linked-roles-appinsights.md)。
+ **Amazon CloudWatch 代理** – Application Insights 安装和配置 CloudWatch 代理。如果您安装了 CloudWatch 代理，则 Application Insights 会保留您的配置。为避免合并冲突，请从现有 CloudWatch 代理配置文件中删除您想在 Application Insights 中使用的资源的配置。有关更多信息，请参阅 [手动创建或编辑 CloudWatch 代理配置文件](CloudWatch-Agent-Configuration-File-Details.md)。

## 设置 SAP NetWeaver 应用程序服务器以进行监控
<a name="appinsights-tutorial-sap-netweaver-set-up"></a>

请按照以下步骤为 SAP NetWeaver 应用程序服务器设置监控。

**设置监控**

1. 打开 [CloudWatch 控制台](https://console.aws.amazon.com/cloudwatch)。

1. 从左侧导航窗格中，选择 **Insights** 下的 **Application Insights**。

1. **Application Insights** 页面会显示使用 Application Insights 监控的应用程序列表以及每个应用程序的监控状态。在右上角，选择 **Add an application**（添加应用程序）。

1. 在 **Specify application details**（指定应用程序详细信息）页面上，从 **Resource group**（资源组）下拉列表中选择您创建的包含 SAP NetWeaver 资源的 AWS 资源组。如果尚未为应用程序创建资源组，则可以在 **Resource group**（资源组）下拉列表下选择 **Create new resource group**（创建新资源组）来创建一个资源组。

1. 在 **Automatic monitoring of new resources**（自动监控新资源）下，选中复选框以允许 Application Insights 自动监控在载入后添加到应用程序资源组的资源。

1. 在 **Monitor EventBridge events**（监控 EventBridge 事件）下，选中复选框将 Application Insights 监控与 CloudWatch Events 集成，以获取 Amazon EBS、Amazon EC2、AWS CodeDeploy、Amazon ECS、AWS Health API 和通知、Amazon RDS、Amazon S3 和 AWS Step Functions 中的洞察。

1. 在 **Integrate with AWS Systems Manager OpsCenter**（与 OpsCenter 集成）下，选中 **Generate AWS Systems Manager OpsCenter OpsItems for remedial actions**（生成 OpsCenter OpsItems 以采取修复措施）旁边的复选框，以在检测到所选应用程序的问题时查看问题及接收通知。要跟踪为解析与 AWS 资源相关的操作工作项（称为 [OpsItems](https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-getting-started-sns.html)）而执行的操作，请提供 SNS 主题 ARN。

1. 您可以选择输入标签以帮助您标识和整理资源。CloudWatch Application Insights 支持基于标签和基于 CloudFormation 堆栈的资源组（Application Auto Scaling 组除外）。有关更多信息，请参阅 *AWS Resource Groups 和标签用户指南*中的[标签编辑器](https://docs.aws.amazon.com/ARG/latest/userguide/tag-editor.html)。

1. 要查看检测到的组件，请选择**下一步**。

1. **查看检测到的组件**页面上列出了 CloudWatch Application Insights 自动检测到的受监控组件及其工作负载。

   1. 如需编辑工作负载类型和名称，请选择**编辑组件**。
**注意**  
包含检测到的 NetWeaver 分布式或 NetWeaver 高可用性工作负载的组件仅支持一个组件一个工作负载。  
![\[CloudWatch Application Insights 控制台的“查看检测到的组件”部分：可以编辑的组件列表。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/appinsights-multiapp-netweaver.png)

1. 选择**下一步**。

1. 在 **Specify component details**（指定组件详细信息）页面上，选择 **Next**（下一步）。

1. 查看应用程序监控配置，然后选择**提交**。

1. 应用程序详细信息页面会打开，您可以在其中查看**应用程序摘要**、**控制面板**、**组件**和**工作负载**。您还可以查看 **Configuration history**（配置历史记录）、**Log patterns**（日志模式）和已创建的任何 **Tags**（标签）。在您提交应用程序后，CloudWatch Application Insights 会为您的 SAP NetWeaver 系统部署所有指标和告警，这最多可能需要一小时。

## 管理 SAP NetWeaver 应用程序服务器的监控
<a name="appinsights-tutorial-sap-netweaver-manage"></a>

请按照以下步骤管理 SAP NetWeaver 应用程序服务器的监控。

**管理监控**

1. 打开 [CloudWatch 控制台](https://console.aws.amazon.com/cloudwatch)。

1. 从左侧导航窗格中，选择 **Insights** 下的 **Application Insights**。

1. 选择 **List view**（列表视图）选项卡。

1. **Application Insights** 页面会显示使用 Application Insights 监控的应用程序列表以及每个应用程序的监控状态。

1. 选择您的应用程序。

1. 选择 **Components**（组件）选项卡。

1. 在 **Monitored components**（已监控组件）下，选择组件名称旁边的单选按钮。然后，选择 **Manage monitoring**（管理监控）。

1. 在 **Instance logs**（实例日志）下，您可以更新现有的日志路径、日志模式集和日志组名称。此外，您可以额外添加最多三个 **Application logs**（应用程序日志）。

1. 在 **Metrics**（指标）下，您可以根据自己的要求选择 SAP NetWeaver 指标。SAP NetWeaver 指标名称的前缀是 `sap`。每个组件可以添加最多 40 个指标。

1. 在**Custom alarms**（自定义告警）下，您可以添加可由 CloudWatch Application Insights 监控的额外告警。

1. 查看应用程序监控配置并选择 **Save**（保存）。提交配置时，您的账户会为 SAP NetWeaver 系统更新所有指标和告警。

## 查看和排查 CloudWatch Application Insights 检测到的 SAP NetWeaver 问题
<a name="appinsights-tutorial-sap-netweaver-troubleshooting"></a>

以下部分提供的步骤可帮助您解决在 Application Insights 上为 SAP NetWeaver 配置监控时出现的常见问题排查情况。

**Topics**
+ [SAP NetWeaver 数据库连接问题](#appinsights-tutorial-sap-netweaver-troubleshooting-database)
+ [SAP NetWeaver 应用程序可用性问题](#appinsights-tutorial-sap-netweaver-troubleshooting-availability)

### SAP NetWeaver 数据库连接问题
<a name="appinsights-tutorial-sap-netweaver-troubleshooting-database"></a>

**描述**  
您的 SAP NetWeaver 应用程序出现数据库连接问题。

**原因**  
您可以前往 CloudWatch Application Insights 控制台并查看 SAP NetWeaver Application Insights 问题控制面板来确定连接问题。选择 **Problem summary**（问题摘要）下的链接以查看特定问题。

![\[CloudWatch Application Insights 的 Detected problems（检测到的问题）控制面板，在 Problem summary（问题摘要）列的 Detected problems（检测到的问题）部分下提供了更多信息。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/appinsights-nw-database-connectivity-1.png)


在以下示例中，**Problem summary**（问题摘要）下的 SAP: Availability（SAP：可用性）是出现的问题。

![\[CloudWatch Application Insights 的问题摘要页面位于 Problem summary（问题摘要）部分下。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/appinsights-nw-database-connectivity-2.png)


紧接在 **Problem summary**（问题摘要）之后，**Insight**（洞察）部分提供了有关错误的更多上下文，您可以从中获得有关问题原因的更多信息。

![\[CloudWatch Application Insights 的问题洞察部分提供了有关错误原因的更多信息。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/appinsights-nw-database-connectivity-3.png)


在同一个问题控制面板上，您可以查看问题检测功能汇总在一起的相关日志和指标，以帮助您找出错误原因。`sap_alerts_Availability` 指标可跟踪 SAP NetWeaver 系统随时间变化的可用性。您可以使用历史跟踪功能来关联该指标何时启动错误状态或超出告警阈值。在以下示例中，SAP NetWeaver 系统存在可用性问题。该示例显示了两个告警，因为有两个 SAP 应用程序服务器实例，系统为每个实例创建了一个告警。

![\[CloudWatch Application Insights 的 SAP 可用性指标提供了有关错误发生时间的历史记录的更多信息。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/appinsights-nw-database-connectivity-4.png)


如要了解有关每个告警的更多信息，请将鼠标悬停在 `sap_alerts_Availability` 指标名称上。

![\[CloudWatch Application Insights 的 SAP 可用性指标提供了有关错误的更多详细信息。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/appinsights-nw-database-connectivity-5.png)


在以下示例中，`sap_alerts_Database` 指标显示数据库层存在问题或故障。该告警表明 SAP NetWeaver 在连接到其数据库或与其数据库通信时出现了问题。

![\[CloudWatch Application Insights 的 SAP 数据库指标提供了有关错误发生时间的更多历史记录。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/appinsights-nw-database-connectivity-6.png)


由于数据库是 SAP NetWeaver 的关键资源，因此当数据库出现问题或故障时，您可能会收到许多相关的告警。在以下示例中，由于数据库不可用，系统启动了 `sap_alerts_FrontendResponseTime` 和 `sap_alerts_LongRunners` 指标。

![\[由于数据库故障而创建的 CloudWatch Application Insights 的其他 SAP 数据库指标。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/appinsights-nw-database-connectivity-7.png)


**解决方案**  
Application Insights 按小时监测检测到的问题。如果 SAP NetWeaver 日志文件中没有新的相关日志条目，则较旧的日志条目将被视为已解决。您必须修复与 CloudWatch 告警相关的任何错误条件。修复错误条件后，在恢复告警和日志时告警会得到解决。解决所有 CloudWatch 日志错误和告警后，Application Insights 将停止检测错误，问题将在一小时内自动解决。我们建议您解决所有日志错误条件和告警，这样您就可以在问题控制面板上看到最新的问题。

以下示例中解决了 SAP 可用性问题。

![\[CloudWatch Application Insights 问题控制面板解决了 SAP 可用性问题。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/appinsights-nw-database-connectivity-resolved.png)


### SAP NetWeaver 应用程序可用性问题
<a name="appinsights-tutorial-sap-netweaver-troubleshooting-availability"></a>

**描述**  
SAP NetWeaver 高可用性入队复制停止运行。

**原因**  
您可以前往 CloudWatch Application Insights 控制台并查看 SAP NetWeaver Application Insights 问题控制面板来确定连接问题。选择 **Problem summary**（问题摘要）下的链接以查看特定问题。

![\[CloudWatch Application Insights 的问题控制面板在 Problem summary（问题摘要）下提供了更多信息。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/appinsights-nw-app-availability-problem-dashboard.png)


在以下示例中，**Problem summary**（问题摘要）下的高可用性入队复制是出现的问题。

![\[CloudWatch Application Insights 的问题摘要列出了 SAP Availability: Enqueue Replication（SAP 可用性：入队复制）错误。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/appinsights-nw-app-availability-1.png)


紧接在 **Problem summary**（问题摘要）之后，**Insight**（洞察）部分提供了有关错误的更多上下文，您可以从中获得有关问题原因的更多信息。

![\[CloudWatch Application Insights 的问题洞察部分提供了有关错误原因的更多信息。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/appinsights-nw-app-availability-2.png)


以下示例显示了问题控制面板，您可以在其中查看分组的日志和指标，以帮助您找出错误原因。`sap_enqueue_server_replication_state` 指标可随时间跟踪该值。您可以使用历史跟踪功能来关联该指标何时启动错误状态或超出告警阈值。

![\[问题控制面板上的入队服务器复制状态指标提供了有关错误发生时间的更多信息。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/appinsights-nw-app-availability-3.png)


在以下示例中，`ha_cluster_pacemaker_fail_count` 指标显示高可用性 Pacemaker 集群出现了资源故障。组件控制面板中标识了故障次数大于或等于 1 的特定 Pacemaker 资源。

![\[故障次数大于或等于 1 的 Pacemaker 资源的 CloudWatch Application Insights 应用程序可用性指标。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/appinsights-nw-app-availability-4.png)


以下示例显示了 `sap_alerts_Shortdumps` 指标，该指标表明在检测到问题时 SAP 应用程序的性能有所降低。

![\[CloudWatch Application Insights 的应用程序可用性警报 Shortdumps 指标。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/appinsights-nw-app-availability-5.png)


#### 日志
<a name="ai-sap-netweaver-logs"></a>

这些日志条目有助于更好地了解在检测到问题时 SAP NetWeaver 层出现的问题。问题控制面板中的日志组小组件显示了问题发生的具体时间。

![\[CloudWatch Application Insights 的日志条目显示了问题发生的确切时间。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/appinsights-nw-app-availability-7.png)


要查看有关日志的详细信息，请选择右上角的三个垂直点，然后选择 **View in CloudWatch Logs Insights**（在 CloudWatch Logs Insights 中查看）。

![\[包含 View in CloudWatch Logs Insights（在 CloudWatch Logs Insights 中查看）功能的 CloudWatch Application Insights 详细信息。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/appinsights-nw-app-availability-8.png)


请按照以下步骤获取有关问题控制面板中显示的指标和告警的更多信息。

**获取有关指标和告警的更多信息**

1. 打开 [CloudWatch 控制台](https://console.aws.amazon.com/cloudwatch)。

1. 在左侧导航窗格中，选择 **Insights** 下的 **Application Insights**。然后，选择 **List view**（列表视图）选项卡，并选择您的应用程序。

1. 选择 **Components**（组件）选项卡。然后，选择您想要获取更多相关信息的 SAP NetWeaver 组件。

   以下示例显示了 **HA Metrics**（HA 指标）部分，其中包含问题控制面板中显示的 `ha_cluster_pacemaker_fail_count` 指标。  
![\[CloudWatch Application Insights 的 HA 指标显示了 Pacemaker 资源的故障次数。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/appinsights-nw-app-availability-9.png)

**解决方案**  
Application Insights 按小时监测检测到的问题。如果 SAP NetWeaver 日志文件中没有新的相关日志条目，则较旧的日志条目将被视为已解决。您必须修复与此问题相关的任何错误条件。

对于 `sap_alerts_Shortdumps` 告警，您必须使用事务代码 `RZ20 → R3Abap → Shortdumps` 导航到 CCMS 警报，以解决 SAP NetWeaver 系统中的警报。有关 CCMS 警报的更多信息，请参阅 [SAP 网站](https://help.sap.com/docs/SAP_NETWEAVER_701/6f45651d6c4b1014a50f9ef0fc8df39d/408dc4a7c415437a9b91d2ef6caa9d7d.html)。请解决 Shortdumps 树中的所有 CCMS 警报。在 SAP NetWeaver 系统中解决所有警报后，CloudWatch 将不再报告处于告警状态的指标。

解决所有 CloudWatch 日志错误和告警后，Application Insights 将停止检测错误，问题将在一小时内自动解决。我们建议您解决所有日志错误条件和告警，这样您就可以在问题控制面板上看到最新的问题。以下示例中解决了 SAP NetWeaver 高可用性入队复制问题。

![\[CloudWatch Application Insights 的问题控制面板显示 SAP Availability: Enqueue Replication（SAP 可用性：入队复制）问题处于 Resolved（已解决）状态。\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/images/appinsights-nw-app-availability-problem-resolved.png)


## 排查 Application Insights for SAP NetWeaver 的问题
<a name="appinsights-tutorial-sap-netweaver-troubleshooting-health-dashboard"></a>

本节提供了帮助您解决 Application Insights 控制面板返回的常见错误的步骤。

### 无法添加超过 60 个监控指标
<a name="ai-unable-add-monitor-metrics"></a>

**返回错误**：`Component cannot have more than 60 monitored metrics.`

**根本原因**：`The current metric limit is 60 monitor metrics per component.`

**解决方法**：删除遵守限制所不需要的指标。

### SAP 指标在载入过程后未显示在控制面板上
<a name="sap-metrics-not-on-dashboard"></a>

**根本原因**：组件控制面板使用五分钟的指标周期来聚合数据点。

**解决方法**：所有指标应在五分钟后显示在控制面板上。

### SAP 指标和告警未显示在控制面板上
<a name="sap-metrics-and-alarms-not-on-dashboard"></a>

请按照以下步骤来确定为什么 SAP 指标和告警在载入过程后未显示在控制面板上。

**使用指标和告警来确定问题**

1. 打开 [CloudWatch 控制台](https://console.aws.amazon.com/cloudwatch)。

1. 在左侧导航窗格中，选择 **Insights** 下的 **Application Insights**。然后，选择 **List view**（列表视图）选项卡，并选择您的应用程序。

1. 选择 **Configuration history**（配置历史记录）选项卡。

1. 如果您发现缺少指标数据点，请检查与 `prometheus-sap_host_exporter` 相关的错误。

1. 如果您在上一步中没有发现错误，请[连接到 Linux 实例](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AccessingInstances.html)。对于高可用性部署，请连接到主集群 Amazon EC2 实例。

1. 在您的实例中，使用以下命令验证导出器是否正在运行。默认端口为 `9680`。如果您使用的是其他端口，请将 `9680` 替换为您正在使用的端口。

   ```
   curl localhost:9680/metrics
   ```

   如果没有返回数据，则导出器启动失败。

1. 要查找在接下来的两个步骤用于 `WORKLOAD_SHORT_NAME` 的正确命名约定，请运行以下命令。
**注意**  
Application Insights 根据正在运行的工作负载在服务名称中添加后缀 `WORKLOAD_SHORT_NAME`。NetWeaver 分布式、标准和高可用性部署的简称分别为 `SAP_NWD`、`SAP_NWS` 和 `SAP_NWH`。

   ```
   sudo systemctl | grep exporter
   ```

1. 要检查导出器服务日志中是否存在错误，请运行以下命令：

   ```
   sudo journalctl -e --unit=prometheus-sap_host_exporter_WORKLOAD_SHORT_NAME.service
   ```

1. 要检查导出器管理器服务日志中是否存在错误，请运行以下命令：

   ```
   sudo journalctl -e --unit=prometheus-sap_host_exporter_manager_WORKLOAD_SHORT_NAME.service
   ```
**注意**  
此服务应始终处于启动和运行状态。

   如果此命令未返回错误，则继续执行下一步。

1. 要手动启动导出器，请运行以下命令。然后，检查导出器的输出。

   ```
   sudo /opt/aws/sap_host_exporter/sap_host_exporter
   ```

   检查错误后，可以退出导出器进程。

**根本原因**：有多种可能的原因会导致此问题。一个常见的原因是导出器无法连接到其中一个应用程序服务器实例。

**解决方法**

请按照以下步骤将导出器连接到应用程序服务器实例。您将验证 SAP 应用程序实例是否正在运行，并使用 SAPControl 连接到该实例。

**将导出器连接到应用程序服务器实例**

1. 在 Amazon EC2 实例中，运行以下命令验证 SAP 应用程序是否正在运行。

   ```
   sapcontrol -nr <App_InstNo> -function GetProcessList
   ```

1. 您必须建立有效的 SAPControl 连接。如果 SAPControl 连接不起作用，请在相关的 SAP 应用程序实例上找到问题的根本原因。

1. 如要在修复 SAPControl 连接问题后手动启动导出器，请运行以下命令：

   ```
   sudo systemctl start prometheus-sap_host_exporter.service
   ```

1. 如果您无法解决 SAPControl 连接问题，请使用以下步骤作为临时修复方案。

   1. 打开[AWS Systems Manager控制台](https://console.aws.amazon.com/systems-manager)。

   1. 从左侧导航窗格中，选择 **State Manager**（状态管理器）。

   1. 在 **Associations**（关联）下搜索 SAP NetWeaver 系统的关联。

      ```
      Association Name: Equal: AWS-ApplicationInsights-SSMSAPHostExporterAssociationForCUSTOMSAPNW<SID>-1
      ```

   1. 选择 **Association id**（关联 ID）。

   1. 选择 **Parameters**（参数）选项卡，然后从 **additionalArguments**（附加参数）中删除应用程序服务器编号。

   1. 选择 **Apply Association Now**（立即应用关联）。
**注意**  
这是临时修复。如果对组件的监控配置进行了更新，则将重新添加该实例。

# 查看和排查 Amazon CloudWatch Application Insights 检测到的问题
<a name="appinsights-troubleshooting"></a>

本节中的主题介绍 Application Insights 显示的检测到的问题相关详细信息和见解，并针对检测到的您账户或配置的问题提供了建议解决方法。

**Topics**
+ [CloudWatch 控制台概览](#appinsights-troubleshooting-overview)
+ [Application Insights 问题摘要页面](#appinsights-troubleshooting-problem-summary)
+ [CloudWatch 代理合并冲突失败](#cwagent-merge-conflicts)
+ [CloudWatch 代理日志处理导致 CPU 使用率过高](#cwagent-high-cpu-usage)
+ [未创建警报](#alarms-not-created)
+ [反馈](#appinsights-troubleshooting-feedback)
+ [配置错误](#appinsights-configuration-errors)

## CloudWatch 控制台概览
<a name="appinsights-troubleshooting-overview"></a>

[CloudWatch 控制台](https://console.aws.amazon.com/cloudwatch)概览页面中的 CloudWatch Application Insights 窗格下列出了影响已监控应用程序的问题概览。

CloudWatch Application Insights 概览窗格显示以下内容：
+ 所检测到的问题的严重性：高/中/低
+ 问题的简短摘要
+ 问题来源
+ 问题的开始时间
+ 问题的解决状态
+ 受影响的资源组

要查看特定问题的详细信息，请在 **Problem Summary**（问题摘要）下选择问题描述。详细控制面板显示问题信息以及相关的指标异常情况和日志错误片段。您可以选择该信息是否有用，以提供相关性反馈。

如果检测到未配置的新资源，问题摘要描述将转到 **Edit configuration**（编辑配置）向导以配置新资源。您可以选择详细控制面板右上角的 **View/edit configuration**（查看/编辑配置）来查看或编辑资源组配置。

要返回到概览，请选择 **Back to overview（返回概览）**，它位于 CloudWatch Application Insights 详细控制面板标题旁边。

## Application Insights 问题摘要页面
<a name="appinsights-troubleshooting-problem-summary"></a>

**Application Insights 问题摘要页面**  
CloudWatch Application Insights 在问题摘要页面上提供有关检测到的问题的以下信息：
+ 问题的简短摘要
+ 问题的开始时间和日期
+ 问题严重性：高/中/低
+ 检测到的问题的状态：正在进行/已解决
+ 信息：自动生成有关检测到的问题和可能的根本原因的信息
+ 信息反馈：您为有关 CloudWatch Application Insights 生成的信息是否有用提供的反馈
+ 相关的观察结果：与各种应用程序组件中的问题相关的指标异常情况和相关日志错误片段的详细视图

## CloudWatch 代理合并冲突失败
<a name="cwagent-merge-conflicts"></a>

CloudWatch Application Insights 在客户实例上安装和配置 CloudWatch 代理。这包括创建包含指标或日志配置的 CloudWatch 代理配置文件。如果客户的实例已经有一个 CloudWatch 代理配置文件，该文件为相同的指标或日志定义了不同的配置，则可能会发生合并冲突。要解决合并冲突，请使用下面的步骤：

1. 识别系统上的 CloudWatch 代理配置文件。有关文件位置的更多信息，请参阅 [CloudWatch 代理文件和位置](troubleshooting-CloudWatch-Agent.md#CloudWatch-Agent-files-and-locations)。

1. 从现有 CloudWatch 代理配置文件中删除要在 Application Insights 中使用的资源配置。如果您只想使用 Application Insights 配置，请删除现有的 CloudWatch 代理配置文件。

## CloudWatch 代理日志处理导致 CPU 使用率过高
<a name="cwagent-high-cpu-usage"></a>

CloudWatch Application Insights 在客户实例上安装和配置 CloudWatch 代理。如果为 Amazon EC2 实例配置了包含大量日志数据的日志路径，则在 CloudWatch 代理处理日志时，该实例的 CPU 使用率可能会增加。要降低 CPU 使用率，请删除 [Amazon EC2 实例组件配置](component-configuration-examples-ec2.md)中的日志路径。

## 未创建警报
<a name="alarms-not-created"></a>

对于某些指标，Application Insights 会根据该指标的先前数据点预测警报阈值。如需启用此预测，必须满足以下条件。
+ **最近的数据点** – 过去 24 小时内必须至少有 100 个数据点。数据点不需要是连续的，可以分散在 24 小时的时间范围内。
+ **历史数据** - 从当前日期前 15 天到当前日期前 1 天的时间范围内，必须至少有 100 个数据点。数据点不需要是连续的，可以分散在 15 天的时间范围内。

**注意**  
对于某些指标，Application Insights 会延迟创建警报，直到满足上述条件。在这种情况下，您会收到一个配置历史事件，表明该指标缺乏足够的数据点来建立警报阈值。

## 反馈
<a name="appinsights-troubleshooting-feedback"></a>

**反馈**

您可以指定为检测到的问题自动生成的信息是否有用以提供反馈。将使用您对这些信息的反馈以及应用程序诊断（指标异常情况和日志异常情况）改进将来对类似问题的检测。

## 配置错误
<a name="appinsights-configuration-errors"></a>

CloudWatch Application Insights 使用您的配置为组件创建监控遥测数据。在 Application Insights 检测到您的账户或配置存在问题时，将在应用程序摘要的 **Remarks**（备注）字段中提供有关如何解决应用程序配置问题的信息。

下表显示了特定备注的建议解决方案。


| 备注 | 建议的解决方案 | 附加说明  | 
| --- | --- | --- | 
|  已达到 CloudFormation 的配额。  |  Application Insights 为每个应用程序创建一个 CloudFormation 堆栈，以管理所有应用程序组件的 CloudWatch 代理安装和配置。默认情况下，每个 AWS 账户可以具有 2000 个堆栈。请参阅 [CloudFormation 限制](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cloudformation-limits.html)。要解决该问题，请提高 CloudFormation 堆栈的限制。  | 不适用 | 
|  在以下实例上没有 SSM 实例角色。  |  要使 Application Insights 能够在应用程序实例上安装和配置 CloudWatch 代理，必须将 AmazonSSMManagedInstanceCore 和 CloudWatchAgentServerPolicy 策略附加到该实例角色。  |  Application Insights 会调用 SSM [DescribeInstanceInformation API](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeInstanceInformation.html) 以获取具有 SSM 权限的实例列表。在将该角色附加到实例后，SSM 需要一段时间以将实例包含在 DescribeInstanceInformation 结果中。在 SSM 将实例包含在结果中之前，应用程序仍然存在 NO\$1SSM\$1INSTANCE\$1ROLE 错误。  | 
|  新组件可能需要进行配置。  |  Application Insights 检测到在应用程序资源组中具有新组件。要解决该问题，请相应地配置新组件。  | 不适用 | 

# Amazon CloudWatch Application Insights 支持的日志和指标
<a name="appinsights-logs-and-metrics"></a>

以下列表显示 Amazon CloudWatch Application Insights 支持的日志和指标。

**CloudWatch Application Insights 支持以下日志：**
+ Microsoft Internet 信息服务 (IIS) 日志
+ EC2 上的 SQL Server 的错误日志
+ 自定义 .NET 应用程序日志，例如 Log4Net
+ Windows 事件日志，包括 Windows 日志（系统、应用程序和安全），以及应用程序和服务日志
+ 适用于 AWS Lambda 的 Amazon CloudWatch Logs
+ EC2 上 RDS MySQL、Aurora MySQL 和 MySQL 的错误日志和慢速日志
+ 适用于 EC2 上的 PostgreSQL RDS 和 PostgreSQL 的 Postgresql 日志
+ 适用于 AWS Step Functions 的 Amazon CloudWatch Logs
+ API Gateway REST API 阶段的执行日志和访问日志（JSON、CSV 和 XML，但不包括 CLF）
+ Prometheus JMX Exporter 日志 (EMF)
+ Amazon RDS 上的 Oracle 和 Amazon EC2 上的 Oracle 的提示日志和侦听器日志
+ 使用 [`awslogs` 日志驱动程序](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_awslogs.html)从 Amazon ECS 容器路由到 CloudWatch 的容器日志。
+ 使用 [FireLens 容器日志路由器](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_firelens.html)从 Amazon ECS 容器路由到 CloudWatch 的容器日志。
+ 使用带有 Container Insights 的 [Fluent Bit 或 Fluentd 日志处理器](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Container-Insights-EKS-logs.html)，从 Amazon EKS 或在 Amazon EC2 上运行的 Kubernetes 路由到 CloudWatch 的容器日志。
+ SAP HANA 跟踪和错误日志
+ HA Pacemaker 日志
+ SAP ASE 服务器日志
+ SAP ASE 备份服务器日志
+ SAP ASE 复制服务器日志
+ SAP ASE RMA 代理日志
+ SAP ASE 故障管理器日志
+ SAP NetWeaver 开发人员跟踪日志
+ 使用 [CloudWatch 代理的 proctstat 插件](CloudWatch-Agent-procstat-process-metrics.md)的 Windows 进程的进程指标
+ 托管区域的公有 DNS 查询日志
+ Amazon Route 53 Resolver DNS 查询日志

**CloudWatch Application Insights 支持以下日志类：**
+ **标准**：Amazon CloudWatch Application Insights 要求日志组配置 [CloudWatch Logs 标准日志类](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CloudWatch_Logs_Log_Classes.html)才能启用监控。

**Contents**
+ [Amazon Elastic Compute Cloud (EC2)](appinsights-metrics-ec2.md)
  + [CloudWatch 内置指标](appinsights-metrics-ec2.md#appinsights-metrics-ec2-built-in)
  + [CloudWatch 代理指标 (Windows Server)](appinsights-metrics-ec2.md#appinsights-metrics-ec2-windows)
  + [CloudWatch 代理进程指标 (Windows Server)](appinsights-metrics-ec2.md#appinsights-metrics-procstat-ec2-windows)
  + [CloudWatch 代理指标 (Linux Server)](appinsights-metrics-ec2.md#appinsights-metrics-ec2-linux)
+ [Elastic Block Store (EBS)](appinsights-metrics-ebs.md)
+ [Amazon Elastic File System (Amazon EFS)](appinsights-metrics-efs.md)
+ [Elastic Load Balancer (ELB)](appinsights-metrics-elb.md)
+ [Application ELB](appinsights-metrics-app-elb.md)
+ [Amazon EC2 Auto Scaling 组](appinsights-metrics-as.md)
+ [Amazon Simple Queue Server (SQS)](appinsights-metrics-sqs.md)
+ [Amazon Relational Database Service（RDS）](appinsights-metrics-rds.md)
  + [RDS 数据库实例](appinsights-metrics-rds.md#appinsights-metrics-rds-instances)
  + [RDS 数据库集群](appinsights-metrics-rds.md#appinsights-metrics-rds-clusters)
+ [AWS Lambda 函数](appinsights-metrics-lambda.md)
+ [Amazon DynamoDB 表](appinsights-metrics-dyanamodb.md)
+ [Amazon S3 存储桶](appinsights-metrics-s3.md)
+ [AWS Step Functions](appinsights-metrics-step-functions.md)
  + [Execution-level](appinsights-metrics-step-functions.md#appinsights-metrics-step-functions-execution)
  + [活动](appinsights-metrics-step-functions.md#appinsights-metrics-step-functions-activity)
  + [Lambda 函数](appinsights-metrics-step-functions.md#appinsights-metrics-step-functions-lambda)
  + [服务集成](appinsights-metrics-step-functions.md#appinsights-metrics-step-functions-service-integration)
  + [Step Functions API](appinsights-metrics-step-functions.md#appinsights-metrics-step-functions-api)
+ [API Gateway REST API 阶段](appinsights-metrics-api-gateway.md)
+ [SAP HANA](appinsights-metrics-sap-hana.md)
+ [SAP ASE](appinsights-metrics-sap-ase.md)
+ [Amazon EC2 上的 SAP ASE 高可用性](appinsights-metrics-sap-ase-ha.md)
+ [SAP NetWeaver](appinsights-metrics-sap-netweaver.md)
+ [HA 集群](appinsights-metrics-ha-cluster.md)
+ [Java](appinsights-metrics-java.md)
+ [Amazon Elastic Container Service（Amazon ECS）](appinsights-metrics-ecs.md)
  + [CloudWatch 内置指标](appinsights-metrics-ecs.md#appinsights-metrics-ecs-built-in-metrics)
  + [Container Insights 指标](appinsights-metrics-ecs.md#appinsights-metrics-ecs-container-insights-metrics)
  + [Container Insights Prometheus 指标](appinsights-metrics-ecs.md#appinsights-metrics-ecs-container-insights-prometheus)
+ [AWS 上的 Kubernetes](appinsights-metrics-kubernetes.md)
  + [Container Insights 指标](appinsights-metrics-kubernetes.md#appinsights-metrics-kubernetes-container-insights-metrics)
  + [Container Insights Prometheus 指标](appinsights-metrics-kubernetes.md#appinsights-metrics-kubernetes-container-insights-prometheus)
+ [Amazon FSx](appinsights-metrics-fsx.md)
+ [Amazon VPC](appinsights-metrics-vpc.md)
+ [Amazon VPC NAT 网关](appinsights-metrics-nat-gateways.md)
+ [Amazon Route 53 运行状况检查](appinsights-metrics-health-check.md)
+ [Amazon Route 53 托管区](appinsights-metrics-hosted-zone.md)
+ [Amazon Route 53 Resolver 端点](appinsights-metrics-resolver-endpoint.md)
+ [AWS Network Firewall 规则组](appinsights-metrics-firewall-rule-group.md)
+ [AWS Network Firewall 规则组关联](appinsights-metrics-firewall-rule-group-assoc.md)
+ [具有数据点要求的指标](appinsights-metrics-datapoint-requirements.md)
  + [AWS/ApplicationELB](appinsights-metrics-datapoint-requirements.md#appinsights-metrics-datapoint-requirements-app-elb)
  + [AWS/AutoScaling](appinsights-metrics-datapoint-requirements.md#appinsights-metrics-datapoint-requirements-autoscaling)
  + [AWS/EC2](appinsights-metrics-datapoint-requirements.md#appinsights-metrics-datapoint-requirements-ec2)
  + [Elastic Block Store (EBS)](appinsights-metrics-datapoint-requirements.md#appinsights-metrics-datapoint-requirements-ebs)
  + [AWS/ELB](appinsights-metrics-datapoint-requirements.md#appinsights-metrics-datapoint-requirements-elb)
  + [AWS/RDS](appinsights-metrics-datapoint-requirements.md#appinsights-metrics-datapoint-requirements-rds)
  + [AWS/Lambda](appinsights-metrics-datapoint-requirements.md#appinsights-metrics-datapoint-requirements-lambda)
  + [AWS/SQS](appinsights-metrics-datapoint-requirements.md#appinsights-metrics-datapoint-requirements-sqs)
  + [AWS/CWAgent](appinsights-metrics-datapoint-requirements.md#appinsights-metrics-datapoint-requirements-cwagent)
  + [AWS/DynamoDB](appinsights-metrics-datapoint-requirements.md#appinsights-metrics-datapoint-requirements-dynamo)
  + [AWS/S3](appinsights-metrics-datapoint-requirements.md#appinsights-metrics-datapoint-requirements-s3)
  + [AWS/States](appinsights-metrics-datapoint-requirements.md#appinsights-metrics-datapoint-requirements-states)
  + [AWS/ApiGateway](appinsights-metrics-datapoint-requirements.md#appinsights-metrics-datapoint-requirements-api-gateway)
  + [AWS/SNS](appinsights-metrics-datapoint-requirements.md#appinsights-metrics-datapoint-requirements-sns)
+ [推荐的指标](application-insights-recommended-metrics.md)
+ [性能计数器指标](application-insights-performance-counter.md)

# Amazon Elastic Compute Cloud (EC2)
<a name="appinsights-metrics-ec2"></a>

CloudWatch Application Insights 支持以下指标：

**Topics**
+ [CloudWatch 内置指标](#appinsights-metrics-ec2-built-in)
+ [CloudWatch 代理指标 (Windows Server)](#appinsights-metrics-ec2-windows)
+ [CloudWatch 代理进程指标 (Windows Server)](#appinsights-metrics-procstat-ec2-windows)
+ [CloudWatch 代理指标 (Linux Server)](#appinsights-metrics-ec2-linux)

## CloudWatch 内置指标
<a name="appinsights-metrics-ec2-built-in"></a>

CPUCreditBalance

CPUCreditUsage

CPUSurplusCreditBalance

CPUSurplusCreditsCharged

CPUUtilization

磁盘读取字节数

磁盘读取操作

磁盘写入字节数

磁盘写入操作

EBSByteBalance%

EBSIOBalance%

EBSReadBytes

EBSReadOps

EBSWriteBytes

EBSWriteOps

NetworkIn

网络输出

NetworkPacketsIn

NetworkPacketsOut

StatusCheckFailed

StatusCheckFailed\$1Instance

StatusCheckFailed\$1System

## CloudWatch 代理指标 (Windows Server)
<a name="appinsights-metrics-ec2-windows"></a>

.NET CLR Exceptions \$1 of Exceps Thrown

.NET CLR Exceptions \$1 of Exceps Thrown/Sec

.NET CLR Exceptions \$1 of Filters/sec

.NET CLR Exceptions \$1 of Finallys/sec

.NET CLR Exceptions Throw to Catch Depth/sec

.NET CLR Interop \$1 of CCWs

.NET CLR Interop \$1 of Stubs

.NET CLR Interop \$1 of TLB exports/sec

.NET CLR Interop \$1 of TLB imports/sec

.NET CLR Interop \$1 of marshaling

.NET CLR Jit % Time in Jit

.NET CLR Jit Standard Jit Failures

.NET CLR Loading % Time Loading

.NET CLR Loading Rate of Load Failures

.NET CLR LocksAndThreads Contention Rate/sec

.NET CLR LocksAndThreads Queue Length/sec

.NET CLR Memory \$1 Total Committed Bytes

.NET CLR Memory % Time in GC

.NET CLR Networking 4.0.0.0 HttpWebRequest Average Queue Time

.NET CLR Networking 4.0.0.0 HttpWebRequests Aborted/sec

.NET CLR Networking 4.0.0.0 HttpWebRequests Failed/sec

.NET CLR Networking 4.0.0.0 HttpWebRequests Queued/sec

APP\$1POOL\$1WAS Total Worker Process Ping Failures

ASP.NET Application Restarts

ASP.NET Applications % Managed Processor Time (estimated)

ASP.NET Applications Errors Total/Sec

ASP.NET Applications Errors Unhandled During Execution/sec

ASP.NET Applications Requests in Application Queue

ASP.NET Applications Requests/Sec

ASP.NET Request Wait Time

ASP.NET Requests Queued

HTTP Service Request Queues CurrentQueueSize

LogicalDisk % Free Space

Memory % Committed Bytes In Use

Memory Available Mbytes

Memory Pages/sec

Network Interface Bytes Total/sec

Paging File % Usage

PhysicalDisk % Disk Time

PhysicalDisk Avg。Disk Queue Length

PhysicalDisk Avg。Disk sec/Read

PhysicalDisk Avg。Disk sec/Write

PhysicalDisk Disk Read Bytes/sec

PhysicalDisk Disk Reads/sec

PhysicalDisk Disk Write Bytes/sec

PhysicalDisk Disk Writes/sec

Processor % Idle Time

Processor % Interrupt Time

Processor % Processor Time

Processor % User Time

SQLServer:Access Methods Forwarded Records/sec

SQLServer:Access Methods Full Scans/sec

SQLServer:Access Methods Page Splits/sec

SQLServer:Buffer Manager Buffer cache hit ratio

SQLServer:Buffer Manager Page life expectancy

SQLServer:General Statistics Processes blocked

SQLServer:General Statistics User Connections

SQLServer:Latches Average Latch Wait Time (ms)

SQLServer:Locks Average Wait Time (ms)

SQLServer:Locks Lock Timeouts/sec

SQLServer:Locks Lock Waits/sec

SQLServer:Locks Number of Deadlocks/sec

SQLServer:Memory Manager Memory Grants Pending

SQLServer:SQL Statistics Batch Requests/sec

SQLServer:SQL Statistics SQL Compilations/sec

SQLServer:SQL Statistics SQL Re-Compilations/sec

System Processor Queue Length

TCPv4 Connections Established

TCPv6 Connections Established

W3SVC\$1W3WP File Cache Flushes

W3SVC\$1W3WP File Cache Misses

W3SVC\$1W3WP Requests/Sec

W3SVC\$1W3WP URI Cache Flushes

W3SVC\$1W3WP URI Cache Misses

Web Service Bytes Received/Sec

Web Service Bytes Sent/Sec

Web Service Connection attempts/sec

Web Service Current Connections

Web Service Get Requests/sec

Web Service Post Requests/sec

Bytes Received/sec

Normal Messages Queue Length/sec

Urgent Message Queue Length/sec

Reconnect Count

Unacknowledged Message Queue Length/sec

Messages Outstanding

Messages Sent/sec

Database Update Messages/sec

Update Messages/sec

Flushes/sec

Crypto Checkpoints Saved/sec

Crypto Checkpoints Restored/sec

Registry Checkpoints Restored/sec

Registry Checkpoints Saved/sec

Cluster API Calls/sec

Resource API Calls/sec

Cluster Handles/sec

Resource Handles/sec

## CloudWatch 代理进程指标 (Windows Server)
<a name="appinsights-metrics-procstat-ec2-windows"></a>

进程指标使用 [CloudWatch 代理 procstat 插件](CloudWatch-Agent-procstat-process-metrics.md)收集。只有运行 Windows 工作负载的 Amazon EC2 实例支持进程指标。

procstat cpu\$1time\$1system

procstat cpu\$1time\$1user

procstat cpu\$1usage

procstat memory\$1rss

procstat memory\$1vms

procstat read\$1bytes

procstat write\$1bytes

.procstat read\$1count

procstat write\$1count

## CloudWatch 代理指标 (Linux Server)
<a name="appinsights-metrics-ec2-linux"></a>

cpu\$1time\$1active

cpu\$1time\$1guest

cpu\$1time\$1guest\$1nice

cpu\$1time\$1idle

cpu\$1time\$1iowait

cpu\$1time\$1irq

cpu\$1time\$1nice

cpu\$1time\$1softirq

cpu\$1time\$1steal

cpu\$1time\$1system

cpu\$1time\$1user

cpu\$1usage\$1active

cpu\$1usage\$1guest

cpu\$1usage\$1guest\$1nice

cpu\$1usage\$1idle

cpu\$1usage\$1iowait

cpu\$1usage\$1irq

cpu\$1usage\$1nice

cpu\$1usage\$1softirq

cpu\$1usage\$1steal

cpu\$1usage\$1system

cpu\$1usage\$1user

disk\$1free

disk\$1inodes\$1free

disk\$1inodes\$1used

disk\$1used

disk\$1used\$1percent

diskio\$1io\$1time

diskio\$1iops\$1in\$1progress

diskio\$1read\$1bytes

diskio\$1read\$1time

diskio\$1reads

diskio\$1write\$1bytes

diskio\$1write\$1time

diskio\$1writes

mem\$1active

mem\$1available

mem\$1available\$1percent

mem\$1buffered

mem\$1cached

mem\$1free

mem\$1inactive

mem\$1used

mem\$1used\$1percent

net\$1bytes\$1recv

net\$1bytes\$1sent

net\$1drop\$1in

net\$1drop\$1out

net\$1err\$1in

net\$1err\$1out

net\$1packets\$1recv

net\$1packets\$1sent

netstat\$1tcp\$1close

netstat\$1tcp\$1close\$1wait

netstat\$1tcp\$1closing

netstat\$1tcp\$1established

netstat\$1tcp\$1fin\$1wait1

netstat\$1tcp\$1fin\$1wait2

netstat\$1tcp\$1last\$1ack

netstat\$1tcp\$1listen

netstat\$1tcp\$1none

netstat\$1tcp\$1syn\$1recv

netstat\$1tcp\$1syn\$1sent

netstat\$1tcp\$1time\$1wait

netstat\$1udp\$1socket

processes\$1blocked

processes\$1dead

processes\$1idle

processes\$1paging

processes\$1running

processes\$1sleeping

processes\$1stopped

processes\$1total

processes\$1total\$1threads

processes\$1wait

processes\$1zombies

swap\$1free

swap\$1used

swap\$1used\$1percent

# Elastic Block Store (EBS)
<a name="appinsights-metrics-ebs"></a>

CloudWatch Application Insights 支持以下指标：

VolumeReadBytes

VolumeWriteBytes

VolumeReadOps

VolumeWriteOps

VolumeTotalReadTime 

VolumeTotalWriteTime 

VolumeIdleTime

VolumeQueueLength

VolumeThroughputPercentage

VolumeConsumedReadWriteOps

BurstBalance

# Amazon Elastic File System (Amazon EFS)
<a name="appinsights-metrics-efs"></a>

CloudWatch Application Insights 支持以下指标：

BurstCreditBalance

PercentIOLimit

PermittedThroughput

MeteredIOBytes

TotalIOBytes

DataWriteIOBytes

DataReadIOBytes

MetadataIOBytes

ClientConnections

TimeSinceLastSync

StorageBytes

吞吐量

PercentageOfPermittedThroughputUtilization

ThroughputIOPS

 PercentThroughputDataReadIOByte

PercentThroughputDataWriteIOBytes

PercentageOfIOPSDataReadIOBytes

PercentageOfIOPSDataWriteIOBytes

AverageDataReadIOBytesSize

AverageDataWriteIOBytesSize

# Elastic Load Balancer (ELB)
<a name="appinsights-metrics-elb"></a>

CloudWatch Application Insights 支持以下指标：

EstimatedALBActiveConnectionCount

EstimatedALBConsumedLCUs

EstimatedALBNewConnectionCount

EstimatedProcessedBytes

HTTPCode\$1Backend\$14XX

HTTPCode\$1Backend\$15XX

HealthyHostCount

RequestCount

UnHealthyHostCount

# Application ELB
<a name="appinsights-metrics-app-elb"></a>

CloudWatch Application Insights 支持以下指标：

EstimatedALBActiveConnectionCount

EstimatedALBConsumedLCUs

EstimatedALBNewConnectionCount

EstimatedProcessedBytes

HTTPCode\$1Backend\$14XX

HTTPCode\$1Backend\$15XX

HealthyHostCount

延迟

RequestCount

SurgeQueueLength

UnHealthyHostCount

# Amazon EC2 Auto Scaling 组
<a name="appinsights-metrics-as"></a>

CloudWatch Application Insights 支持以下指标：

CPUCreditBalance

CPUCreditUsage

CPUSurplusCreditBalance

CPUSurplusCreditsCharged

CPUUtilization

磁盘读取字节数

磁盘读取操作

磁盘写入字节数

磁盘写入操作

EBSByteBalance%

EBSIOBalance%

EBSReadBytes

EBSReadOps

EBSWriteBytes

EBSWriteOps

NetworkIn

网络输出

NetworkPacketsIn

NetworkPacketsOut

StatusCheckFailed

StatusCheckFailed\$1Instance

StatusCheckFailed\$1System

# Amazon Simple Queue Server (SQS)
<a name="appinsights-metrics-sqs"></a>

CloudWatch Application Insights 支持以下指标：

ApproximateAgeOfOldestMessage

ApproximateNumberOfMessagesDelayed

ApproximateNumberOfMessagesNotVisible

ApproximateNumberOfMessagesVisible

NumberOfEmptyReceives

NumberOfMessagesDeleted

NumberOfMessagesReceived

NumberOfMessagesSent

# Amazon Relational Database Service（RDS）
<a name="appinsights-metrics-rds"></a>

CloudWatch Application Insights 支持以下指标：

**Topics**
+ [RDS 数据库实例](#appinsights-metrics-rds-instances)
+ [RDS 数据库集群](#appinsights-metrics-rds-clusters)

## RDS 数据库实例
<a name="appinsights-metrics-rds-instances"></a>

BurstBalance

CPUCreditBalance

CPUUtilization

DatabaseConnections

DiskQueueDepth

FailedSQLServerAgentJobsCount

FreeStorageSpace

FreeableMemory

NetworkReceiveThroughput

NetworkTransmitThroughput

读取 IOPS

ReadLatency

ReadThroughput

写入 IOPS

WriteLatency

写入吞吐量

## RDS 数据库集群
<a name="appinsights-metrics-rds-clusters"></a>

ActiveTransactions

AuroraBinlogReplicaLag

AuroraReplicaLag

BackupRetentionPeriodStorageUsed

BinLogDiskUsage

BlockedTransactions

BufferCacheHitRatio

CPUUtilization

CommitLatency

CommitThroughput

DDLLatency

DDLThroughput

DMLLatency

DMLThroughput

DatabaseConnections

死锁数

DeleteLatency

DeleteThroughput

EngineUptime

FreeLocalStorage

FreeableMemory

InsertLatency

InsertThroughput

LoginFailures

NetworkReceiveThroughput

NetworkThroughput

NetworkTransmitThroughput

查询

ResultSetCacheHitRatio

SelectLatency

SelectThroughput

SnapshotStorageUsed

TotalBackupStorageBilled

UpdateLatency

UpdateThroughput

VolumeBytesUsed

VolumeReadIOPs

VolumeWriteIOPs

# AWS Lambda 函数
<a name="appinsights-metrics-lambda"></a>

CloudWatch Application Insights 支持以下指标：

错误

DeadLetterErrors

Duration

节流

IteratorAge

ProvisionedConcurrencySpilloverInvocations

# Amazon DynamoDB 表
<a name="appinsights-metrics-dyanamodb"></a>

CloudWatch Application Insights 支持以下指标：

SystemErrors

UserErrors

已使用读取容量单位

已使用写入容量单位

ReadThrottleEvents

WriteThrottleEvents

TimeToLiveDeletedItemCount

ConditionalCheckFailedRequests

TransactionConflict

ReturnedRecordsCount

PendingReplicationCount

ReplicationLatency

# Amazon S3 存储桶
<a name="appinsights-metrics-s3"></a>

CloudWatch Application Insights 支持以下指标：

ReplicationLatency

BytesPendingReplication

OperationsPendingReplication

4xxErrors

5xxErrors

AllRequests

GetRequests

PutRequests

DeleteRequests

HeadRequests

PostRequests

SelectRequests

ListRequests

SelectScannedBytes

SelectReturnedBytes

FirstByteLatency

TotalRequestLatency

BytesDownloaded

BytesUploaded

# AWS Step Functions
<a name="appinsights-metrics-step-functions"></a>

CloudWatch Application Insights 支持以下指标：

**Topics**
+ [Execution-level](#appinsights-metrics-step-functions-execution)
+ [活动](#appinsights-metrics-step-functions-activity)
+ [Lambda 函数](#appinsights-metrics-step-functions-lambda)
+ [服务集成](#appinsights-metrics-step-functions-service-integration)
+ [Step Functions API](#appinsights-metrics-step-functions-api)

## Execution-level
<a name="appinsights-metrics-step-functions-execution"></a>

ExecutionTime

ExecutionThrottled

ExecutionsFailed

ExecutionsTimedOut

ExecutionsAborted

ExecutionsSucceeded

ExecutionsStarted

## 活动
<a name="appinsights-metrics-step-functions-activity"></a>

ActivityRunTime

ActivityScheduleTime

ActivityTime

ActivitiesFailed

ActivitiesHeartbeatTimedOut

ActivitiesTimedOut

ActivitiesScheduled

ActivitiesSucceeded

ActivitiesStarted

## Lambda 函数
<a name="appinsights-metrics-step-functions-lambda"></a>

LambdaFunctionRunTime

LambdaFunctionScheduleTime

LambdaFunctionTime

LambdaFunctionsFailed

LambdaFunctionsTimedOut

LambdaFunctionsScheduled

LambdaFunctionsSucceeded

LambdaFunctionsStarted

## 服务集成
<a name="appinsights-metrics-step-functions-service-integration"></a>

ServiceIntegrationRunTime

ServiceIntegrationScheduleTime

ServiceIntegrationTime

ServiceIntegrationsFailed

ServiceIntegrationsTimedOut

ServiceIntegrationsScheduled

ServiceIntegrationsSucceeded

ServiceIntegrationsStarted

## Step Functions API
<a name="appinsights-metrics-step-functions-api"></a>

ThrottledEvents

ProvisionedBucketSize

ProvisionedRefillRate

ConsumedCapacity

# API Gateway REST API 阶段
<a name="appinsights-metrics-api-gateway"></a>

CloudWatch Application Insights 支持以下指标：

4XXError

5XXError

IntegrationLatency

延迟

CacheHitCount

CacheMissCount

# SAP HANA
<a name="appinsights-metrics-sap-hana"></a>

**注意**  
CloudWatch Application Insights 仅支持单个 SID HANA 环境。如果连接了多个 HANA SID，则只会为第一个检测到的 SID 设置监控。

CloudWatch Application Insights 支持以下指标：

hanadb\$1every\$1service\$1started\$1status

hanadb\$1daemon\$1service\$1started\$1status

hanadb\$1preprocessor\$1service\$1started\$1status

hanadb\$1webdispatcher\$1service\$1started\$1status

hanadb\$1compileserver\$1service\$1started\$1status

hanadb\$1nameserver\$1service\$1started\$1status

hanadb\$1server\$1startup\$1time\$1variations\$1seconds

hanadb\$1level\$15\$1alerts\$1count

hanadb\$1level\$14\$1alerts\$1count

hanadb\$1out\$1of\$1memory\$1events\$1count

hanadb\$1max\$1trigger\$1read\$1ratio\$1percent

hanadb\$1max\$1trigger\$1write \$1rate\$1ratio\$1%

hanadb\$1log\$1switch\$1wait\$1ratio\$1percent

hanadb\$1log\$1switch\$1race\$1ratio\$1percent

hanadb\$1time\$1since\$1last\$1savepoint\$1seconds

hanadb\$1disk\$1usage\$1highlevel\$1percent

hanadb\$1max\$1converter\$1page\$1number\$1count

hanadb\$1long\$1running\$1savepoints\$1count

hanadb\$1failed\$1io\$1reads\$1count

hanadb\$1failed\$1io\$1writes\$1count

hanadb\$1disk\$1data\$1unused\$1percent

hanadb\$1current\$1allocation\$1limit\$1used\$1percent

hanadb\$1table\$1allocation\$1limit\$1used\$1percent

hanadb\$1host\$1total\$1physical\$1memory\$1mb

hanadb\$1host\$1physical\$1memory\$1used\$1mb

hanadb\$1host\$1physical\$1memory\$1free\$1mb

hanadb\$1swap\$1memory\$1free\$1mb

hanadb\$1swap\$1memory\$1used\$1mb

hanadb\$1host\$1allocation\$1limit\$1mb

hanadb\$1host\$1total\$1memory\$1used\$1mb

 hanadb\$1host\$1total\$1peak\$1memory\$1used\$1mb

hanadb\$1host\$1total\$1allocation\$1limit\$1mb

hanadb\$1host\$1code\$1size\$1mb

hanadb\$1host\$1shared\$1memory\$1allocation\$1mb

hanadb\$1cpu\$1usage\$1percent

hanadb\$1cpu\$1user\$1percent

hanadb\$1cpu\$1system\$1percent

hanadb\$1cpu\$1waitio\$1percent

hanadb\$1cpu\$1busy\$1percent

hanadb\$1cpu\$1idle\$1percent

hanadb\$1long\$1delta\$1merge\$1count

hanadb\$1unsuccessful\$1delta\$1merge\$1count

hanadb\$1successful\$1delta\$1merge\$1count

hanadb\$1row\$1store\$1allocated\$1size\$1mb

hanadb\$1row\$1store\$1free\$1size\$1mb

hanadb\$1row\$1store\$1used\$1size\$1mb

hanadb\$1temporary\$1tables\$1count

hanadb\$1large\$1non\$1compressed\$1tables\$1count

hanadb\$1total\$1non\$1compressed\$1tables\$1count

hanadb\$1longest\$1running\$1job\$1seconds

hanadb\$1average\$1commit\$1time\$1milliseconds

hanadb\$1suspended\$1sql\$1statements\$1count

hanadb\$1plan\$1cache\$1hit\$1ratio\$1percent

hanadb\$1plan\$1cache\$1lookup\$1count

hanadb\$1plan\$1cache\$1hit\$1count

hanadb\$1plan\$1cache\$1total\$1execution\$1microseconds

hanadb\$1plan\$1cache\$1cursor\$1duration\$1microseconds

hanadb\$1plan\$1cache\$1preparation\$1microseconds

hanadb\$1plan\$1cache\$1evicted\$1count

hanadb\$1plan\$1cache\$1evicted\$1microseconds

hanadb\$1plan\$1cache\$1evicted\$1preparation\$1count

hanadb\$1plan\$1cache\$1evicted\$1execution\$1count

hanadb\$1plan\$1cache\$1evicted\$1preparation\$1microseconds

hanadb\$1plan\$1cache\$1evicted\$1cursor\$1duration\$1microseconds

hanadb\$1plan\$1cache\$1evicted\$1total\$1execution\$1microseconds

hanadb\$1plan\$1cache\$1evicted\$1plan\$1size\$1mb

hanadb\$1plan\$1cache\$1count

hanadb\$1plan\$1cache\$1preparation\$1count

hanadb\$1plan\$1cache\$1execution\$1count

hanadb\$1network\$1collision\$1rate

hanadb\$1network\$1receive\$1rate

hanadb\$1network\$1transmit\$1rate

hanadb\$1network\$1packet\$1receive\$1rate

hanadb\$1network\$1packet\$1transmit\$1rate

hanadb\$1network\$1transmit\$1error\$1rate

hanadb\$1network\$1receive\$1error\$1rate

hanadb\$1time\$1until\$1license\$1expires\$1days

hanadb\$1is\$1license\$1valid\$1status

hanadb\$1local\$1running\$1connections\$1count

hanadb\$1local\$1idle\$1connections\$1count

hanadb\$1remote\$1running\$1connections\$1count

hanadb\$1remote\$1idle\$1connections\$1count

hanadb\$1last\$1full\$1data\$1backup\$1age\$1days

hanadb\$1last\$1data\$1backup\$1age\$1days

hanadb\$1last\$1log\$1backup\$1age\$1hours

hanadb\$1failed\$1data\$1backup\$1past\$17\$1days\$1count

hanadb\$1failed\$1log\$1backup\$1past\$17\$1days\$1count

hanadb\$1oldest\$1backup\$1in\$1catalog\$1age\$1days

hanadb\$1backup\$1catalog\$1size\$1mb

hanadb\$1hsr\$1replication\$1status

hanadb\$1hsr\$1log\$1shipping\$1delay\$1seconds

hanadb\$1hsr\$1secondary\$1failover\$1count

hanadb\$1hsr\$1secondary\$1reconnect\$1count

hanadb\$1hsr\$1async\$1buffer\$1used\$1mb

hanadb\$1hsr\$1secondary\$1active\$1status

hanadb\$1handle\$1count

hanadb\$1ping\$1time\$1milliseconds

hanadb\$1connection\$1count

hanadb\$1internal\$1connection\$1count

hanadb\$1external\$1connection\$1count

hanadb\$1idle\$1connection\$1count

hanadb\$1transaction\$1count

hanadb\$1internal\$1transaction\$1count

hanadb\$1external\$1transaction\$1count

hanadb\$1user\$1transaction\$1count

hanadb\$1blocked\$1transaction\$1count

hanadb\$1statement\$1count

hanadb\$1active\$1commit\$1id\$1range\$1count

hanadb\$1mvcc\$1version\$1count

hanadb\$1pending\$1session\$1count

hanadb\$1record\$1lock\$1count

hanadb\$1read\$1count

hanadb\$1write\$1count

hanadb\$1merge\$1count

hanadb\$1unload\$1count

hanadb\$1active\$1thread\$1count

hanadb\$1waiting\$1thread\$1count

hanadb\$1total\$1thread\$1count

hanadb\$1active\$1sql\$1executor\$1count

hanadb\$1waiting\$1sql\$1executor\$1count

hanadb\$1total\$1sql\$1executor\$1count

hanadb\$1data\$1write\$1size\$1mb

hanadb\$1data\$1write\$1time\$1milliseconds

hanadb\$1log\$1write\$1size\$1mb

hanadb\$1log\$1write\$1time\$1milliseconds

hanadb\$1data\$1read\$1size\$1mb

hanadb\$1data\$1read\$1time\$1milliseconds

hanadb\$1log\$1read\$1size\$1mb

hanadb\$1log\$1read\$1time\$1milliseconds

hanadb\$1data\$1backup\$1write\$1size\$1mb

hanadb\$1data\$1backup\$1write\$1time\$1milliseconds

hanadb\$1log\$1backup\$1write\$1size\$1mb

hanadb\$1log\$1backup\$1write\$1time\$1milliseconds

hanadb\$1mutex\$1colision\$1count

hanadb\$1read\$1write\$1lock\$1collision\$1count

hanadb\$1admission\$1control\$1admit\$1count

hanadb\$1admission\$1control\$1reject\$1count

hanadb\$1admission\$1control\$1queue\$1size\$1mb

hanadb\$1admission\$1control\$1wait\$1time\$1milliseconds

# SAP ASE
<a name="appinsights-metrics-sap-ase"></a>

CloudWatch Application Insights 支持以下指标：

asedb\$1database\$1availability

asedb\$1trunc\$1log\$1on\$1chkpt\$1enabled

asedb\$1last\$1db\$1backup\$1age\$1in\$1days

asedb\$1last\$1transaction\$1log\$1backup\$1age\$1in\$1hours

asedb\$1suspected\$1database

asedb\$1db\$1space\$1usage\$1percent

asedb\$1db\$1log\$1space\$1usage\$1usage\$1percent

asedb\$1locked\$1login

asedb\$1has\$1mixed\$1log\$1and\$1data

asedb\$1runtime\$1for\$1open\$1transactime

asedb\$1data\$1cache\$1hit\$1ratio

asedb\$1data\$1cache\$1usage\$1usage

asedb\$1sql\$1cache\$1hit\$1ratio

asedb\$1cache\$1usage

asedb\$1run\$1queue\$1length

asedb\$1number\$1of\$1rollbacks

asedb\$1of\$1commit\$1numbits

asedb\$1number\$1of\$1transactions

asedb\$1outstanding\$1disk\$1io

asedb\$1percent\$1io\$1busy

asedb\$1percent\$1system\$1busy

asedb\$1percent\$1locks\$1active

asedb\$1scheduled\$1jobs\$1failed\$1percent

asedb\$1user\$1connections\$1pection

asedb\$1query\$1logical\$1reads

asedb\$1query\$1physical\$1reads

asedb\$1query\$1cpu\$1time

asedb\$1query\$1memory\$1usage

# Amazon EC2 上的 SAP ASE 高可用性
<a name="appinsights-metrics-sap-ase-ha"></a>

CloudWatch Application Insights 支持以下指标：

asedb\$1ha\$1replication\$1state

asedb\$1ha\$1replication\$1mode

asedb\$1ha\$1replication\$1latency\$1in\$1minus

# SAP NetWeaver
<a name="appinsights-metrics-sap-netweaver"></a>

CloudWatch Application Insights 支持以下指标：


| 指标 | 说明 | 
| --- | --- | 
| sap\$1alerts\$1ResponseTime |  来自 CCMS (RZ20)>R3Services>Dialog>ResponseTime 的 SAP 响应时间警报。  | 
|  sap\$1alerts\$1ResponseTimeDialog  | 来自 CCMS (RZ20)>R3Services>Dialog>ResponseTimeDialog 的 SAP 响应时间对话警报。 | 
| sap\$1alerts\$1ResponseTimeDialogRFC | 来自 CCMS (RZ20)>R3Services>Dialog>ResponseTimeDialogRFC 的 SAP 响应时间警报。 | 
| sap\$1alerts\$1DBRequestTime | 来自 CCMS (RZ20)>R3Services>Dialog>DBRequestTime 的 SAP 响应时间警报。 | 
| sap\$1alerts\$1FrontendResponseTime | 来自 CCMS (RZ20)>R3Services>Dialog>FrontEndResponseTime 的 SAP 响应时间警报。 | 
| sap\$1alerts\$1Database  | SAP 系统记录了数据库相关错误。来自 SM21 或 CCMS (RZ20)>R3Syslog>Database 的警报。 | 
| sap\$1alerts\$1QueueTime  | 来自 CCMS (RZ20)>R3Services>Dialog>QueueTime 的 SAP 队列时间警报。 | 
| sap\$1alerts\$1AbortedJobs | SAP 系统中的后台作业失败。来自 (RZ20)>R3Services>Background>AbortedJobs 的警报。 | 
| sap\$1alerts\$1BasisSystem | SAP 系统记录了系统级错误。来自 SM21 或 CCMS (RZ20)>R3Syslog>BasisSystem 的警报。 | 
| sap\$1alerts\$1Security  | SAP 系统记录了与安全相关的消息。来自 SM21 或 CCMS (RZ20)>R3Syslog>Security 的警报。 | 
| sap\$1alerts\$1System  | SAP 系统记录了与安全或审核相关的消息。来自 SM21 或 CCMS (RZ20)>Security>System 的警报。 | 
| sap\$1alerts\$1LongRunners  | 您的 SAP 系统中有长时间运行的程序。来自 CCMS (RZ20)>R3Services>Dialog>LongRunners 的警报。 | 
| sap\$1alerts\$1SqlError  | 有 SAP 数据库客户端层错误日志。来自 CCMS (RZ20)>DatabaseClient>AbapSql>SqlError 的警报。 | 
| sap\$1alerts\$1State  | 来自 CCMS (RZ20)>OS Collector>State 的状态警报。 | 
| sap\$1alerts\$1Shortdumps  | 来自 ST22 和 CCMS (RZ20)>R3Abap>Shortdumps 的 Shortdumps 警报。 | 
| sap\$1alerts\$1Availability  | 来自 SM21、SM50、SM51、SM66 和 CCMS (RZ20)>InstanceAsTask>Availability 的 SAP 应用程序服务器实例可用性警报。 | 
| sap\$1dispatcher\$1queue\$1high | SAPControl Web 服务函数 GetQueueStatistic 提供调度程序队列的高计数。 | 
| sap\$1dispatcher\$1queue\$1max | SAPControl Web 服务函数 GetQueueStatistic 提供调度程序队列的最大计数。 | 
| sap\$1dispatcher\$1queue\$1now | SAPControl Web 服务函数 GetQueueStatistic 提供调度程序队列的当前计数。 | 
| sap\$1dispatcher\$1queue\$1reads | SAPControl Web 服务函数 GetQueueStatistic 提供调度程序队列的读取计数。 | 
| sap\$1dispatcher\$1queue\$1writes | SAPControl Web 服务函数 GetQueueStatistic 提供调度程序队列的写入计数。 | 
| sap\$1enqueue\$1server\$1arguments\$1high  | SAPControl Web 服务函数 EnqGetStatistic 提供高入队参数。 | 
| sap\$1enqueue\$1server\$1arguments\$1max  | SAPControl Web 服务函数 EnqGetStatistic 提供最大入队参数。 | 
| sap\$1enqueue\$1server\$1arguments\$1now | SAPControl Web 服务函数 EnqGetStatistic 提供当前入队参数。 | 
| sap\$1enqueue\$1server\$1arguments\$1state | SAPControl Web 服务函数 EnqGetStatistic 提供入队参数状态。 | 
| sap\$1enqueue\$1server\$1backup\$1requests | SAPControl Web 服务函数 EnqGetStatistic 提供入队备份请求。 | 
| sap\$1enqueue\$1server\$1cleanup\$1requests | SAPControl Web 服务函数 EnqGetStatistic 提供入队清理请求。 | 
| sap\$1enqueue\$1server\$1dequeue\$1all\$1requests | SAPControl Web 服务函数 EnqGetStatistic 提供全部出队请求。 | 
| sap\$1enqueue\$1server\$1dequeue\$1errors | SAPControl Web 服务函数 EnqGetStatistic 提供出队错误。 | 
| sap\$1enqueue\$1server\$1dequeue\$1requests  | SAPControl Web 服务函数 EnqGetStatistic 提供出队请求。 | 
| sap\$1enqueue\$1server\$1enqueue\$1errors | SAPControl Web 服务函数 EnqGetStatistic 提供入队错误。 | 
| sap\$1enqueue\$1server\$1enqueue\$1rejects  | SAPControl Web 服务函数 EnqGetStatistic 提供入队拒绝。 | 
| sap\$1enqueue\$1server\$1enqueue\$1requests | SAPControl Web 服务函数 EnqGetStatistic 提供入队请求。 | 
| sap\$1enqueue\$1server\$1lock\$1time | SAPControl Web 服务函数 EnqGetStatistic 提供入队锁定时间。 | 
| sap\$1enqueue\$1server\$1lock\$1wait\$1time | SAPControl Web 服务函数 EnqGetStatistic 提供入队锁定等待时间。 | 
| sap\$1enqueue\$1server\$1locks\$1high | SAPControl Web 服务函数 EnqGetStatistic 提供入队锁定的高计数。 | 
| sap\$1enqueue\$1server\$1locks\$1max | SAPControl Web 服务函数 EnqGetStatistic 提供入队锁定的最大计数。 | 
| sap\$1enqueue\$1server\$1locks\$1now | SAPControl Web 服务函数 EnqGetStatistic 提供入队锁定的当前计数。 | 
| sap\$1enqueue\$1server\$1locks\$1state | SAPControl Web 服务函数 EnqGetStatistic 提供入队锁定状态。 | 
| sap\$1enqueue\$1server\$1owner\$1high | SAPControl Web 服务函数 EnqGetStatistic 提供入队所有者的高计数。 | 
| sap\$1enqueue\$1server\$1owner\$1max | SAPControl Web 服务函数 EnqGetStatistic 提供入队所有者的最大计数。 | 
| sap\$1enqueue\$1server\$1owner\$1now | SAPControl Web 服务函数 EnqGetStatistic 提供入队所有者的当前计数。 | 
| sap\$1enqueue\$1server\$1owner\$1state | SAPControl Web 服务函数 EnqGetStatistic 提供入队所有者状态。 | 
| sap\$1enqueue\$1server\$1replication\$1state  | SAPControl Web 服务函数 EnqGetStatistic 提供入队复制状态。 | 
| sap\$1enqueue\$1server\$1reporting\$1requests | SAPControl Web 服务函数 EnqGetStatistic 提供报告请求状态。 | 
| sap\$1enqueue\$1server\$1server\$1time | SAPControl Web 服务函数 EnqGetStatistic 提供入队服务器时间。 | 
| sap\$1HA\$1check\$1failover\$1config\$1state | SAPControl Web 服务函数 HACheckFailoverConfig 提供 SAP 高可用性状态。 | 
| sap\$1HA\$1get\$1failover\$1config\$1HAActive | SAPControl Web 服务函数 HAGetFailoverConfig 提供 SAP 高可用性集群配置和状态。 | 
| sap\$1start\$1service\$1processes  | SAPControl Web 服务函数 GetProcessList 提供 disp\$1work、IGS、gwrd、icman、消息服务器和入队服务器进程状态。 | 

# HA 集群
<a name="appinsights-metrics-ha-cluster"></a>

CloudWatch Application Insights 支持以下指标：

ha\$1cluster\$1pacemaker\$1stonith\$1enabled 

ha\$1cluster\$1corosync\$1quorate

hanadb\$1webdispatcher\$1service\$1started\$1status

ha\$1cluster\$1pacemaker\$1nodes 

ha\$1cluster\$1corosync\$1ring\$1errors

ha\$1cluster\$1pacemaker\$1fail\$1count 

# Java
<a name="appinsights-metrics-java"></a>

CloudWatch Application Insights 支持以下指标：

java\$1lang\$1memory\$1heapmemoryusage\$1used

java\$1lang\$1memory\$1heapmemoryusage\$1committed

java\$1lang\$1operatingsystem\$1openfiledescriptorcount

java\$1lang\$1operatingsystem\$1maxfiledescriptorcount

java\$1lang\$1operatingsystem\$1freephysicalmemorysize

java\$1lang\$1operatingsystem\$1freeswapspacesize

java\$1lang\$1threading\$1threadcount

java\$1lang\$1threading\$1daemonthreadcount

java\$1lang\$1classloading\$1loadedclasscount

java\$1lang\$1garbagecollector\$1collectiontime\$1copy

java\$1lang\$1garbagecollector\$1collectiontime\$1ps\$1scavenge

java\$1lang\$1garbagecollector\$1collectiontime\$1parnew

java\$1lang\$1garbagecollector\$1collectiontime\$1marksweepcompact

java\$1lang\$1garbagecollector\$1collectiontime\$1ps\$1marksweep

java\$1lang\$1garbagecollector\$1collectiontime\$1concurrentmarksweep

java\$1lang\$1garbagecollector\$1collectiontime\$1g1\$1young\$1generation

java\$1lang\$1garbagecollector\$1collectiontime\$1g1\$1old\$1generation

java\$1lang\$1garbagecollector\$1collectiontime\$1g1\$1mixed\$1generation

java\$1lang\$1operatingsystem\$1committedvirtualmemorysize

# Amazon Elastic Container Service（Amazon ECS）
<a name="appinsights-metrics-ecs"></a>

CloudWatch Application Insights 支持以下指标：

**Topics**
+ [CloudWatch 内置指标](#appinsights-metrics-ecs-built-in-metrics)
+ [Container Insights 指标](#appinsights-metrics-ecs-container-insights-metrics)
+ [Container Insights Prometheus 指标](#appinsights-metrics-ecs-container-insights-prometheus)

## CloudWatch 内置指标
<a name="appinsights-metrics-ecs-built-in-metrics"></a>

CPUReservation

CPUUtilization

MemoryReservation

MemoryUtilization

GPUReservation

## Container Insights 指标
<a name="appinsights-metrics-ecs-container-insights-metrics"></a>

ContainerInstanceCount

CpuUtilized

CpuReserved

DeploymentCount

DesiredTaskCount

MemoryUtilized

MemoryReserved

NetworkRxBytes

NetworkTxBytes

PendingTaskCount

RunningTaskCount

ServiceCount

StorageReadBytes

StorageWriteBytes

TaskCount

TaskSetCount

instance\$1cpu\$1limit

instance\$1cpu\$1reserved\$1capacity

instance\$1cpu\$1usage\$1total

instance\$1cpu\$1utilization

instance\$1filesystem\$1utilization

instance\$1memory\$1limit

instance\$1memory\$1reserved\$1capacity

instance\$1memory\$1utilization

instance\$1memory\$1working\$1set

instance\$1network\$1total\$1bytes

instance\$1number\$1of\$1running\$1tasks

## Container Insights Prometheus 指标
<a name="appinsights-metrics-ecs-container-insights-prometheus"></a>

**Java JMX 指标**

java\$1lang\$1memory\$1heapmemoryusage\$1used

java\$1lang\$1memory\$1heapmemoryusage\$1committed

java\$1lang\$1operatingsystem\$1openfiledescriptorcount

java\$1lang\$1operatingsystem\$1maxfiledescriptorcount

java\$1lang\$1operatingsystem\$1freephysicalmemorysize

java\$1lang\$1operatingsystem\$1freeswapspacesize

java\$1lang\$1threading\$1threadcount

java\$1lang\$1classloading\$1loadedclasscount

java\$1lang\$1threading\$1daemonthreadcount

java\$1lang\$1garbagecollector\$1collectiontime\$1copy

java\$1lang\$1garbagecollector\$1collectiontime\$1ps\$1scavenge

java\$1lang\$1garbagecollector\$1collectiontime\$1parnew

java\$1lang\$1garbagecollector\$1collectiontime\$1marksweepcompact

java\$1lang\$1garbagecollector\$1collectiontime\$1ps\$1marksweep

java\$1lang\$1garbagecollector\$1collectiontime\$1concurrentmarksweep

java\$1lang\$1garbagecollector\$1collectiontime\$1g1\$1young\$1generation

java\$1lang\$1garbagecollector\$1collectiontime\$1g1\$1old\$1generation

java\$1lang\$1garbagecollector\$1collectiontime\$1g1\$1mixed\$1generation

java\$1lang\$1operatingsystem\$1committedvirtualmemorysize

# AWS 上的 Kubernetes
<a name="appinsights-metrics-kubernetes"></a>

CloudWatch Application Insights 支持以下指标：

**Topics**
+ [Container Insights 指标](#appinsights-metrics-kubernetes-container-insights-metrics)
+ [Container Insights Prometheus 指标](#appinsights-metrics-kubernetes-container-insights-prometheus)

## Container Insights 指标
<a name="appinsights-metrics-kubernetes-container-insights-metrics"></a>

cluster\$1failed\$1node\$1count

cluster\$1node\$1count

namespace\$1number\$1of\$1running\$1pods

node\$1cpu\$1limit

node\$1cpu\$1reserved\$1capacity

node\$1cpu\$1usage\$1total

node\$1cpu\$1utilization

node\$1filesystem\$1utilization

node\$1memory\$1limit

node\$1memory\$1reserved\$1capacity

node\$1memory\$1utilization

node\$1memory\$1working\$1set

node\$1network\$1total\$1bytes

node\$1number\$1of\$1running\$1containers

node\$1number\$1of\$1running\$1pods

pod\$1cpu\$1reserved\$1capacity

pod\$1cpu\$1utilization

pod\$1cpu\$1utilization\$1over\$1pod\$1limit

pod\$1memory\$1reserved\$1capacity

pod\$1memory\$1utilization

pod\$1memory\$1utilization\$1over\$1pod\$1limit

pod\$1network\$1rx\$1bytes

pod\$1network\$1tx\$1bytes

service\$1number\$1of\$1running\$1pods

## Container Insights Prometheus 指标
<a name="appinsights-metrics-kubernetes-container-insights-prometheus"></a>

**Java JMX 指标**

java\$1lang\$1memory\$1heapmemoryusage\$1used

java\$1lang\$1memory\$1heapmemoryusage\$1committed

java\$1lang\$1operatingsystem\$1openfiledescriptorcount

java\$1lang\$1operatingsystem\$1maxfiledescriptorcount

java\$1lang\$1operatingsystem\$1freephysicalmemorysize

java\$1lang\$1operatingsystem\$1freeswapspacesize

java\$1lang\$1threading\$1threadcount

java\$1lang\$1classloading\$1loadedclasscount

java\$1lang\$1threading\$1daemonthreadcount

java\$1lang\$1garbagecollector\$1collectiontime\$1copy

java\$1lang\$1garbagecollector\$1collectiontime\$1ps\$1scavenge

java\$1lang\$1garbagecollector\$1collectiontime\$1parnew

java\$1lang\$1garbagecollector\$1collectiontime\$1marksweepcompact

java\$1lang\$1garbagecollector\$1collectiontime\$1ps\$1marksweep

java\$1lang\$1garbagecollector\$1collectiontime\$1concurrentmarksweep

java\$1lang\$1garbagecollector\$1collectiontime\$1g1\$1young\$1generation

java\$1lang\$1garbagecollector\$1collectiontime\$1g1\$1old\$1generation

java\$1lang\$1garbagecollector\$1collectiontime\$1g1\$1mixed\$1generation

java\$1lang\$1operatingsystem\$1committedvirtualmemorysize

# Amazon FSx
<a name="appinsights-metrics-fsx"></a>

CloudWatch Application Insights 支持以下指标：

DataReadBytes

DataWriteBytes

DataReadOperations

DataWriteOperations

MetadataOperations

FreeStorageCapacity

FreeDataStorageCapacity

LogicalDiskUsage

PhysicalDiskUsage

# Amazon VPC
<a name="appinsights-metrics-vpc"></a>

CloudWatch Application Insights 支持以下指标：

NetworkAddressUsage

NetworkAddressUsagePeered

VPCFirewallQueryVolume

# Amazon VPC NAT 网关
<a name="appinsights-metrics-nat-gateways"></a>

CloudWatch Application Insights 支持以下指标：

ErrorPortAllocation

IdleTimeoutCount

# Amazon Route 53 运行状况检查
<a name="appinsights-metrics-health-check"></a>

CloudWatch Application Insights 支持以下指标：

ChildHealthCheckHealthyCount

ConnectionTime

HealthCheckPercentageHealthy

HealthCheckStatus

SSLHandshakeTime 

TimeToFirstByte

# Amazon Route 53 托管区
<a name="appinsights-metrics-hosted-zone"></a>

CloudWatch Application Insights 支持以下指标：

DNSQueries

DNSSECInternalFailure

DNSSECKeySigningKeysNeedingAction

DNSSECKeySigningKeyMaxNeedingActionAge

DNSSECKeySigningKeyAge

# Amazon Route 53 Resolver 端点
<a name="appinsights-metrics-resolver-endpoint"></a>

CloudWatch Application Insights 支持以下指标：

EndpointHealthyENICount

EndpointUnHealthyENICount

InboundQueryVolume

OutboundQueryVolume

OutboundQueryAggregateVolume

# AWS Network Firewall 规则组
<a name="appinsights-metrics-firewall-rule-group"></a>

CloudWatch Application Insights 支持以下指标：

FirewallRuleGroupQueryVolume

# AWS Network Firewall 规则组关联
<a name="appinsights-metrics-firewall-rule-group-assoc"></a>

CloudWatch Application Insights 支持以下指标：

FirewallRuleGroupVpcQueryVolume

# 具有数据点要求的指标
<a name="appinsights-metrics-datapoint-requirements"></a>

对于没有触发警报的明显默认阈值的指标，Application Insights 等到指标具有足够的数据点以预测触发警报的合理阈值。CloudWatch Application Insights 在告警创建之前检查的指标数据点要求如下：
+ 指标从过去 15 天到过去 2 天期间至少具有 100 个数据点。
+ 指标在最后一天至少具有 100 个数据点。

以下指标遵循这些数据点要求。请注意，CloudWatch 代理指标最多需要一小时才能创建警报。

**Topics**
+ [AWS/ApplicationELB](#appinsights-metrics-datapoint-requirements-app-elb)
+ [AWS/AutoScaling](#appinsights-metrics-datapoint-requirements-autoscaling)
+ [AWS/EC2](#appinsights-metrics-datapoint-requirements-ec2)
+ [Elastic Block Store (EBS)](#appinsights-metrics-datapoint-requirements-ebs)
+ [AWS/ELB](#appinsights-metrics-datapoint-requirements-elb)
+ [AWS/RDS](#appinsights-metrics-datapoint-requirements-rds)
+ [AWS/Lambda](#appinsights-metrics-datapoint-requirements-lambda)
+ [AWS/SQS](#appinsights-metrics-datapoint-requirements-sqs)
+ [AWS/CWAgent](#appinsights-metrics-datapoint-requirements-cwagent)
+ [AWS/DynamoDB](#appinsights-metrics-datapoint-requirements-dynamo)
+ [AWS/S3](#appinsights-metrics-datapoint-requirements-s3)
+ [AWS/States](#appinsights-metrics-datapoint-requirements-states)
+ [AWS/ApiGateway](#appinsights-metrics-datapoint-requirements-api-gateway)
+ [AWS/SNS](#appinsights-metrics-datapoint-requirements-sns)

## AWS/ApplicationELB
<a name="appinsights-metrics-datapoint-requirements-app-elb"></a>

ActiveConnectionCount

ConsumedLCUs

HTTPCode\$1ELB\$14XX\$1Count

HTTPCode\$1Target\$12XX\$1Count

HTTPCode\$1Target\$13XX\$1Count

HTTPCode\$1Target\$14XX\$1Count

HTTPCode\$1Target\$15XX\$1Count

NewConnectionCount

ProcessedBytes

TargetResponseTime

UnHealthyHostCount

## AWS/AutoScaling
<a name="appinsights-metrics-datapoint-requirements-autoscaling"></a>

GroupDesiredCapacity

GroupInServiceInstances

GroupMaxSize

GroupMinSize

GroupPendingInstances

GroupStandbyInstances

GroupTerminatingInstances

GroupTotalInstances

## AWS/EC2
<a name="appinsights-metrics-datapoint-requirements-ec2"></a>

CPUCreditBalance

CPUCreditUsage

CPUSurplusCreditBalance

CPUSurplusCreditsCharged

CPUUtilization

磁盘读取字节数

磁盘读取操作

磁盘写入字节数

磁盘写入操作

EBSByteBalance%

EBSIOBalance%

EBSReadBytes

EBSReadOps

EBSWriteBytes

EBSWriteOps

NetworkIn

网络输出

NetworkPacketsIn

NetworkPacketsOut

## Elastic Block Store (EBS)
<a name="appinsights-metrics-datapoint-requirements-ebs"></a>

VolumeReadBytes 

VolumeWriteBytes 

VolumeReadOps

VolumeWriteOps

VolumeTotalReadTime 

VolumeTotalWriteTime 

VolumeIdleTime

VolumeQueueLength

VolumeThroughputPercentage

VolumeConsumedReadWriteOps

BurstBalance

## AWS/ELB
<a name="appinsights-metrics-datapoint-requirements-elb"></a>

EstimatedALBActiveConnectionCount

EstimatedALBConsumedLCUs

EstimatedALBNewConnectionCount

EstimatedProcessedBytes

HTTPCode\$1Backend\$14XX

HTTPCode\$1Backend\$15XX

HealthyHostCount

延迟

RequestCount

SurgeQueueLength

UnHealthyHostCount

## AWS/RDS
<a name="appinsights-metrics-datapoint-requirements-rds"></a>

ActiveTransactions

AuroraBinlogReplicaLag

AuroraReplicaLag

BackupRetentionPeriodStorageUsed

BinLogDiskUsage

BlockedTransactions

CPUCreditBalance

CommitLatency

CommitThroughput

DDLLatency

DDLThroughput

DMLLatency

DMLThroughput

DatabaseConnections

死锁数

DeleteLatency

DeleteThroughput

DiskQueueDepth

EngineUptime

FreeLocalStorage

FreeStorageSpace

FreeableMemory

InsertLatency

InsertThroughput

LoginFailures

NetworkReceiveThroughput

NetworkThroughput

NetworkTransmitThroughput

查询

读取 IOPS

ReadThroughput

SelectLatency

SelectThroughput

SnapshotStorageUsed

TotalBackupStorageBilled

UpdateLatency

UpdateThroughput

VolumeBytesUsed

VolumeReadIOPs

VolumeWriteIOPs

写入 IOPS

写入吞吐量

## AWS/Lambda
<a name="appinsights-metrics-datapoint-requirements-lambda"></a>

错误

DeadLetterErrors

Duration

节流

IteratorAge

ProvisionedConcurrencySpilloverInvocations

## AWS/SQS
<a name="appinsights-metrics-datapoint-requirements-sqs"></a>

ApproximateAgeOfOldestMessage

ApproximateNumberOfMessagesDelayed

ApproximateNumberOfMessagesNotVisible

ApproximateNumberOfMessagesVisible

NumberOfEmptyReceives

NumberOfMessagesDeleted

NumberOfMessagesReceived

NumberOfMessagesSent

## AWS/CWAgent
<a name="appinsights-metrics-datapoint-requirements-cwagent"></a>

LogicalDisk % Free Space

Memory % Committed Bytes In Use

Memory Available Mbytes

Network Interface Bytes Total/sec

Paging File % Usage

PhysicalDisk % Disk Time

PhysicalDisk Avg。Disk sec/Read

PhysicalDisk Avg。Disk sec/Write

PhysicalDisk Disk Read Bytes/sec

PhysicalDisk Disk Reads/sec

PhysicalDisk Disk Write Bytes/sec

PhysicalDisk Disk Writes/sec

Processor % Idle Time

Processor % Interrupt Time

Processor % Processor Time

Processor % User Time

SQLServer:Access Methods Forwarded Records/sec

SQLServer:Access Methods Page Splits/sec

SQLServer:Buffer Manager Buffer cache hit ratio

SQLServer:Buffer Manager Page life expectancy

SQLServer：接收的数据库副本文件字节数/秒

SQLServer：接收的数据库副本日志字节数/秒

SQLServer：保留数据库副本日志以供撤消

SQLServer：数据库副本日志发送队列

SQLServer：数据库副本镜像写事务数/秒

SQLServer：数据库副本恢复队列

SQLServer：剩余数据库副本重做字节数

SQLServer：数据库副本已重做的字节数/秒

SQLServer：需要撤消的数据库副本总日志

SQLServer：数据库副本事务延迟

SQLServer:General Statistics Processes blocked

SQLServer:SQL Statistics Batch Requests/sec

SQLServer:SQL Statistics SQL Compilations/sec

SQLServer:SQL Statistics SQL Re-Compilations/sec

System Processor Queue Length

TCPv4 Connections Established

TCPv6 Connections Established

## AWS/DynamoDB
<a name="appinsights-metrics-datapoint-requirements-dynamo"></a>

已使用读取容量单位

已使用写入容量单位

ReadThrottleEvents

WriteThrottleEvents

TimeToLiveDeletedItemCount

ConditionalCheckFailedRequests

TransactionConflict

ReturnedRecordsCount

PendingReplicationCount

ReplicationLatency

## AWS/S3
<a name="appinsights-metrics-datapoint-requirements-s3"></a>

ReplicationLatency

BytesPendingReplication

OperationsPendingReplication

4xxErrors

5xxErrors

AllRequests

GetRequests

PutRequests

DeleteRequests

HeadRequests

PostRequests

SelectRequests

ListRequests

SelectScannedBytes

SelectReturnedBytes

FirstByteLatency

TotalRequestLatency

BytesDownloaded

BytesUploaded

## AWS/States
<a name="appinsights-metrics-datapoint-requirements-states"></a>

ActivitiesScheduled

ActivitiesStarted

ActivitiesSucceeded

ActivityScheduleTime

ActivityRuntime

ActivityTime

LambdaFunctionsScheduled

LambdaFunctionsStarted

LambdaFunctionsSucceeded

LambdaFunctionScheduleTime

LambdaFunctionRuntime

LambdaFunctionTime

ServiceIntegrationsScheduled

ServiceIntegrationsStarted

ServiceIntegrationsSucceeded

ServiceIntegrationScheduleTime

ServiceIntegrationRuntime

ServiceIntegrationTime

ProvisionedRefillRate

ProvisionedBucketSize

ConsumedCapacity

ThrottledEvents

## AWS/ApiGateway
<a name="appinsights-metrics-datapoint-requirements-api-gateway"></a>

4XXError 

IntegrationLatency

延迟

DataProcessed

CacheHitCount

CacheMissCount

## AWS/SNS
<a name="appinsights-metrics-datapoint-requirements-sns"></a>

NumberOfNotificationsDelivered

NumberOfMessagesPublished

NumberOfNotificationsFailed

NumberOfNotificationsFilteredOut

NumberOfNotificationsFilteredOut-InvalidAttributes

NumberOfNotificationsFilteredOut-NoMessageAttributes

NumberOfNotificationsRedrivenToDlq

NumberOfNotificationsFailedToRedriveToDlq

SMSSuccessRate

# 推荐的指标
<a name="application-insights-recommended-metrics"></a>

下表列出了每种组件类型的建议指标。

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/application-insights-recommended-metrics.html)

下表列出了每种组件类型的建议流程和流程指标。CloudWatch Application Insights 不建议对不在实例上运行的流程进行流程监控。

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/monitoring/application-insights-recommended-metrics.html)

# 性能计数器指标
<a name="application-insights-performance-counter"></a>

仅当 Windows 实例上安装了相应的性能计数器集时，才建议对实例使用性能计数器指标。


| 性能计数器指标名称 | 性能计数器集名称 | 
| --- | --- | 
| .NET CLR Exceptions \$1 of Exceps Thrown | .NET CLR Exceptions | 
| .NET CLR Exceptions \$1 of Exceps Thrown/Sec  | .NET CLR Exceptions | 
| .NET CLR Exceptions \$1 of Filters/Sec  | .NET CLR Exceptions | 
| .NET CLR Exceptions \$1 of Finallys/Sec  | .NET CLR Exceptions | 
| .NET CLR Exceptions Throw to Catch Depth/Sec  | .NET CLR Exceptions | 
| .NET CLR Interop \$1 of CCWs  | .NET CLR Interop  | 
| .NET CLR Interop \$1 of Stubs  | .NET CLR Interop  | 
| .NET CLR Interop \$1 of TLB exports/Sec  | .NET CLR Interop  | 
| .NET CLR Interop \$1 of TLB imports/Sec  | .NET CLR Interop  | 
| .NET CLR Interop \$1 of Marshaling  | .NET CLR Interop  | 
| .NET CLR Jit % Time in Jit  | .NET CLR Jit  | 
| .NET CLR Jit Standard Jit Failures  | .NET CLR Jit  | 
| .NET CLR Loading % Time Loading  | .NET CLR Loading  | 
| .NET CLR Loading Rate of Load Failures  | .NET CLR Loading  | 
| .NET CLR LocksAndThreads Contention Rate/Sec  | .NET CLR LocksAndThreads  | 
| .NET CLR LocksAndThreads Queue Length/Sec  | .NET CLR LocksAndThreads  | 
| .NET CLR Memory \$1 Total Committed Bytes  | .NET CLR Memory | 
| .NET CLR Memory % Time in GC | .NET CLR Memory | 
| .NET CLR Networking 4.0.0.0 HttpWebRequest Average Queue Time  | .NET CLR Networking 4.0.0.0  | 
| .NET CLR Networking 4.0.0.0 HttpWebRequests Aborted/Sec  | .NET CLR Networking 4.0.0.0  | 
| .NET CLR Networking 4.0.0.0 HttpWebRequests Failed/Sec  | .NET CLR Networking 4.0.0.0  | 
| .NET CLR Networking 4.0.0.0 HttpWebRequests Queued/Sec  | .NET CLR Networking 4.0.0.0  | 
| APP\$1POOL\$1WAS Total Worker Process Ping Failures | APP\$1POOL\$1WAS | 
| ASP.NET Application Restarts  | ASP.NET  | 
| ASP.NET 请求被拒 | ASP.NET | 
| ASP.NET 工作进程重启 | ASP.NET | 
| ASP.NET 应用程序缓存 API 修剪 | ASP.NET Applications | 
| ASP.NET Applications % Managed Processor Time (estimated) | ASP.NET Applications | 
| ASP.NET Applications Errors Total/Sec | ASP.NET Applications | 
|  ASP.NET Applications Errors Unhandled During Execution/Sec  |  ASP.NET Applications  | 
|  ASP.NET Applications Requests in Application Queue  |  ASP.NET Applications  | 
|  ASP.NET Applications Requests/Sec  |  ASP.NET Applications  | 
| ASP.NET Request Wait Time  | ASP.NET  | 
| ASP.NET Requests Queued  | ASP.NET  | 
| 数据库 ==> 实例数据库缓存 % 命中 | 数据库 ==> 实例 | 
| 数据库 ==> 实例 I/O 数据库读取平均延迟 | 数据库 ==> 实例 | 
| 数据库 ==> 实例 I/O 数据库读取/秒 | 数据库 ==> 实例 | 
| 数据库 ==> 实例 I/O 日志写入平均延迟 | 数据库 ==> 实例 | 
| DirectoryServices DRA 挂起的复制操作 | DirectoryServices | 
| DirectoryServices DRA 挂起的复制同步 | DirectoryServices | 
| DirectoryServices LDAP 绑定时间 | DirectoryServices | 
| DNS 递归查询/秒 | DNS | 
| DNS 递归查询失败/秒 | DNS | 
| DNS TCP 接收查询/秒 | DNS | 
| DNS 总接收查询/秒 | DNS | 
| DNS 总发送响应/秒 | DNS | 
| DNS UDP 接收查询/秒 | DNS | 
| HTTP Service Request Queues CurrentQueueSize  | HTTP Service Request Queues  | 
|  LogicalDisk % Free Space  |  LogicalDisk  | 
| LogicalDisk 平均值 Disk sec/Write | LogicalDisk | 
| LogicalDisk 平均值 Disk sec/Read | LogicalDisk | 
| LogicalDisk 平均值 Disk Queue Length | LogicalDisk | 
|  Memory % Committed Bytes In Use  | 内存 | 
|  Memory Available Mbytes  |  内存  | 
| Memory Pages/Sec  |  内存  | 
| 内存长期平均备用缓存寿命（秒） | 内存 | 
|  Network Interface Bytes Total/Sec  | 网络接口 | 
| 网络接口接收的字节数/秒 | 网络接口 | 
| 网络接口发送的字节数/秒 | 网络接口 | 
| 网络接口当前带宽 | 网络接口 | 
|  Paging File % Usage  |  Paging File  | 
| PhysicalDisk % Disk Time | PhysicalDisk | 
| PhysicalDisk Avg。Disk Queue Length | PhysicalDisk | 
| PhysicalDisk Avg。Disk Sec/Read | PhysicalDisk | 
| PhysicalDisk Avg。Disk Sec/Write | PhysicalDisk | 
| PhysicalDisk Disk Read Bytes/Sec | PhysicalDisk | 
| PhysicalDisk Disk Reads/Sec | PhysicalDisk | 
| PhysicalDisk Disk Write Bytes/Sec | PhysicalDisk | 
| PhysicalDisk Disk Writes/Sec | PhysicalDisk | 
|  Processor % Idle Time  | 处理器 | 
| Processor % Interrupt Time |  处理器  | 
| Processor % Processor Time |  处理器  | 
| Processor % User Time |  处理器  | 
| SharePoint 基于磁盘的缓存 Blob 缓存填充率  | SharePoint 基于磁盘的缓存  | 
| SharePoint 基于磁盘的缓存 Blob 缓存刷新/秒  | SharePoint 基于磁盘的缓存  | 
| SharePoint 基于磁盘的缓存 Blob 缓存命中率  | SharePoint 基于磁盘的缓存  | 
| SharePoint 基于磁盘的缓存缓存压缩总数 | SharePoint 基于磁盘的缓存  | 
| SharePoint Foundation 执行时间/页面请求 | SharePoint Foundation | 
| SharePoint 发布缓存发布缓存刷新/秒 | SharePoint 发布缓存 | 
| 安全系统范围的统计信息 Kerberos 身份验证 | 安全系统范围的统计 | 
| 安全系统范围的统计信息 NTLM 身份验证 | 安全系统范围的统计 | 
| SQLServer:Access Methods Forwarded Records/Sec |  SQLServer:Access Methods  | 
| SQLServer:Access Methods Full Scans/Sec |  SQLServer:Access Methods  | 
| SQLServer:Access Methods Page Splits/Sec |  SQLServer:Access Methods  | 
| SQLServer:Buffer Manager Buffer cache hit Ratio |  SQLServer:Buffer Manager  | 
| SQLServer:Buffer Manager Page life Expectancy |  SQLServer:Buffer Manager  | 
| SQLServer：接收的数据库副本文件字节数/秒 | SQLServer：数据库副本 | 
| SQLServer：接收的数据库副本日志字节数/秒 | SQLServer：数据库副本 | 
| SQLServer：保留数据库副本日志以供撤消 | SQLServer：数据库副本 | 
| SQLServer：数据库副本日志发送队列 | SQLServer：数据库副本 | 
| SQLServer：数据库副本镜像写事务数/秒 | SQLServer：数据库副本 | 
| SQLServer：数据库副本恢复队列 | SQLServer：数据库副本 | 
| SQLServer：剩余数据库副本重做字节数 | SQLServer：数据库副本 | 
| SQLServer：数据库副本已重做的字节数/秒 | SQLServer：数据库副本 | 
| SQLServer：需要撤消的数据库副本总日志 | SQLServer：数据库副本 | 
| SQLServer：数据库副本事务延迟 | SQLServer：数据库副本 | 
| SQLServer:General Statistics Processes Blocked |  SQLServer:General Statistics  | 
| SQLServer:General Statistics User Connections | SQLServer:General Statistics | 
| SQLServer:Latches Average Latch Wait Time (ms)  | SQLServer:Latches  | 
| SQLServer:Locks Average Wait Time (ms)  | SQLServer:Locks  | 
| SQLServer:Locks Lock Timeouts/Sec  | SQLServer:Locks  | 
| SQLServer:Locks Lock Waits/Sec  | SQLServer:Locks  | 
| SQLServer:Locks Number of Deadlocks/Sec  | SQLServer:Locks  | 
| SQLServer:Memory Manager Memory Grants Pending  | SQLServer:Memory Manager  | 
| SQLServer:SQL Statistics Batch Requests/Sec | SQLServer:SQL Statistics | 
| SQLServer:SQL Statistics SQL Compilations/Sec | SQLServer:SQL Statistics | 
| SQLServer:SQL Statistics SQL Re-Compilations/Sec |  SQLServer:SQL Statistics  | 
| System Processor Queue Length |  系统  | 
| TCPv4 Connections Established | TCPv4 | 
| TCPv6 Connections Established | TCPv6 | 
| W3SVC\$1W3WP File Cache Flushes  | W3SVC\$1W3WP  | 
| W3SVC\$1W3WP File Cache Misses  | W3SVC\$1W3WP  | 
| W3SVC\$1W3WP Requests/Sec  | W3SVC\$1W3WP  | 
| W3SVC\$1W3WP URI Cache Flushes  | W3SVC\$1W3WP  | 
| W3SVC\$1W3WP URI Cache Misses  | W3SVC\$1W3WP  | 
| Web Service Bytes Received/Sec |  Web 服务  | 
| Web Service Bytes Sent/Sec |  Web 服务  | 
|  Web Service Connection Attempts/Sec   |  Web 服务  | 
| Web Service Current Connections  |  Web 服务  | 
| Web Service Get Requests/Sec  |  Web 服务  | 
| Web Service Post Requests/Sec  |  Web 服务  | 

# 使用 CloudWatch 控制台中的资源运行状况视图
<a name="servicelens_resource_health"></a>

您可以使用资源运行状况视图在单个视图中自动发现、管理和可视化主机在其所有应用程序中的运行状况和性能。您可以按性能维度（如 CPU 或内存）可视化显示其主机的运行状况，并使用筛选条件在单个视图中对数百台主机进行切片和切块。您可以按标签或使用案例进行筛选，例如同一 Auto Scaling 组中的主机或使用同一负载均衡器的主机，

## 先决条件
<a name="servicelens_resource_health-prerequisites"></a>

要确保充分享受资源运行状况视图的益处，请检查您是否满足以下先决条件。
+ 要查看主机的内存利用率并将其用作筛选条件，您必须在主机上安装 CloudWatch 代理，并将其设置为在默认 `CWAgent` 命名空间中向 CloudWatch 发送内存指标。在 Linux 和 macOS 实例上，CloudWatch 代理必须发送 `mem_used_percent` 指标。在 Windows 实例上，此代理必须发送 `Memory % Committed Bytes In Use` 指标。如果您使用向导创建 CloudWatch 代理配置文件并选择任意预定义的指标集，则这些指标会包含在其中。CloudWatch 代理收集的指标按自定义指标计费。有关更多信息，请参阅 [安装 CloudWatch 代理](install-CloudWatch-Agent-on-EC2-Instance.md)。

  当您使用 CloudWatch 代理收集这些内存指标以用于资源运行状况视图时，您必须将以下部分添加到 CloudWatch 代理配置文件中。此部分包含默认维度设置，并且是预设情况下的创建内容，因此请勿更改此部分的任何内容，保持其与以下示例所示内容一致。

  ```
  "append_dimensions": {
    "ImageId": "${aws:ImageId}",
    "InstanceId": "${aws:InstanceId}",
    "InstanceType": "${aws:InstanceType}",
    "AutoScalingGroupName": "${aws:AutoScalingGroupName}"
  },
  ```
+  要查看资源运行状况视图中的所有可用信息，您必须登录具有以下权限的账户。如果您登录的账户的权限较少，您仍然可以使用资源运行状况视图，但某些性能数据将不可见。

------
#### [ JSON ]

****  

  ```
  {
      "Version":"2012-10-17",		 	 	 
      "Statement": [
          {
              "Action": [
                  "autoscaling:Describe*",
                  "cloudwatch:Describe*",
                  "cloudwatch:Describe*",
                  "cloudwatch:Get*",
                  "cloudwatch:List*",
                  "logs:Get*",
                  "logs:Describe*",
                  "sns:Get*",
                  "sns:List*",
                  "ec2:DescribeInstances",
                  "ec2:DescribeInstanceStatus",
                  "ec2:DescribeRegions"
              ],
              "Effect": "Allow",
              "Resource": "*"
          }
      ]
  }
  ```

------

**在账户中查看资源运行状况**

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 在导航窗格中，选择**洞察**，然后选择 **EC2 资源运行状况**。

   此时将显示资源运行状况页面，页面上显示账户中每台主机对应的一个方块。根据 **Color by（颜色依据）**设置，每个方块的颜色都基于该主机的当前状态。主机方块带有告警符号，表示该主机当前有一个或多个处于 ALARM 状态的告警。

   您可以在单个视图中查看多达 500 台主机的运行状况。如果您账户中主机数量超过此数量，请使用此程序步骤 6 中的筛选条件设置。

1. 若要更改显示每个主机运行状况所基于的条件，请选择 **Color by（颜色依据）**。您可以选择 **CPU Utilization（CPU 利用率）**、**Memory Utilization（内存利用率）**，或 **Status check（状态检查）**。内存利用率指标仅适用于运行 CloudWatch 代理且将其配置为收集内存指标并将指标发送到默认 `CWAgent` 命名空间的主机。有关更多信息，请参阅 [使用 CloudWatch 代理采集指标、日志和跟踪数据](Install-CloudWatch-Agent.md)。

1. 若要更改用于网格中运行状况指标的阈值和颜色，请选择网格上方的齿轮图标。

1. 若要切换是否在主机网格中显示告警，请选择或清除 **Show alarms across all metrics（显示所有指标的告警）**。

1. 若要将地图中的主机拆分为组，请选择 **Group by（分组依据）**。

1. 若要将视图所涵盖的主机范围缩小，请选择 **Filter by（筛选条件）**中的筛选条件。您可以按标签和资源分组（如 Auto Scaling 组、实例类型、安全组等）进行筛选。

1. 若要对主机进行排序，请选择 **Sort by（排序方式）**。您可以按状态检查结果、实例状态、CPU 或内存利用率以及处于 ALARM 状态的告警数量进行排序。

1. 要查看有关主机的详细信息，请选择表示该主机的方块。随后会显示一个弹出窗格。然后要深入了解有关该主机的信息，请选择 **View dashboard（查看控制面板）**或 **View on list（在列表中查看）**。