Azure 監視 REST API 逐步解說

本文說明如何使用 Azure 監視器 REST API 參考

使用 Azure 監視器 API 擷取計量定義、維度值和計量值,並使用應用程式中的數據,或儲存在資料庫中進行分析。 您也可以使用 Azure 監視器 API 列出警示規則和檢視活動記錄。

驗證 Azure 監視器要求

使用 Azure 監視器 API 提交的要求會使用 Azure Resource Manager 驗證模型。 所有要求都會使用 Microsoft Entra ID 進行驗證。 驗證客戶端應用程式的其中一種方法是建立 Microsoft Entra 服務主體並擷取驗證令牌。 您可以使用 Azure 入口網站、CLI 或 PowerShell 來建立 Microsoft Entra 服務主體。 如需詳細資訊,請參閱 註冊應用程式以要求授權令牌和使用 API

擷取令牌

建立服務主體之後,請使用 REST 呼叫擷取存取令牌。 針對您的服務主體或應用程式,使用 appIdpassword 提交下列要求:


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

例如:

curl --location --request POST 'https://login.microsoftonline.com/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.azure.com'

成功的要求會在回應中接收存取令牌:

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

驗證和擷取令牌之後,請在 Azure 監視器 API 要求中包含標頭,以使用存取令牌 'Authorization: Bearer <access token>'

注意

如需使用 Azure REST API 的詳細資訊,請參閱 Azure REST API 參考

擷取資源標識碼

使用 REST API 需要目標 Azure 資源的資源識別碼。 資源識別碼遵循下列模式:

/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 來尋找資源識別碼。

若要在入口網站中尋找 resourceID,請從資源的概觀頁面選取 [JSON 檢視]A screenshot showing the overview page for a resource with the JSON view link highlighted.

[資源 JSON] 頁面隨即顯示。 您可以使用識別子右邊的圖示來複製資源識別碼。

A screenshot showing the Resource JSON page for a resource.

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 監視器計量定義 REST API 來存取服務可用的計量清單。 使用下列要求格式來擷取計量定義。

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

例如,下列要求會擷取 Azure 儲存體 帳戶的計量定義。

curl --location --request GET 'https://management.azure.com/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/12345678-abcd-98765432-abcdef012345/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Storage/storageAccounts/ContosoStorage/providers/microsoft.insights/metricdefinitions/UsedCapacity",
            "resourceId": "/subscriptions/12345678-abcd-98765432-abcdef012345/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/12345678-abcd-98765432-abcdef012345/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Storage/storageAccounts/ContosoStorage/providers/microsoft.insights/metricdefinitions/Transactions",
            "resourceId": "/subscriptions/12345678-abcd-98765432-abcdef012345/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 監視器計量 REST API 來尋找指定計量維度的所有值。

在篩選定義中使用計量的 name.value 元素。 如果未指定任何篩選,則會傳回預設計量。 API 只允許一個維度具有通配符篩選。 使用 "resultType=metadata" 查詢參數指定維度值的要求。 resultType計量值要求會省略 。

注意

若要使用 Azure 監視器 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.azure.com
Content-Type: application/json
Authorization: Bearer <access token>

下列範例會擷取針對API NameTransactions計量維度發出的維度值清單,其中GeoType維度具有 指定時間範圍的 值Primary

curl --location --request GET 'https://management.azure.com/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/12345678-abcd-98765432-abcdef012345/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": "eastus"
}

擷取計量值

擷取計量定義和維度值之後,擷取計量值。 使用 Azure 監視器計量 REST API 來擷取計量值。

在篩選定義中使用計量的 name.value 元素。 如果未指定維度篩選,則會傳回匯總的匯總計量。

若要擷取具有特定維度值的多個時間序列,請指定篩選查詢參數,以指定兩個維度值,例如 "&$filter=ApiName eq 'ListContainers' or ApiName eq 'GetBlobServiceProperties'"

若要傳回指定維度之每個值的時間序列,請使用 * 例如 的 "&$filter=ApiName eq '*'"篩選。 TopOrderBy 查詢參數可用來限制和排序傳回的時間序列數目。

注意

若要使用 Azure 監視器 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.azure.com
Content-Type: application/json
Authorization: Bearer <access token>

下列範例會擷取前三個 API,其 Transactions 值為 的遞減值順序,在 GeoType 5 分鐘範圍內,其中維度的值為 Primary

curl --location --request GET 'https://management.azure.com/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/12345678-abcd-98765432-abcdef012345/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": "eastus"
}

一次查詢多個資源的計量。

除了查詢個別資源的計量之外,某些資源類型也支援在單一要求中查詢多個資源。 這些 API 是 Azure 計量總管中多資源體驗的強大功能。 您可以透過內容刀鋒視窗上範圍選取器中的資源類型下拉式清單,在 Azure 監視器的 [計量] 刀鋒視窗上看到支持查詢多個計量的資源類型。 如需詳細資訊,請參閱 多資源 UX 檔

查詢多個和個別資源的計量之間有一些重要差異。

  • 計量多資源 API 會在訂用帳戶層級運作,而不是資源標識符層級。 此限制表示查詢這些 API 的用戶必須擁有 訂用帳戶本身的監視讀取者 許可權。
  • 計量多資源 API 僅支援每個查詢的單一 resourceType,此類型必須以計量命名空間查詢參數的形式指定。
  • 計量多資源 API 僅支援每個查詢的單一 Azure 區域,此區域必須以區域查詢參數的形式指定。

查詢多個資源範例的計量

下列範例顯示個別計量定義要求:

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

下列要求會顯示多個資源的對等計量定義要求。 唯一的變更是訂用帳戶路徑,而不是資源標識符路徑,以及新增 regionmetricNamespace 查詢參數。

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

下列範例顯示個別計量要求。

GET https://management.azure.com/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.azure.com/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=eastus&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": "eastus"
}

針對多個資源的查詢計量進行疑難解答

  • 傳回的空白時間序列 "timeseries": []

    • 當指定的時間範圍和篩選沒有數據可用時,會傳回空的時間序列。 最常見的原因是指定不包含任何數據的時間範圍。 例如,如果時間範圍設定為未來的日期。
    • 另一個常見原因是指定不符合任何資源的篩選。 例如,如果篩選指定訂用帳戶和區域組合中任何資源上不存在的維度值, "timeseries": [] 則會傳回 。
  • 通配符篩選
    使用通配符篩選條件,例如 Microsoft.ResourceId eq '*' ,讓 API 傳回訂用帳戶和區域中每個 resourceId 的時間序列。 如果訂用帳戶和區域組合不包含任何資源,則會傳回空的時間序列。 沒有通配符篩選的相同查詢會傳回單一時間序列,例如訂用帳戶和區域,匯總要求的計量。 如果訂用帳戶和區域組合中沒有任何資源,API 會傳回單一時間序列,且具有 單一數據點 0

  • 401 授權錯誤:
    個別資源計量 API 需要使用者具有 所查詢資源的監視讀取者 許可權。 由於多重資源計量 API 是訂用帳戶層級 API,因此用戶必須具有 查詢訂用帳戶的監視讀取者 許可權,才能使用多重資源計量 API。 即使使用者在訂用帳戶中的所有資源上都有監視讀取器,如果使用者本身沒有監視讀取器,要求也會失敗。

下一步