Azure 监视 REST API 演练Azure Monitoring REST API walkthrough

备注

本文进行了更新,以便使用新的 Azure PowerShell Az 模块。This article has been updated to use the new Azure PowerShell Az module. 你仍然可以使用 AzureRM 模块,至少在 2020 年 12 月之前,它将继续接收 bug 修补程序。You can still use the AzureRM module, which will continue to receive bug fixes until at least December 2020. 若要详细了解新的 Az 模块和 AzureRM 兼容性,请参阅新 Azure Powershell Az 模块简介To learn more about the new Az module and AzureRM compatibility, see Introducing the new Azure PowerShell Az module. 有关 Az 模块安装说明,请参阅安装 Azure PowerShellFor Az module installation instructions, see Install Azure PowerShell.

本文说明如何执行身份验证,使代码能够遵循 Azure Monitor REST API 参考This article shows you how to perform authentication so your code can use the Azure Monitor REST API Reference.

使用 Azure Monitor API 能够以编程方式检索可用的默认指标定义、粒度和指标值。The Azure Monitor API makes it possible to programmatically retrieve the available default metric definitions, granularity, and metric values. 可将数据保存在独立的数据存储(例如 Azure SQL 数据库或 Azure Cosmos DB)中。The data can be saved in a separate data store such as Azure SQL Database, or Azure Cosmos DB. 然后,可以根据需要从该处执行其他分析。From there additional analysis can be performed as needed.

除了处理各种指标数据点以外,使用监视 API 还可以列出警报规则、查看活动日志以及执行其他许多操作。Besides working with various metric data points, the Monitor API also makes it possible to list alert rules, view activity logs, and much more. 有关可用操作的完整列表,请参阅 Azure Monitor REST API 参考For a full list of available operations, see the Azure Monitor REST API Reference.

对 Azure Monitor 请求进行身份验证Authenticating Azure Monitor requests

第一步是对请求进行身份验证。The first step is to authenticate the request.

针对 Azure 监视器 API 执行的所有任务都使用 Azure Resource Manager 身份验证模型。All the tasks executed against the Azure Monitor API use the Azure Resource Manager authentication model. 因此,所有请求必须使用 Azure Active Directory (Azure AD) 进行身份验证。Therefore, all requests must be authenticated with Azure Active Directory (Azure AD). 对客户端应用程序进行身份验证的方法之一是创建 Azure AD 服务主体,并检索身份验证 (JWT) 令牌。One approach to authenticate the client application is to create an Azure AD service principal and retrieve the authentication (JWT) token. 以下示例脚本演示如何通过 PowerShell 创建 Azure AD 服务主体。The following sample script demonstrates creating an Azure AD service principal via PowerShell. 有关更详细的演练,请参阅有关使用 Azure PowerShell 创建用于访问资源的服务主体的文档。For a more detailed walk-through, refer to the documentation on using Azure PowerShell to create a service principal to access resources. 还可以通过 Azure 门户创建服务主体It is also possible to create a service principal via the Azure portal.

$subscriptionId = "{azure-subscription-id}"
$resourceGroupName = "{resource-group-name}"

# Authenticate to a specific Azure subscription.
Connect-AzAccount -Environment AzureChinaCloud -SubscriptionId $subscriptionId

# Password for the service principal
$pwd = "{service-principal-password}"
$secureStringPassword = ConvertTo-SecureString -String $pwd -AsPlainText -Force

# Create a new Azure AD application
$azureAdApplication = New-AzADApplication `
                        -DisplayName "My Azure Monitor" `
                        -HomePage "https://localhost/azure-monitor" `
                        -IdentifierUris "https://localhost/azure-monitor" `
                        -Password $secureStringPassword

# Create a new service principal associated with the designated application
New-AzADServicePrincipal -ApplicationId $azureAdApplication.ApplicationId

