Azure 监视 REST API 演练

本文说明如何使用 Azure Monitor REST API 参考

使用 Azure Monitor API 检索指标定义、维度值和指标值,并在你的应用程序中使用这些数据或存储在数据库中进行分析。 还可以使用 Azure Monitor API 列出警报规则并查看活动日志。

对 Azure Monitor 请求进行身份验证

使用 Azure Monitor API 提交的请求使用 Azure 资源管理器身份验证模型。 所有请求都使用 Microsoft Entra ID 进行身份验证。 要对客户端应用程序进行身份验证,一种方法是创建 Microsoft Entra 服务主体,并检索身份验证令牌。 可以使用 Azure 门户、CLI 或 PowerShell 创建 Microsoft Entra 服务主体。 有关详细信息,请参阅注册应用以请求授权令牌并使用 API

检索令牌

创建服务主体后,使用 REST 调用检索访问令牌。 使用 appIdpassword 为服务主体或应用提交以下请求:


    POST /<tenant-id>/oauth2/token
    Host: https://login.partner.microsoftonline.cn
    Content-Type: application/x-www-form-urlencoded
    
    grant_type=client_credentials
    &client_id=<app-client-id>
    &resource=https://management.chinacloudapi.cn
    &client_secret=<password>

例如

curl --location --request POST 'https://login.partner.microsoftonline.cn/abcd1234-5849-4a5d-a2eb-5267eae1bbc7/oauth2/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=client_credentials' \
--data-urlencode 'client_id=0123b56a-c987-1234-abcd-1a2b3c4d5e6f' \
--data-urlencode 'client_secret=123456.ABCDE.~XYZ876123ABceDb0000' \
--data-urlencode 'resource=https://management.chinacloudapi.cn'

成功的请求在响应中接收访问令牌:

{
   token_type": "Bearer",
   "expires_in": "86399",
   "ext_expires_in": "86399",
   "access_token": "eyJ0eXAiOiJKV1QiLCJ.....Ax"
}

验证和检索令牌后,在 Azure Monitor API 请求中使用该访问令牌,方法是包括标头 'Authorization: Bearer <access token>'

注意

有关使用 Azure REST API 的详细信息,请参阅 Azure REST API 参考

检索资源 ID

使用 REST API 需要目标 Azure 资源的资源 ID。 资源 ID 遵循以下模式:

/subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/<provider>/<resource name>/

例如

  • Azure IoT 中心:/subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/Microsoft.Devices/IotHubs/<iot-hub-name>
  • SQL 弹性池:/subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/Microsoft.Sql/servers/<pool-db>/elasticpools/<sql-pool-name>
  • Azure SQL 数据库 (v12):/subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/Microsoft.Sql/servers/<server-name>/databases/<database-name>
  • Azure 服务总线:/subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/Microsoft.ServiceBus/<namespace>/<servicebus-name>
  • Azure 虚拟机规模集:/subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/Microsoft.Compute/virtualMachineScaleSets/<vm-name>
  • Azure 虚拟机:/subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/Microsoft.Compute/virtualMachines/<vm-name>
  • Azure 事件中心:/subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/Microsoft.EventHub/namespaces/<eventhub-namespace>

使用 Azure 门户、PowerShell 或 Azure CLI 查找资源 ID。

要在门户中查找 resourceID,请从资源的概述页面中选择“JSON 视图显示资源概述页面的屏幕截图,其中突出显示了 JSON 视图链接。

随即将显示“资源 JSON”页。 可以使用 ID 右侧的图标复制资源 ID。

屏幕截图显示资源的“资源 JSON”页。

API 终结点

API 终结点将使用以下模式:
/<resource URI>/providers/microsoft.insights/<metrics|metricDefinitions>?api-version=<apiVersion>
resource URI 由以下部分组成:
/subscriptions/<subscription id>/resourcegroups/<resourceGroupName>/providers/<resourceProviderNamespace>/<resourceType>/<resourceName>/

重要

进行 API 调用以检索指标或指标定义时,请确保在资源 URI 后面添加 /providers/microsoft.insights/

检索指标定义

使用 Azure Monitor 指标定义 REST API 访问服务可用的指标列表。 使用以下请求格式检索指标定义。

