MetricsClient Class

MetricsClient Paul should be used for performing metrics queries on multiple monitored resources in the same region. A credential with authorization at the subscription level is required when using this client.

Constructor

MetricsClient(endpoint: str, credential: TokenCredential, **kwargs: Any)

Parameters

Name Description
endpoint
Required
str

The regional endpoint to use, for example https://eastus.metrics.monitor.azure.com. The region should match the region of the requested resources. For global resources, the region should be 'global'. Required.

credential
Required

The credential to authenticate the client.

Keyword-Only Parameters

Name Description
audience
str

The audience to use when requesting tokens for Microsoft Entra ID. Defaults to the public cloud audience (https://metrics.monitor.azure.com).

api_version
str

The API version to use for this operation. Default value is "2024-02-01". Note that overriding this default value may result in unsupported behavior.

Examples

Creating the MetricsClient for use with a sovereign cloud (i.e. non-public cloud).


   from azure.identity import AzureAuthorityHosts, DefaultAzureCredential
   from azure.monitor.querymetrics import MetricsClient

   credential = DefaultAzureCredential(authority=AzureAuthorityHosts.AZURE_GOVERNMENT)
   client = MetricsClient(
       "https://usgovvirginia.metrics.monitor.azure.us",
       credential,
       audience="https://metrics.monitor.azure.us",
   )

Methods

close
query_resources

Lists the metric values for multiple resources.

send_request

Runs the network request through the client's chained policies.


>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest("GET", "https://www.example.org/")
<HttpRequest [GET], url: 'https://www.example.org/'>
>>> response = client.send_request(request)
<HttpResponse: 200 OK>

For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request

close

close() -> None

query_resources

Lists the metric values for multiple resources.

query_resources(*, resource_ids: Sequence[str], metric_namespace: str, metric_names: Sequence[str], timespan: timedelta | Tuple[datetime, timedelta] | Tuple[datetime, datetime] | None = None, granularity: timedelta | None = None, aggregations: Sequence[MetricAggregationType | str] | None = None, max_results: int | None = None, order_by: str | None = None, filter: str | None = None, roll_up_by: str | None = None, **kwargs: Any) -> List[MetricsQueryResult]

Keyword-Only Parameters

Name Description
resource_ids

A list of resource IDs to query metrics for. Required.

metric_namespace
str

Metric namespace that contains the requested metric names. Required.

metric_names

The names of the metrics to retrieve. Required.

timespan

The timespan for which to query the data. This can be a timedelta, a tuple of a start datetime with timedelta, or a tuple with start and end datetimes.

Default value: None
granularity

The granularity (i.e. timegrain) of the query.

Default value: None
aggregations

The list of aggregation types to retrieve. Use azure.monitor.querymetrics.MetricAggregationType enum to get each aggregation type.

Default value: None
max_results

The maximum number of records to retrieve. Valid only if 'filter' is specified. Defaults to 10.

Default value: None
order_by

The aggregation to use for sorting results and the direction of the sort. Only one order can be specified. Examples: 'sum asc', 'maximum desc'.

Default value: None
filter
str

The filter is used to reduce the set of metric data returned. Default value is None.

Example: Metric contains metadata A, B and C.

  • Return all time series of C where A = a1 and B = b1 or b2:

    filter="A eq 'a1' and B eq 'b1' or B eq 'b2' and C eq '*'"

  • Invalid variant:

    filter="A eq 'a1' and B eq 'b1' and C eq '*' or B = 'b2'". This is invalid because the logical 'or' operator cannot separate two different metadata names.

  • Return all time series where A = a1, B = b1 and C = c1:

    filter="A eq 'a1' and B eq 'b1' and C eq 'c1'"

  • Return all time series where A = a1:

    filter="A eq 'a1' and B eq '' and C eq ''"

  • Special case: When dimension name or dimension value uses round brackets. Example: When dimension name is dim (test) 1, instead of using filter="dim (test) 1 eq '*'" use filter="dim %2528test%2529 1 eq '*'".

    When dimension name is dim (test) 3 and dimension value is dim3 (test) val, instead of using filter="dim (test) 3 eq 'dim3 (test) val'", use filter="dim %2528test%2529 3 eq 'dim3 %2528test%2529 val'".

Default value: None
roll_up_by
str

Dimension name(s) to rollup results by. For example if you only want to see metric values with a filter like 'City eq Seattle or City eq Tacoma' but don't want to see separate values for each city, you can specify 'City' to see the results for Seattle and Tacoma rolled up into one timeseries.

Default value: None

Returns

Type Description

A list of MetricsQueryResult objects.

Exceptions

Type Description

Examples

Get a response for a batch metrics query.


   from datetime import timedelta
   import os

   from azure.core.exceptions import HttpResponseError
   from azure.identity import DefaultAzureCredential
   from azure.monitor.querymetrics import MetricsClient, MetricAggregationType


   endpoint = os.environ["AZURE_METRICS_ENDPOINT"]

   credential = DefaultAzureCredential()
   client = MetricsClient(endpoint, credential)

   resource_ids = [
       "/subscriptions/<id>/resourceGroups/<rg>/providers/Microsoft.Storage/storageAccounts/<account-1>",
       "/subscriptions/<id>/resourceGroups/<rg>/providers/Microsoft.Storage/storageAccounts/<account-2>",
   ]

   try:
       response = client.query_resources(
           resource_ids=resource_ids,
           metric_namespace="Microsoft.Storage/storageAccounts",
           metric_names=["Ingress"],
           timespan=timedelta(hours=2),
           granularity=timedelta(minutes=5),
           aggregations=[MetricAggregationType.AVERAGE],
       )

       for metrics_query_result in response:
           for metric in metrics_query_result.metrics:
               print(metric.name + " -- " + metric.display_description)
               for time_series_element in metric.timeseries:
                   for metric_value in time_series_element.data:
                       print("The ingress at {} is {}".format(metric_value.timestamp, metric_value.average))
   except HttpResponseError as err:
       print("something fatal happened")
       print(err)

send_request

Runs the network request through the client's chained policies.


>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest("GET", "https://www.example.org/")
<HttpRequest [GET], url: 'https://www.example.org/'>
>>> response = client.send_request(request)
<HttpResponse: 200 OK>

For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request

send_request(request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse

Parameters

Name Description
request
Required

The network request you want to make. Required.

Keyword-Only Parameters

Name Description
stream

Whether the response payload will be streamed. Defaults to False.

Default value: False

Returns

Type Description

The response of your network call. Does not do error handling on your response.