# Assign Reader role to the newly created service principal
New-AzRoleAssignment -RoleDefinitionName Reader `
                          -ServicePrincipalName $azureAdApplication.ApplicationId.Guid

若要查询 Azure 监视器 API,客户端应用程序应使用事先创建的服务主体进行身份验证。To query the Azure Monitor API, the client application should use the previously created service principal to authenticate. 以下示例 PowerShell 脚本演示了一种使用 Active Directory 身份验证库 (ADAL) 来获取 JWT 身份验证令牌的方法。The following example PowerShell script shows one approach, using the Active Directory Authentication Library (ADAL) to obtain the JWT authentication token. JWT 令牌作为请求中 HTTP 授权参数的一部分传递给 Azure Monitor REST API。The JWT token is passed as part of an HTTP Authorization parameter in requests to the Azure Monitor REST API.

$azureAdApplication = Get-AzADApplication -IdentifierUri "https://localhost/azure-monitor"

$subscription = Get-AzSubscription -SubscriptionId $subscriptionId

$clientId = $azureAdApplication.ApplicationId.Guid
$tenantId = $subscription.TenantId
$authUrl = "https://login.partner.microsoftonline.cn/${tenantId}"

$AuthContext = [Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext]$authUrl
$cred = New-Object -TypeName Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential -ArgumentList ($clientId, $pwd)

$result = $AuthContext.AcquireTokenAsync("https://management.core.chinacloudapi.cn/", $cred).GetAwaiter().GetResult()

# Build an array of HTTP header values
$authHeader = @{
'Content-Type'='application/json'
'Accept'='application/json'
'Authorization'=$result.CreateAuthorizationHeader()
}

进行身份验证后,可以针对 Azure Monitor REST API 执行查询。After authenticating, queries can then be executed against the Azure Monitor REST API. 有两个有用的查询:There are two helpful queries:

  1. 列出资源的指标定义List the metric definitions for a resource
  2. 检索指标值Retrieve the metric values

备注

有关使用 Azure REST API 进行身份验证的其他信息,请参阅 Azure REST API 参考For additional information on authenticating with the Azure REST API, please refer to the Azure REST API Reference.

检索指标定义(多维 API)Retrieve Metric Definitions (Multi-Dimensional API)

使用 Azure Monitor 指标定义 REST API 可以访问服务可用的指标列表。Use the Azure Monitor Metric definitions REST API to access the list of metrics that are available for a service.

方法:GETMethod: GET

请求 URI:https://management.chinacloudapi.cn/subscriptions/ {subscriptionId} /resourceGroups/ {resourceGroupName} /providers/ {resourceProviderNamespace} / {resourceType} / {resourceName} /providers/microsoft.insights/metricDefinitions?api-version= {apiVersion}Request URI: https://management.chinacloudapi.cn/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}/providers/microsoft.insights/metricDefinitions?api-version={apiVersion}

例如,若要检索 Azure 存储帐户的指标定义,请求将如下所示:For example, to retrieve the metric definitions for an Azure Storage account, the request would appear as follows:

$request = "https://management.chinacloudapi.cn/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Storage/storageAccounts/ContosoStorage/providers/microsoft.insights/metricDefinitions?api-version=2018-01-01"

Invoke-RestMethod -Uri $request `
                  -Headers $authHeader `
                  -Method Get `
                  -OutFile ".\contosostorage-metricdef-results.json" `
                  -Verbose

备注

若要使用多维 Azure Monitor 指标 REST API 检索指标定义,请使用“2018-01-01”作为 API 版本。To retrieve metric definitions using the multi-dimensional Azure Monitor metrics REST API, use "2018-01-01" as the API version.

生成的 JSON 响应正文将类似于以下示例:(请注意第二个指标具有维度)The resulting JSON response body would be similar to the following example: (Note that the second metric has dimensions)

{
    "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": "PT6H",
                    "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": "PT15M",
                    "retention": "P93D"
                },
                {
                    "timeGrain": "PT30M",
                    "retention": "P93D"
                },
                {
                    "timeGrain": "PT1H",
                    "retention": "P93D"
                },
                {
                    "timeGrain": "PT6H",
                    "retention": "P93D"
                },
                {
                    "timeGrain": "PT12H",
                    "retention": "P93D"
                },
                {
                    "timeGrain": "P1D",
                    "retention": "P93D"
                }
            ],
            "dimensions": [
                {
                    "value": "ResponseType",
                    "localizedValue": "Response type"
                },
                {
                    "value": "GeoType",
                    "localizedValue": "Geo type"
                },
                {
                    "value": "ApiName",
                    "localizedValue": "API name"
                }
            ]
        },
        ...
    ]
}

检索维值(多维 API)Retrieve Dimension Values (Multi-Dimensional API)

了解可用的指标定义后,可能会发现一些指标具有多个维。Once the available metric definitions are known, there may be some metrics that have dimensions. 在查询指标前,可能需要查明某个维具有的值的范围。Before querying for the metric you may want to discover what the range of values a dimension has. 然后,根据这些维值,在查询指标时,可以选择根据维值对指标进行筛选或分段。Based on these dimension values you can then choose to filter or segment the metrics based on dimension values while querying for metrics. 为此,请使用 Azure Monitor 指标 REST APIUse the Azure Monitor Metrics REST API to achieve this.

对于任何筛选请求,请使用指标的名称“value”(而非“localizedValue”)。Use the metric’s name ‘value’ (not the ‘localizedValue’) for any filtering requests . 如果未指定筛选器,则返回默认指标。If no filters are specified, the default metric is returned. 使用此 API 仅允许一个维度具有通配符筛选器。The usage of this API only allows one dimension to have a wildcard filter.

备注

若要使用 Azure Monitor REST API 检索维度值,请使用“2018-01-01”作为 API 版本。To retrieve dimension values using the Azure Monitor REST API, use "2018-01-01" as the API version.

方法:GETMethod: GET

请求 URI:https://management.chinacloudapi.cn/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}Request URI: https://management.chinacloudapi.cn/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}

例如,若要检索为“事务”指标的“API 名称维度”发出的维度值列表,其中在指定时间范围内 GeoType 维度为“Primary”,则请求将如下所示:For example, to retrieve the list of dimension values that were emitted for the 'API Name dimension' for the 'Transactions' metric, where the GeoType dimension = 'Primary' during the specified time range, the request would be as follows:

$filter = "APIName eq '*' and GeoType eq 'Primary'"
$request = "https://management.chinacloudapi.cn/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Storage/storageAccounts/ContosoStorage/providers/microsoft.insights/metrics?metricnames=Transactions&timespan=2018-03-01T00:00:00Z/2018-03-02T00:00:00Z&resultType=metadata&`$filter=${filter}&api-version=2018-01-01"
Invoke-RestMethod -Uri $request `
    -Headers $authHeader `
    -Method Get `
    -OutFile ".\contosostorage-dimension-values.json" `
    -Verbose