GET /subscriptions/<subscription id>/resourcegroups/<resourceGroupName>/providers/<resourceProviderNamespace>/<resourceType>/<resourceName>/providers/microsoft.insights/metricDefinitions?api-version=<apiVersion>
Host: management.chinacloudapi.cn
Content-Type: application/json
Authorization: Bearer <access token>

例如,以下请求检索 Azure 存储帐户的指标定义。

curl --location --request GET 'https://management.chinacloudapi.cn/subscriptions/12345678-abcd-98765432-abcdef012345/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Storage/storageAccounts/ContosoStorage/providers/microsoft.insights/metricDefinitions?api-version=2018-01-01'
--header 'Authorization: Bearer eyJ0eXAiOi...xYz

以下 JSON 展示了一个示例响应正文。 在此示例中,只有第二个指标具有维度。

{
    "value": [
        {
            "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Storage/storageAccounts/ContosoStorage/providers/microsoft.insights/metricdefinitions/UsedCapacity",
            "resourceId": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Storage/storageAccounts/ContosoStorage",
            "namespace": "Microsoft.Storage/storageAccounts",
            "category": "Capacity",
            "name": {
                "value": "UsedCapacity",
                "localizedValue": "Used capacity"
            },
            "isDimensionRequired": false,
            "unit": "Bytes",
            "primaryAggregationType": "Average",
            "supportedAggregationTypes": [
                "Total",
                "Average",
                "Minimum",
                "Maximum"
            ],
            "metricAvailabilities": [
                {
                    "timeGrain": "PT1H",
                    "retention": "P93D"
                },
                 ...
                {
                    "timeGrain": "PT12H",
                    "retention": "P93D"
                },
                {
                    "timeGrain": "P1D",
                    "retention": "P93D"
                }
            ]
        },
        {
            "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Storage/storageAccounts/ContosoStorage/providers/microsoft.insights/metricdefinitions/Transactions",
            "resourceId": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Storage/storageAccounts/ContosoStorage",
            "namespace": "Microsoft.Storage/storageAccounts",
            "category": "Transaction",
            "name": {
                "value": "Transactions",
                "localizedValue": "Transactions"
            },
            "isDimensionRequired": false,
            "unit": "Count",
            "primaryAggregationType": "Total",
            "supportedAggregationTypes": [
                "Total"
            ],
            "metricAvailabilities": [
                {
                    "timeGrain": "PT1M",
                    "retention": "P93D"
                },
                {
                    "timeGrain": "PT5M",
                    "retention": "P93D"
                },
                ...
                {
                    "timeGrain": "PT30M",
                    "retention": "P93D"
                },
                {
                    "timeGrain": "PT1H",
                    "retention": "P93D"
                },
                ...
                {
                    "timeGrain": "P1D",
                    "retention": "P93D"
                }
            ],
            "dimensions": [
                {
                    "value": "ResponseType",
                    "localizedValue": "Response type"
                },
                {
                    "value": "GeoType",
                    "localizedValue": "Geo type"
                },
                {
                    "value": "ApiName",
                    "localizedValue": "API name"
                }
            ]
        },
        ...
    ]
}

注意

建议使用 API 版本“2018-01-01”或更高版本。 较旧版本的指标定义 API 不支持维度。

检索维度值

检索可用的指标定义后,检索指标维度的值范围。 使用维度值筛选或细分查询中的指标。 使用 Azure Monitor 指标 REST API 查找给定指标维度的所有值。

在筛选器定义中使用指标的 name.value 元素。 如果未指定筛选器,则返回默认指标。 此 API 仅允许一个维度具有通配符筛选器。 使用 "resultType=metadata" 查询参数指定维度值请求。 对于指标值请求,省略 resultType

注意

若要使用 Azure Monitor REST API 检索维度值,请使用 API 版本“2019-07-01”或更高。

使用以下请求格式检索维度值。

GET /subscriptions/<subscription-id>/resourceGroups/  
<resource-group-name>/providers/<resource-provider-namespace>/  
<resource-type>/<resource-name>/providers/microsoft.insights/  
metrics?metricnames=<metric>  
&timespan=<starttime/endtime>  
&$filter=<filter>  
&resultType=metadata  
&api-version=<apiVersion>   HTTP/1.1
Host: management.chinacloudapi.cn
Content-Type: application/json
Authorization: Bearer <access token>

以下示例检索为 Transactions 指标的 API Name 维度发出的维度值列表,其中在指定时间范围内 GeoType 维度的值为 Primary

curl --location --request GET 'https://management.chinacloudapi.cn/subscriptions/12345678-abcd-98765432-abcdef012345/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Storage/storageAccounts/ContosoStorage/providers/microsoft.insights/metrics  \
?metricnames=Transactions \
&timespan=2023-03-01T00:00:00Z/2023-03-02T00:00:00Z \
&resultType=metadata \
&$filter=GeoType eq \'Primary\' and ApiName eq \'*\' \
&api-version=2019-07-01'
-header 'Content-Type: application/json' \
--header 'Authorization: Bearer eyJ0e..meG1lWm9Y'

以下 JSON 展示了一个示例响应正文。

{
  "timespan": "2023-03-01T00:00:00Z/2023-03-02T00:00:00Z",
  "value": [
    {
      "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Storage/storageAccounts/ContosoStorage/providers/Microsoft.Insights/metrics/Transactions",
      "type": "Microsoft.Insights/metrics",
      "name": {
        "value": "Transactions",
        "localizedValue": "Transactions"
      },
      "unit": "Count",
      "timeseries": [
        {
          "metadatavalues": [
            {
              "name": {
                "value": "apiname",
                "localizedValue": "apiname"
              },
              "value": "DeleteBlob"
            }
          ]
        },
        {
          "metadatavalues": [
            {
              "name": {
                "value": "apiname",
                "localizedValue": "apiname"
              },
              "value": "SetBlobProperties"
            }
          ]
        },
        ...
      ]
    }
  ],
  "namespace": "Microsoft.Storage/storageAccounts",
  "resourceregion": "chinanorth"
}

检索指标值

检索指标定义和维度值之后,检索指标值。 使用 Azure Monitor 指标 REST API 检索指标值。

在筛选器定义中使用指标的 name.value 元素。 如果未指定维筛选器,则会返回汇总的聚合指标。

若要提取具有特定维度值的多个时序,请指定一个筛选器查询参数,该参数指定两个维度值,例如 "&$filter=ApiName eq 'ListContainers' or ApiName eq 'GetBlobServiceProperties'"

若要返回给定维度的每个值的时序,请使用 * 筛选器,例如 "&$filter=ApiName eq '*'"TopOrderBy 查询参数可用于限制返回的时序数以及对这些时序进行排序。

注意

若要使用 Azure Monitor REST API 检索多维指标值,请使用 API 版本“2019-07-01”或更高。

使用以下请求格式检索指标值。

GET /subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/<resource-provider-namespace>/<resource-type>/<resource-name>/providers/microsoft.insights/metrics?metricnames=<metric>&timespan=<starttime/endtime>&$filter=<filter>&interval=<timeGrain>&aggregation=<aggreation>&api-version=<apiVersion>
Host: management.chinacloudapi.cn
Content-Type: application/json
Authorization: Bearer <access token>

以下示例按 5 分钟范围内的 Transactions 数(降序)检索前三个 API,其中 GeoType 维度的值为 Primary

curl --location --request GET 'https://management.chinacloudapi.cn/subscriptions/12345678-abcd-98765432-abcdef012345/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Storage/storageAccounts/ContosoStorage/providers/microsoft.insights/metrics \
?metricnames=Transactions \
&timespan=2023-03-01T02:00:00Z/2023-03-01T02:05:00Z \
& $filter=apiname eq '\''GetBlobProperties'\'
&interval=PT1M \
&aggregation=Total  \
&top=3 \
&orderby=Total desc \
&api-version=2019-07-01"' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer yJ0eXAiOi...g1dCI6Ii1LS'

以下 JSON 展示了一个示例响应正文。

{
  "cost": 0,
  "timespan": "2023-03-01T02:00:00Z/2023-03-01T02:05:00Z",
  "interval": "PT1M",
  "value": [
    {
      "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Storage/storageAccounts/ContosoStorage/providers/Microsoft.Insights/metrics/Transactions",
      "type": "Microsoft.Insights/metrics",
      "name": {
        "value": "Transactions",
        "localizedValue": "Transactions"
      },
      "unit": "Count",
      "timeseries": [
        {
          "metadatavalues": [
            {
              "name": {
                "value": "apiname",
                "localizedValue": "apiname"
              },
              "value": "GetBlobProperties"
            }
          ],
          "data": [
            {
              "timeStamp": "2023-09-19T02:00:00Z",
              "total": 2
            },
            {
              "timeStamp": "2023-09-19T02:01:00Z",
              "total": 1
            },
            {
              "timeStamp": "2023-09-19T02:02:00Z",
              "total": 3
            },
            {
              "timeStamp": "2023-09-19T02:03:00Z",
              "total": 7
            },
            {
              "timeStamp": "2023-09-19T02:04:00Z",
              "total": 2
            }
          ]
        },
        ...
      ]
    }
  ],
  "namespace": "Microsoft.Storage/storageAccounts",
  "resourceregion": "chinanorth"
}