生成的 JSON 响应正文将类似于以下示例:The resulting JSON response body would be similar to the following example:

{
  "timespan": "2018-03-01T00:00:00Z/2018-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"
}

检索指标值(多维 API)Retrieve Metric Values (Multi-Dimensional API)

知道可用的指标定义和可能的维值后,即可检索相关的指标值。Once the available metric definitions and possible dimension values are known, it is then possible to retrieve the related metric values. 为此,请使用 Azure Monitor 指标 REST APIUse the Azure Monitor Metrics REST API to achieve this.

对于任何筛选请求,请使用指标的名称“value”(而非“localizedValue”)。Use the metric’s name ‘value’ (not the ‘localizedValue’) for any filtering requests. 如果未指定维筛选器,则会返回汇总的聚合指标。If no dimension filters are specified, the rolled up aggregated metric is returned. 如果指标查询返回多个时间序列,则可以使用“Top”和“OrderBy”查询参数返回时间序列的有限排序列表。If a metric query returns multiple timeseries, then you can use the 'Top' and 'OrderBy' query parameters to return an limited ordered list of timeseries.

备注

若要使用 Azure Monitor REST API 检索多维指标值,请使用“2018-01-01”作为 API 版本。To retrieve multi-dimensional metric values using the Azure Monitor REST API, use "2018-01-01" as the API version.

方法:GETMethod: GET

请求 URIhttps://management.chinacloudapi.cn/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}Request URI: https://management.chinacloudapi.cn/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}

例如,若要在 5 分钟时间范围内按“事务”数降序值检索前 3 个 API,其中 GeotType 为 “Primary”,则请求将如下所示:For example, to retrieve the top 3 APIs, in descending value, by the number of 'Transactions' during a 5 min range, where the GeotType was 'Primary', the request would be as follows:

$filter = "APIName eq '*' and GeoType eq 'Primary'"
$request = "https://management.chinacloudapi.cn/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Storage/storageAccounts/ContosoStorage/providers/microsoft.insights/metrics?metricnames=Transactions&timespan=2018-03-01T02:00:00Z/2018-03-01T02:05:00Z&`$filter=${filter}&interval=PT1M&aggregation=Total&top=3&orderby=Total desc&api-version=2018-01-01"
Invoke-RestMethod -Uri $request `
    -Headers $authHeader `
    -Method Get `
    -OutFile ".\contosostorage-metric-values.json" `
    -Verbose

生成的 JSON 响应正文将类似于以下示例:The resulting JSON response body would be similar to the following example:

{
  "cost": 0,
  "timespan": "2018-03-01T02:00:00Z/2018-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": "2017-09-19T02:00:00Z",
              "total": 2
            },
            {
              "timeStamp": "2017-09-19T02:01:00Z",
              "total": 1
            },
            {
              "timeStamp": "2017-09-19T02:02:00Z",
              "total": 3
            },
            {
              "timeStamp": "2017-09-19T02:03:00Z",
              "total": 7
            },
            {
              "timeStamp": "2017-09-19T02:04:00Z",
              "total": 2
            }
          ]
        },
        ...
      ]
    }
  ],
  "namespace": "Microsoft.Storage/storageAccounts",
  "resourceregion": "chinanorth"
}

检索指标定义Retrieve metric definitions

使用 Azure Monitor 指标定义 REST API 可以访问服务可用的指标列表。Use the Azure Monitor Metric definitions REST API to access the list of metrics that are available for a service.

方法:GETMethod: GET

请求 URI:https://management.chinacloudapi.cn/subscriptions/ {subscriptionId} /resourceGroups/ {resourceGroupName} /providers/ {resourceProviderNamespace} / {resourceType} / {resourceName} /providers/microsoft.insights/metricDefinitions?api-version= {apiVersion}Request URI: https://management.chinacloudapi.cn/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}/providers/microsoft.insights/metricDefinitions?api-version={apiVersion}

例如,若要检索某个 Azure 逻辑应用的指标定义,请求将如下所示:For example, to retrieve the metric definitions for an Azure Logic App, the request would appear as follows:

$request = "https://management.chinacloudapi.cn/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Logic/workflows/ContosoTweets/providers/microsoft.insights/metricDefinitions?api-version=2016-03-01"

Invoke-RestMethod -Uri $request `
                  -Headers $authHeader `
                  -Method Get `
                  -OutFile ".\contosotweets-metricdef-results.json" `
                  -Verbose

备注

若要使用 Azure 监视器 REST API 检索指标定义,请使用“2016-03-01”作为 API 版本。To retrieve metric definitions using the Azure Monitor REST API, use "2016-03-01" as the API version.

生成的 JSON 响应正文将类似于以下示例:The resulting JSON response body would be similar to the following example:

{
  "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Logic/workflows/ContosoTweets/providers/microsoft.insights/metricdefinitions",
  "value": [
    {
      "name": {
        "value": "RunsStarted",
        "localizedValue": "Runs Started"
      },
      "category": "AllMetrics",
      "startTime": "0001-01-01T00:00:00Z",
      "endTime": "0001-01-01T00:00:00Z",
      "unit": "Count",
      "primaryAggregationType": "Total",
      "resourceUri": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Logic/workflows/ContosoTweets",
      "resourceId": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Logic/workflows/ContosoTweets",
      "metricAvailabilities": [
        {
          "timeGrain": "PT1M",
          "retention": "P30D",
          "location": null,
          "blobLocation": null
        },
        {
          "timeGrain": "PT1H",
          "retention": "P30D",
          "location": null,
          "blobLocation": null
        }
      ],
      "properties": null,
      "dimensions": null,
      "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Logic/workflows/ContosoTweets/providers/microsoft.insights/metricdefinitions/RunsStarted",
      "supportedAggregationTypes": [ "None", "Average", "Minimum", "Maximum", "Total", "Count" ]
    }
  ]
}