一次性查询多个资源的指标。

除了查询单个资源的指标外,某些资源类型还支持在单个请求中查询多个资源。 这些 API 为 Azure 指标资源管理器中的多资源体验提供了支持。 可以通过上下文边栏选项卡上范围选择器中的资源类型下拉列表在 Azure Monitor 的“指标”边栏选项卡中查看支持查询多个指标的资源类型集。

查询多个资源和单个资源的指标之间存在一些重要差异。

  • 指标多资源 API 在订阅级别而不是资源 ID 级别运行。 此限制意味着查询这些 API 的用户必须对订阅本身具有监视读者权限。
  • 指标多资源 API 仅支持每个查询单个 resourceType,这必须以 metricnamespace 查询参数的形式指定。
  • 指标多资源 API 仅支持每个查询单个 Azure 区域,这必须以区域查询参数的形式指定。

查询多个资源的指标示例

以下示例显示了各个指标定义请求:

GET https://management.chinacloudapi.cn/subscriptions/12345678-abcd-98765432-abcdef012345/resourceGroups/EASTUS-TESTING/providers/Microsoft.Compute/virtualMachines/TestVM1/providers/microsoft.insights/metricdefinitions?api-version=2021-05-01

以下请求显示了多个资源的等效指标定义请求。 唯一的更改是订阅路径而不是资源 ID 路径,以及添加了 regionmetricNamespace 查询参数。

GET https://management.chinacloudapi.cn/subscriptions/12345678-abcd-98765432-abcdef012345/providers/microsoft.insights/metricdefinitions?api-version=2021-05-01&region=chinanorth&metricNamespace=microsoft.compute/virtualmachines

以下示例显示了单个指标请求。

GET https://management.chinacloudapi.cn/subscriptions/12345678-abcd-98765432-abcdef012345/resourceGroups/EASTUS-TESTING/providers/Microsoft.Compute/virtualMachines/TestVM1/providers/microsoft.Insights/metrics?timespan=2023-06-25T22:20:00.000Z/2023-06-26T22:25:00.000Z&interval=PT5M&metricnames=Percentage CPU&aggregation=average&api-version=2021-05-01

下面是面向多个资源的等效指标请求:

GET https://management.chinacloudapi.cn/subscriptions/12345678-abcd-98765432-abcdef012345/providers/microsoft.Insights/metrics?timespan=2023-06-25T22:20:00.000Z/2023-06-26T22:25:00.000Z&interval=PT5M&metricnames=Percentage CPU&aggregation=average&api-version=2021-05-01&region=chinanorth&metricNamespace=microsoft.compute/virtualmachines&$filter=Microsoft.ResourceId eq '*'

注意

在多资源指标请求示例中添加了 Microsoft.ResourceId eq '*' 筛选器。 筛选器会告知 API 在订阅和区域中为每个虚拟机资源返回单独的时序。 如果没有筛选器,API 将会返回聚合了所有 VM 的平均 CPU 的单个时序。 每个资源的时序由每个时序条目的 Microsoft.ResourceId 元数据值进行区分,如以下示例返回值所示。 如果此查询未检索 resourceId,则返回空时序"timeseries": []