有关详细信息,请参阅 List the metric definitions for a resource in Azure Monitor REST API(在 Azure Monitor REST API 中列出资源的指标定义)文档。For more information, see the List the metric definitions for a resource in Azure Monitor REST API documentation.

检索指标值Retrieve metric values

知道可用的指标定义后,即可检索相关的指标值。Once the available metric definitions are known, it is then possible to retrieve the related metric values. 将指标的名称“value”(而不是“localizedValue”)用于任何筛选请求(例如,检索“CpuTime”和“Requests”指标数据点)。Use the metric’s name ‘value’ (not the ‘localizedValue’) for any filtering requests (for example, retrieve the ‘CpuTime’ and ‘Requests’ metric data points). 如果未指定筛选器,则返回默认指标。If no filters are specified, the default metric is returned.

备注

若要使用 Azure Monitor REST API 检索指标值,请使用“2016-09-01”作为 API 版本。To retrieve metric values using the Azure Monitor REST API, use "2016-09-01" as the API version.

方法:GETMethod: GET

请求 URIhttps:\//management.chinacloudapi.cn/subscriptions/\*{subscription-id}*/resourceGroups/*{resource-group-name}*/providers/*{resource-provider-namespace}*/*{resource-type}*/*{resource-name}*/providers/microsoft.insights/metrics?$filter=*{filter}*&api-version=*{apiVersion}*Request URI: https:\//management.chinacloudapi.cn/subscriptions/\*{subscription-id}*/resourceGroups/*{resource-group-name}*/providers/*{resource-provider-namespace}*/*{resource-type}*/*{resource-name}*/providers/microsoft.insights/metrics?$filter=*{filter}*&api-version=*{apiVersion}*

例如,要检索给定时间范围内时间粒度为 1 小时的 RunsSucceeded 指标数据点,请求将如下所示:For example, to retrieve the RunsSucceeded metric data points for the given time range and for a time grain of 1 hour, the request would be as follows:

$filter = "(name.value eq 'RunsSucceeded') and aggregationType eq 'Total' and startTime eq 2017-08-18T19:00:00 and endTime eq 2017-08-18T23:00:00 and timeGrain eq duration'PT1H'"
$request = "https://management.chinacloudapi.cn/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Logic/workflows/ContosoTweets/providers/microsoft.insights/metrics?`$filter=${filter}&api-version=2016-09-01"
Invoke-RestMethod -Uri $request `
    -Headers $authHeader `
    -Method Get `
    -OutFile ".\contosotweets-metrics-results.json" `
    -Verbose

生成的 JSON 响应正文将类似于以下示例:The resulting JSON response body would be similar to the following example:

{
  "value": [
    {
      "data": [
        {
          "timeStamp": "2017-08-18T19:00:00Z",
          "total": 0.0
        },
        {
          "timeStamp": "2017-08-18T20:00:00Z",
          "total": 159.0
        },
        {
          "timeStamp": "2017-08-18T21:00:00Z",
          "total": 174.0
        },
        {
          "timeStamp": "2017-08-18T22:00:00Z",
          "total": 97.0
        }
      ],
      "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Logic/workflows/ContosoTweets/providers/Microsoft.Insights/metrics/RunsSucceeded",
      "name": {
        "value": "RunsSucceeded",
        "localizedValue": "Runs Succeeded"
      },
      "type": "Microsoft.Insights/metrics",
      "unit": "Count"
    }
  ]
}

要检索多个数据点或聚合点,请将指标定义名称和聚合类型添加到筛选器,如以下示例中所示:To retrieve multiple data or aggregation points, add the metric definition names and aggregation types to the filter, as seen in the following example:

$filter = "(name.value eq 'ActionsCompleted' or name.value eq 'RunsSucceeded') and (aggregationType eq 'Total' or aggregationType eq 'Average') and startTime eq 2017-08-18T21:00:00 and endTime eq 2017-08-18T21:30:00 and timeGrain eq duration'PT1M'"
$request = "https://management.chinacloudapi.cn/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Logic/workflows/ContosoTweets/providers/microsoft.insights/metrics?`$filter=${filter}&api-version=2016-09-01"
Invoke-RestMethod -Uri $request `
    -Headers $authHeader `
    -Method Get `
    -OutFile ".\contosotweets-metrics-multiple-results.json" `
    -Verbose

生成的 JSON 响应正文将类似于以下示例:The resulting JSON response body would be similar to the following example:

{
  "value": [
    {
      "data": [
        {
          "timeStamp": "2017-08-18T21:03:00Z",
          "total": 5.0,
          "average": 1.0
        },
        {
          "timeStamp": "2017-08-18T21:04:00Z",
          "total": 7.0,
          "average": 1.0
        }
      ],
      "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Logic/workflows/ContosoTweets/providers/Microsoft.Insights/metrics/ActionsCompleted",
      "name": {
        "value": "ActionsCompleted",
        "localizedValue": "Actions Completed "
      },
      "type": "Microsoft.Insights/metrics",
      "unit": "Count"
    },
    {
      "data": [
        {
          "timeStamp": "2017-08-18T21:03:00Z",
          "total": 5.0,
          "average": 1.0
        },
        {
          "timeStamp": "2017-08-18T21:04:00Z",
          "total": 7.0,
          "average": 1.0
        }
      ],
      "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Logic/workflows/ContosoTweets/providers/Microsoft.Insights/metrics/RunsSucceeded",
      "name": {
        "value": "RunsSucceeded",
        "localizedValue": "Runs Succeeded"
      },
      "type": "Microsoft.Insights/metrics",
      "unit": "Count"
    }
  ]
}

使用 ARMClientUse ARMClient

另一种方法是使用 Windows 计算机上的 ARMClientAn additional approach is to use ARMClient on your Windows machine. ARMClient 将自动处理 Azure AD 身份验证(及生成的 JWT 令牌)。ARMClient handles the Azure AD authentication (and resulting JWT token) automatically. 以下步骤概述如何使用 ARMClient 检索指标数据:The following steps outline the use of ARMClient for retrieving metric data:

  1. 安装 ChocolateyARMClientInstall Chocolatey and ARMClient.
  2. 在终端窗口中,键入 armclient.exe loginIn a terminal window, type armclient.exe login. 这样做会提示登录到 Azure。Doing so prompts you to log in to Azure.
  3. 键入 armclient GET [your_resource_id]/providers/microsoft.insights/metricdefinitions?api-version=2016-03-01Type armclient GET [your_resource_id]/providers/microsoft.insights/metricdefinitions?api-version=2016-03-01
  4. 键入 armclient GET [your_resource_id]/providers/microsoft.insights/metrics?api-version=2016-09-01Type armclient GET [your_resource_id]/providers/microsoft.insights/metrics?api-version=2016-09-01

例如,若要检索特定逻辑应用的指标定义,请发出以下命令:For example, in order to retrieve the metric definitions for a specific Logic App, issue the following command:

armclient GET /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Logic/workflows/ContosoTweets/providers/microsoft.insights/metricDefinitions?api-version=2016-03-01

检索资源 IDRetrieve the resource ID

使用 REST API 确实有助于了解可用的指标定义、粒度和相关值。Using the REST API can really help to understand the available metric definitions, granularity, and related values. 使用 Azure 管理库时,这些信息很有用。That information is helpful when using the Azure Management Library.

对于上述代码,要使用的资源 ID 是所需 Azure 资源的完整路径。For the preceding code, the resource ID to use is the full path to the desired Azure resource. 例如,要针对某个 Azure Web 应用执行查询,资源 ID 将是:For example, to query against an Azure Web App, the resource ID would be:

/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/Microsoft.Web/sites/{site-name}//subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/Microsoft.Web/sites/{site-name}/