{
    "timespan": "2023-06-25T22:35:00Z/2023-06-26T22:40:00Z",
    "interval": "PT6H",
    "value": [
        {
            "id": "subscriptions/12345678-abcd-98765432-abcdef012345/providers/Microsoft.Insights/metrics/Percentage CPU",
            "type": "Microsoft.Insights/metrics",
            "name": {
                "value": "Percentage CPU",
                "localizedValue": "Percentage CPU"
            },
            "displayDescription": "The percentage of allocated compute units that are currently in use by the Virtual Machine(s)",
            "unit": "Percent",
            "timeseries": [
                {
                    "metadatavalues": [
                        {
                            "name": {
                                "value": "Microsoft.ResourceId",
                                "localizedValue": "Microsoft.ResourceId"
                            },
                            "value": "/subscriptions/12345678-abcd-98765432-abcdef012345/resourceGroups/EASTUS-TESTING/providers/Microsoft.Compute/virtualMachines/TestVM1"
                        }
                    ],
                    "data": [
                        {
                            "timeStamp": "2023-06-25T22:35:00Z",
                            "average": 3.2618888888888886
                        },
                        {
                            "timeStamp": "2023-06-26T04:35:00Z",
                            "average": 4.696944444444445
                        },
                        {
                            "timeStamp": "2023-06-26T10:35:00Z",
                            "average": 6.19701388888889
                        },
                        {
                            "timeStamp": "2023-06-26T16:35:00Z",
                            "average": 2.630347222222222
                        },
                        {
                            "timeStamp": "2023-06-26T22:35:00Z",
                            "average": 21.288999999999998
                        }
                    ]
                },
                {
                    "metadatavalues": [
                        {
                            "name": {
                                "value": "Microsoft.ResourceId",
                                "localizedValue": "Microsoft.ResourceId"
                            },
                            "value": "/subscriptions/12345678-abcd-98765432-abcdef012345/resourceGroups/EASTUS-TESTING/providers/Microsoft.Compute/virtualMachines/TestVM2"
                        }
                    ],
                    "data": [
                        {
                            "timeStamp": "2023-06-25T22:35:00Z",
                            "average": 7.567069444444444
                        },
                        {
                            "timeStamp": "2023-06-26T04:35:00Z",
                            "average": 5.111835883171071
                        },
                        {
                            "timeStamp": "2023-06-26T10:35:00Z",
                            "average": 10.078277777777778
                        },
                        {
                            "timeStamp": "2023-06-26T16:35:00Z",
                            "average": 8.399097222222222
                        },
                        {
                            "timeStamp": "2023-06-26T22:35:00Z",
                            "average": 2.647
                        }
                    ]
                },
                {
                    "metadatavalues": [
                        {
                            "name": {
                                "value": "Microsoft.ResourceId",
                                "localizedValue": "Microsoft.ResourceId"
                            },
                            "value": "/subscriptions/12345678-abcd-98765432-abcdef012345/resourceGroups/Common-TESTING/providers/Microsoft.Compute/virtualMachines/CommonVM1"
                        }
                    ],
                    "data": [
                        {
                            "timeStamp": "2023-06-25T22:35:00Z",
                            "average": 6.892319444444444
                        },
                        {
                            "timeStamp": "2023-06-26T04:35:00Z",
                            "average": 3.5054305555555554
                        },
                        {
                            "timeStamp": "2023-06-26T10:35:00Z",
                            "average": 8.398817802503476
                        },
                        {
                            "timeStamp": "2023-06-26T16:35:00Z",
                            "average": 6.841666666666667
                        },
                        {
                            "timeStamp": "2023-06-26T22:35:00Z",
                            "average": 3.3850000000000002
                        }
                    ]
                }
            ],
            "errorCode": "Success"
        }
    ],
    "namespace": "microsoft.compute/virtualmachines",
    "resourceregion": "chinanorth"
}

排除查询多个资源的指标时的故障

  • 返回的空时序 "timeseries": []

    • 当没有可用于指定时间范围和筛选器的数据时,将返回空时序。 最常见的原因是指定的时间范围不包含任何数据。 例如,如果时间范围设置为将来的日期。
    • 另一个常见原因是指定的筛选器与任何资源不匹配。 例如,如果筛选器指定订阅和区域组合中的任何资源上不存在的维度值,则返回 "timeseries": []
  • 通配符筛选器
    使用通配符筛选器(例如 Microsoft.ResourceId eq '*')会导致 API 返回订阅和区域中每个 resourceId 的时序。 如果订阅和区域组合不包含任何资源,则返回空时序。 没有通配符筛选器的相同查询将返回单个时序,将请求的指标聚合到请求的维度上,例如订阅和区域。 如果订阅和区域组合中没有资源,API 将返回具有单个数据点 0 的单个时序。

  • 401 授权错误:
    单个指标 API 要求用户对要查询的资源具有监视读者权限。 由于多资源指标 API 是订阅级 API,因此用户必须对所查询订阅具有监视读者权限才能使用多资源指标 API。 即使用户对订阅中所有资源具有监视读者权限,如果用户对订阅本身没有该权限,请求也会失败。

后续步骤