以下列表包含各种 Azure 资源的几个资源 ID 格式示例:The following list contains a few examples of resource ID formats for various Azure resources:

  • IoT 中心 - /subscriptions/ {subscription-id} /resourceGroups/ {resource-group-name} /providers/Microsoft.Devices/IotHubs/ {iot-hub-name}IoT Hub - /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}Elastic SQL Pool - /subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/Microsoft.Sql/servers/{pool-db}/elasticpools/{sql-pool-name}
  • SQL 数据库 (v12) - /subscriptions/ {subscription-id} /resourceGroups/ {resource-group-name} /providers/Microsoft.Sql/servers/ {server-name} /databases/ {database-name}SQL Database (v12) - /subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/Microsoft.Sql/servers/{server-name}/databases/{database-name}
  • 服务总线 - /subscriptions/ {subscription-id} /resourceGroups/ {resource-group-name} /providers/Microsoft.ServiceBus/ {namespace} / {servicebus-name}Service Bus - /subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/Microsoft.ServiceBus/{namespace}/{servicebus-name}
  • 虚拟机规模集 - /subscriptions/ {subscription-id} /resourceGroups/ {resource-group-name} /providers/Microsoft.Compute/virtualMachineScaleSets/ {vm-name}Virtual machine scale sets - /subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/Microsoft.Compute/virtualMachineScaleSets/{vm-name}
  • VM - /subscriptions/ {subscription-id} /resourceGroups/ {resource-group-name} /providers/Microsoft.Compute/virtualMachines/ {vm-name}VMs - /subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/Microsoft.Compute/virtualMachines/{vm-name}
  • 事件中心 - /subscriptions/ {subscription-id} /resourceGroups/ {resource-group-name} /providers/Microsoft.EventHub/namespaces/ {eventhub-namespace}Event Hubs - /subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/Microsoft.EventHub/namespaces/{eventhub-namespace}

还可以通过其他方法检索资源 ID,包括使用 Azure 资源浏览器,以及通过 Azure 门户、PowerShell 或 Azure CLI 查看所需的资源。There are alternative approaches to retrieving the resource ID, including using Azure Resource Explorer, viewing the desired resource in the Azure portal, and via PowerShell or the Azure CLI.

Azure 资源浏览器Azure Resource Explorer

若要查找所需资源的资源 ID,一种有效的方法是使用 Azure 资源浏览器工具。To find the resource ID for a desired resource, one helpful approach is to use the Azure Resource Explorer tool. 导航到所需的资源,并查看如以下屏幕截图中所示的 ID:Navigate to the desired resource and then look at the ID shown, as in the following screenshot:

Alt "Azure 资源浏览器"

Azure 门户Azure portal

还可以从 Azure 门户获取资源 ID。The resource ID can also be obtained from the Azure portal. 为此,请导航到所需的资源,并选择“属性”。To do so, navigate to the desired resource and then select Properties. 资源 ID 将显示在“属性”部分中,如以下屏幕截图中所示:The Resource ID is displayed in the Properties section, as seen in the following screenshot:

Alt "Azure 门户的“属性”边栏选项卡中显示的资源 ID"

Azure PowerShellAzure PowerShell

也可以使用 Azure PowerShell cmdlet 检索资源 ID。The resource ID can be retrieved using Azure PowerShell cmdlets as well. 例如,若要获取某个 Azure 逻辑应用的资源 ID,请执行 Get-AzureLogicApp cmdlet,如以下示例中所示:For example, to obtain the resource ID for an Azure Logic App, execute the Get-AzureLogicApp cmdlet, as in the following example:

Get-AzLogicApp -ResourceGroupName azmon-rest-api-walkthrough -Name contosotweets

结果应类似于以下示例:The result should be similar to the following example:

Id             : /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Logic/workflows/ContosoTweets
Name           : ContosoTweets
Type           : Microsoft.Logic/workflows
Location       : chinanorth
ChangedTime    : 8/21/2017 6:58:57 PM
CreatedTime    : 8/18/2017 7:54:21 PM
AccessEndpoint : https://prod-08.chinanorth.logic.chinacloudapi.cn:443/workflows/f3a91b352fcc47e6bff989b85446c5db
State          : Enabled
Definition     : {$schema, contentVersion, parameters, triggers...}
Parameters     : {[$connections, Microsoft.Azure.Management.Logic.Models.WorkflowParameter]}
SkuName        :
AppServicePlan :
PlanType       :
PlanId         :
Version        : 08586982649483762729

Azure CLIAzure CLI

若要使用 Azure CLI 检索某个 Azure 存储帐户的资源 ID,请执行 az storage account show 命令,如以下示例中所示:To retrieve the resource ID for an Azure Storage account using the Azure CLI, execute the az storage account show command, as shown in the following example:

az storage account show -g azmon-rest-api-walkthrough -n contosotweets2017

结果应类似于以下示例:The result should be similar to the following example:

{
  "accessTier": null,
  "creationTime": "2017-08-18T19:58:41.840552+00:00",
  "customDomain": null,
  "enableHttpsTrafficOnly": false,
  "encryption": null,
  "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Storage/storageAccounts/contosotweets2017",
  "identity": null,
  "kind": "Storage",
  "lastGeoFailoverTime": null,
  "location": "chinanorth",
  "name": "contosotweets2017",
  "networkAcls": null,
  "primaryEndpoints": {
    "blob": "https://contosotweets2017.blob.core.chinacloudapi.cn/",
    "file": "https://contosotweets2017.file.core.chinacloudapi.cn/",
    "queue": "https://contosotweets2017.queue.core.chinacloudapi.cn/",
    "table": "https://contosotweets2017.table.core.chinacloudapi.cn/"
  },
  "primaryLocation": "chinanorth",
  "provisioningState": "Succeeded",
  "resourceGroup": "azmon-rest-api-walkthrough",
  "secondaryEndpoints": null,
  "secondaryLocation": "chinanorth2",
  "sku": {
    "name": "Standard_GRS",
    "tier": "Standard"
  },
  "statusOfPrimary": "available",
  "statusOfSecondary": "available",
  "tags": {},
  "type": "Microsoft.Storage/storageAccounts"
}

备注

Azure 逻辑应用尚不能通过 Azure CLI 获取,因此,前面的示例中显示了一个 Azure 存储帐户。Azure Logic Apps are not yet available via the Azure CLI, thus an Azure Storage account is shown in the preceding example.

检索活动日志数据Retrieve activity log data

除了指标定义和相关值以外,还可以使用 Azure Monitor REST API 检索有关 Azure 资源的其他需关注的深入信息。In addition to metric definitions and related values, it is also possible to use the Azure Monitor REST API to retrieve additional interesting insights related to Azure resources. 例如,可查询活动日志数据。As an example, it is possible to query activity log data. 以下示例请求使用 Azure Monitor REST API 查询活动日志。The following sample requests use the Azure Monitor REST API to query the activity log.

在有过滤器的情况下获取活动日志:Get Activity Logs with filter:

GET https://management.chinacloudapi.cn/subscriptions/089bd33f-d4ec-47fe-8ba5-0753aa5c5b33/providers/microsoft.insights/eventtypes/management/values?api-version=2015-04-01&$filter=eventTimestamp ge '2018-01-21T20:00:00Z' and eventTimestamp le '2018-01-23T20:00:00Z' and resourceGroupName eq 'MSSupportGroup'

在有过滤器的情况下获取活动日志,然后选择:Get Activity Logs with filter and select:

GET https://management.chinacloudapi.cn/subscriptions/089bd33f-d4ec-47fe-8ba5-0753aa5c5b33/providers/microsoft.insights/eventtypes/management/values?api-version=2015-04-01&$filter=eventTimestamp ge '2015-01-21T20:00:00Z' and eventTimestamp le '2015-01-23T20:00:00Z' and resourceGroupName eq 'MSSupportGroup'&$select=eventName,id,resourceGroupName,resourceProviderName,operationName,status,eventTimestamp,correlationId,submissionTimestamp,level

获取活动日志且选择:Get Activity Logs with select:

GET https://management.chinacloudapi.cn/subscriptions/089bd33f-d4ec-47fe-8ba5-0753aa5c5b33/providers/microsoft.insights/eventtypes/management/values?api-version=2015-04-01&$select=eventName,id,resourceGroupName,resourceProviderName,operationName,status,eventTimestamp,correlationId,submissionTimestamp,level

在没有过滤器的情况下获取活动日志,或选择:Get Activity Logs without filter or select:

GET https://management.chinacloudapi.cn/subscriptions/089bd33f-d4ec-47fe-8ba5-0753aa5c5b33/providers/microsoft.insights/eventtypes/management/values?api-version=2015-04-01

后续步骤Next steps