Skip to content

Commit 011a618

Browse files
pvaneckCopilot
andauthored
[Monitor Metrics] Add samples (#42242)
Signed-off-by: Paul Van Eck <[email protected]> Co-authored-by: Copilot <[email protected]>
1 parent 9c7455d commit 011a618

File tree

11 files changed

+357
-10
lines changed

11 files changed

+357
-10
lines changed
Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,25 @@
11
# Release History
22

3-
## 1.0.0 (Unreleased)
3+
## 1.0.0 (2025-07-28)
44

55
### Features Added
66

7-
- Initial release. This version includes the core functionality for querying metrics from Azure Monitor using the `MetricsClient`, which was originally introduced in the `azure-monitor-query` package.
7+
- **Initial release** of `azure-monitor-querymetrics` package with core Azure Monitor metrics querying functionality.
8+
- Includes the `MetricsClient` for querying metrics from Azure Monitor resources.
89

9-
### Breaking Changes
10+
**Migration from azure-monitor-query**
1011

11-
### Bugs Fixed
12+
This package extracts the metrics functionality from the `azure-monitor-query` package to provide a focused solution for metrics querying.
1213

13-
### Other Changes
14+
**For existing users of `MetricsClient`:**
15+
- Migration is straightforward - only import paths need to be updated.
16+
- The API surface remains unchanged.
17+
- **Before:** `from azure.monitor.query import MetricsClient`
18+
- **After:** `from azure.monitor.querymetrics import MetricsClient`
19+
20+
**For users of `MetricsQueryClient`:**
21+
- This functionality is **not included** in this package.
22+
- **Recommended alternative:** Use `MonitorManagementClient` from the `azure-mgmt-monitor` package.
23+
- The management client provides comprehensive Azure Monitor resource management capabilities.
24+
25+
For more details, see the [migration guide](https://aka.ms/azsdk/python/monitor/query/migration).

sdk/monitor/azure-monitor-querymetrics/README.md

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,19 @@
11
# Azure Monitor Query Metrics client library for Python
22

3-
The Azure Monitor Query Metrics client library is used to execute read-only queries against [Azure Monitor][azure_monitor_overview]'s metrics data platform:
3+
The Azure Monitor Query Metrics client library enables you to perform read-only queries against [Azure Monitor][azure_monitor_overview]'s metrics data platform. It is designed for retrieving numerical metrics from Azure resources, supporting scenarios such as monitoring, alerting, and troubleshooting.
44

5-
- [Metrics](https://learn.microsoft.com/azure/azure-monitor/essentials/data-platform-metrics) - Collects numeric data from monitored resources into a time series database. Metrics are numerical values that are collected at regular intervals and describe some aspect of a system at a particular time. Metrics are lightweight and capable of supporting near real-time scenarios, making them useful for alerting and fast detection of issues.
5+
- [Metrics](https://learn.microsoft.com/azure/azure-monitor/essentials/data-platform-metrics): Numeric data collected from resources at regular intervals, stored as time series. Metrics provide insights into resource health and performance, and are optimized for near real-time analysis.
6+
7+
This library interacts with the Azure Monitor Metrics Data Plane API, allowing you to query metrics for multiple resources in a single request. For details on batch querying, see [Batch API migration guide](https://learn.microsoft.com/azure/azure-monitor/metrics/migrate-to-batch-api?tabs=individual-response).
68

79
**Resources:**
810

9-
<!-- TODO: Add PyPI, Conda, Ref Docs, Samples links-->
11+
<!-- TODO: Add Conda-->
1012
- [Source code][source]
13+
- [Package (PyPI)][package]
14+
- [API reference documentation][python-querymetrics-ref-docs]
1115
- [Service documentation][azure_monitor_overview]
16+
- [Samples][samples]
1217
- [Change log][changelog]
1318

1419
## Getting started
@@ -238,8 +243,10 @@ This project has adopted the [Microsoft Open Source Code of Conduct][code_of_con
238243
[azure_subscription]: https://azure.microsoft.com/free/python/
239244
[changelog]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/monitor/azure-monitor-querymetrics/CHANGELOG.md
240245
[metric_namespaces]: https://learn.microsoft.com/azure/azure-monitor/reference/supported-metrics/metrics-index#supported-metrics-and-log-categories-by-resource-type
246+
[package]: https://aka.ms/azsdk-python-monitor-querymetrics-pypi
241247
[pip]: https://pypi.org/project/pip/
242248
[python_logging]: https://docs.python.org/3/library/logging.html
249+
[python-querymetrics-ref-docs]: https://aka.ms/azsdk/python/querymetrics/docs
243250
[samples]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/monitor/azure-monitor-querymetrics/samples
244251
[source]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/monitor/azure-monitor-querymetrics/
245252
[troubleshooting_guide]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/monitor/azure-monitor-querymetrics/TROUBLESHOOTING.md

sdk/monitor/azure-monitor-querymetrics/TROUBLESHOOTING.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ client.query_workspace(logging_enable=True)
4848

4949
### Authentication errors
5050

51-
Azure Monitor Query Metrics supports Azure Active Directory authentication. The MetricsClient has methods to set the `credential`. To provide a valid credential, you can use
51+
Azure Monitor Query Metrics supports Microsoft Entra ID authentication. The MetricsClient has methods to set the `credential`. To provide a valid credential, you can use
5252
`azure-identity` dependency. For more details on getting started, refer to
5353
the [README](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/monitor/azure-monitor-querymetrics#create-the-client)
5454
of Azure Monitor Query Metrics library. You can also refer to

sdk/monitor/azure-monitor-querymetrics/azure/monitor/querymetrics/_patch.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,24 @@ class MetricsClient(GeneratedClient):
5151
:keyword api_version: The API version to use for this operation. Default value is "2024-02-01".
5252
Note that overriding this default value may result in unsupported behavior.
5353
:paramtype api_version: str
54+
55+
.. admonition:: Example:
56+
57+
.. literalinclude:: ../samples/sample_authentication.py
58+
:start-after: [START create_metrics_client]
59+
:end-before: [END create_metrics_client]
60+
:language: python
61+
:dedent: 4
62+
:caption: Creating the MetricsClient with a credential.
63+
64+
.. admonition:: Example:
65+
66+
.. literalinclude:: ../samples/sample_authentication.py
67+
:start-after: [START create_metrics_client_sovereign_cloud]
68+
:end-before: [END create_metrics_client_sovereign_cloud]
69+
:language: python
70+
:dedent: 4
71+
:caption: Creating the MetricsClient for use with a sovereign cloud (i.e. non-public cloud).
5472
"""
5573

5674
def __init__(self, endpoint: str, credential: "TokenCredential", **kwargs: Any) -> None:
@@ -140,6 +158,14 @@ def query_resources(
140158
:return: A list of MetricsQueryResult objects.
141159
:rtype: list[~azure.monitor.querymetrics.MetricsQueryResult]
142160
:raises ~azure.core.exceptions.HttpResponseError:
161+
162+
.. admonition:: Example:
163+
164+
.. literalinclude:: ../samples/sample_metrics_query.py
165+
:start-after: [START send_metrics_batch_query]
166+
:end-before: [END send_metrics_batch_query]
167+
:language: python
168+
:caption: Get a response for a batch metrics query.
143169
"""
144170
if not resource_ids:
145171
raise ValueError("'resource_ids' must be provided and must not be empty.")

sdk/monitor/azure-monitor-querymetrics/azure/monitor/querymetrics/aio/_patch.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,24 @@ class MetricsClient(GeneratedClient):
4646
:keyword api_version: The API version to use for this operation. Default value is "2024-02-01".
4747
Note that overriding this default value may result in unsupported behavior.
4848
:paramtype api_version: str
49+
50+
.. admonition:: Example:
51+
52+
.. literalinclude:: ../samples/sample_authentication_async.py
53+
:start-after: [START create_metrics_client_async]
54+
:end-before: [END create_metrics_client_async]
55+
:language: python
56+
:dedent: 4
57+
:caption: Creating the asynchronous MetricsClient with a credential.
58+
59+
.. admonition:: Example:
60+
61+
.. literalinclude:: ../samples/sample_authentication_async.py
62+
:start-after: [START create_metrics_client_sovereign_cloud_async]
63+
:end-before: [END create_metrics_client_sovereign_cloud_async]
64+
:language: python
65+
:dedent: 4
66+
:caption: Creating the MetricsClient for use with a sovereign cloud (i.e. non-public cloud).
4967
"""
5068

5169
def __init__(self, endpoint: str, credential: "AsyncTokenCredential", **kwargs: Any) -> None:
@@ -135,6 +153,14 @@ async def query_resources(
135153
:return: A list of MetricsQueryResult objects.
136154
:rtype: list[~azure.monitor.querymetrics.MetricsQueryResult]
137155
:raises ~azure.core.exceptions.HttpResponseError:
156+
157+
.. admonition:: Example:
158+
159+
.. literalinclude:: ../samples/sample_metrics_query_async.py
160+
:start-after: [START send_metrics_batch_query_async]
161+
:end-before: [END send_metrics_batch_query_async]
162+
:language: python
163+
:caption: Get a response for a batch metrics query.
138164
"""
139165
if not resource_ids:
140166
raise ValueError("'resource_ids' must be provided and must not be empty.")
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
---
2+
page_type: sample
3+
languages:
4+
- python
5+
products:
6+
- azure
7+
- azure-monitor
8+
urlFragment: querymetrics-azuremonitor-samples
9+
---
10+
11+
# Azure Monitor Query Metrics client library Python samples
12+
13+
## Samples
14+
15+
The following code samples show common scenarios with the Azure Monitor Query Metrics client library.
16+
17+
For examples on authenticating with the Azure Monitor service, see [sample_authentication.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/monitor/azure-monitor-querymetrics/samples/sample_authentication.py) and [sample_authentication_async.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/monitor/azure-monitor-querymetrics/samples/sample_authentication_async.py).
18+
19+
### Metrics query samples
20+
21+
- [Send a query to resources using MetricsClient](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/monitor/azure-monitor-querymetrics/samples/sample_metrics_query.py) ([async sample](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/monitor/azure-monitor-querymetrics/samples/sample_metrics_query_async.py))
22+
23+
## Prerequisites
24+
25+
- Python 3.9 or later
26+
- An [Azure subscription][azure_subscription]
27+
- Authorization to read metrics data at the Azure subscription level. For example, the [Monitoring Reader role](https://learn.microsoft.com/azure/role-based-access-control/built-in-roles/monitor#monitoring-reader) on the subscription containing the resources to be queried.
28+
- Azure resource of any kind (Storage Account, Key Vault, Cosmos DB, etc.).
29+
30+
## Setup
31+
32+
1. Install the latest version of the Azure Monitor Query Metrics library:
33+
34+
```bash
35+
pip install azure-monitor-querymetrics
36+
```
37+
38+
2. Clone or download this sample repository.
39+
3. Open the *samples* folder in Visual Studio Code or your IDE of choice.
40+
4. To run the samples, you need `azure-identity`.
41+
42+
```bash
43+
pip install azure-identity
44+
```
45+
46+
5. To run the async samples, you need an asynchronous HTTP framework like `aiohttp`:
47+
48+
```bash
49+
pip install aiohttp
50+
```
51+
52+
## Run the samples
53+
54+
1. Open a terminal window and `cd` to the directory that the samples are saved in.
55+
2. Set the environment variables specified in the sample file you wish to run.
56+
3. Follow the usage described in the file. For example, `python sample_metrics_query.py`.
57+
58+
## Next steps
59+
60+
To learn more about Azure Monitor, see the [Azure Monitor service documentation](https://learn.microsoft.com/azure/azure-monitor/).
61+
62+
<!-- LINKS -->
63+
64+
[azure_subscription]: https://azure.microsoft.com/free/python/
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# Copyright (c) Microsoft Corporation. All rights reserved.
2+
# Licensed under the MIT License.
3+
"""
4+
FILE: sample_authentication.py
5+
DESCRIPTION:
6+
This sample demonstrates how to authenticate to the Azure Monitor service using MetricsClient.
7+
USAGE:
8+
python sample_authentication.py
9+
10+
This example uses DefaultAzureCredential, which requests a token from Microsoft Entra ID.
11+
For more information on DefaultAzureCredential, see https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#defaultazurecredential.
12+
"""
13+
14+
15+
def create_metrics_client():
16+
# [START create_metrics_client]
17+
from azure.identity import DefaultAzureCredential
18+
from azure.monitor.querymetrics import MetricsClient
19+
20+
credential = DefaultAzureCredential()
21+
client = MetricsClient("https://eastus.metrics.monitor.azure.com", credential)
22+
# [END create_metrics_client]
23+
24+
25+
def create_metrics_client_sovereign_cloud():
26+
# [START create_metrics_client_sovereign_cloud]
27+
from azure.identity import AzureAuthorityHosts, DefaultAzureCredential
28+
from azure.monitor.querymetrics import MetricsClient
29+
30+
credential = DefaultAzureCredential(authority=AzureAuthorityHosts.AZURE_GOVERNMENT)
31+
client = MetricsClient(
32+
"https://usgovvirginia.metrics.monitor.azure.us",
33+
credential,
34+
audience="https://metrics.monitor.azure.us",
35+
)
36+
# [END create_metrics_client_sovereign_cloud]
37+
38+
39+
if __name__ == "__main__":
40+
create_metrics_client()
41+
create_metrics_client_sovereign_cloud()
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Copyright (c) Microsoft Corporation. All rights reserved.
2+
# Licensed under the MIT License.
3+
"""
4+
FILE: sample_authentication_async.py
5+
DESCRIPTION:
6+
This sample demonstrates how to authenticate to the Azure Monitor service using MetricsClient.
7+
USAGE:
8+
python sample_authentication_async.py
9+
10+
This example uses DefaultAzureCredential, which requests a token from Microsoft Entra ID.
11+
For more information on DefaultAzureCredential, see https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#defaultazurecredential.
12+
"""
13+
import asyncio
14+
15+
16+
async def create_metrics_client_async():
17+
# [START create_metrics_client_async]
18+
from azure.identity.aio import DefaultAzureCredential
19+
from azure.monitor.querymetrics.aio import MetricsClient
20+
21+
credential = DefaultAzureCredential()
22+
client = MetricsClient("https://eastus.metrics.monitor.azure.com", credential)
23+
# [END create_metrics_client_async]
24+
25+
26+
async def create_metrics_client_sovereign_cloud_async():
27+
# [START create_metrics_client_sovereign_cloud_async]
28+
from azure.identity import AzureAuthorityHosts
29+
from azure.identity.aio import DefaultAzureCredential
30+
from azure.monitor.querymetrics.aio import MetricsClient
31+
32+
credential = DefaultAzureCredential(authority=AzureAuthorityHosts.AZURE_GOVERNMENT)
33+
client = MetricsClient(
34+
"https://usgovvirginia.metrics.monitor.azure.us",
35+
credential,
36+
audience="https://metrics.monitor.azure.us",
37+
)
38+
# [END create_metrics_client_sovereign_cloud_async]
39+
40+
41+
async def main():
42+
await create_metrics_client_async()
43+
await create_metrics_client_sovereign_cloud_async()
44+
45+
46+
if __name__ == "__main__":
47+
asyncio.run(main())
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
# Copyright (c) Microsoft Corporation. All rights reserved.
2+
# Licensed under the MIT License.
3+
"""
4+
FILE: sample_metrics_query.py
5+
DESCRIPTION:
6+
This sample demonstrates authenticating the MetricsClient and retrieving the "Ingress"
7+
metric along with the "Average" aggregation type for multiple resources.
8+
The query will execute over a timespan of 2 hours with a granularity of 5 minutes.
9+
USAGE:
10+
python sample_metrics_query.py
11+
1) AZURE_METRICS_ENDPOINT - The regional metrics endpoint to use (i.e. https://westus3.metrics.monitor.azure.com)
12+
13+
This example uses DefaultAzureCredential, which requests a token from Microsoft Entra ID.
14+
For more information on DefaultAzureCredential, see https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#defaultazurecredential.
15+
16+
In this example, storage account resources are queried for metrics.
17+
"""
18+
19+
# [START send_metrics_batch_query]
20+
from datetime import timedelta
21+
import os
22+
23+
from azure.core.exceptions import HttpResponseError
24+
from azure.identity import DefaultAzureCredential
25+
from azure.monitor.querymetrics import MetricsClient, MetricAggregationType
26+
27+
28+
endpoint = os.environ["AZURE_METRICS_ENDPOINT"]
29+
30+
credential = DefaultAzureCredential()
31+
client = MetricsClient(endpoint, credential)
32+
33+
resource_ids = [
34+
"/subscriptions/<id>/resourceGroups/<rg>/providers/Microsoft.Storage/storageAccounts/<account-1>",
35+
"/subscriptions/<id>/resourceGroups/<rg>/providers/Microsoft.Storage/storageAccounts/<account-2>",
36+
]
37+
38+
try:
39+
response = client.query_resources(
40+
resource_ids=resource_ids,
41+
metric_namespace="Microsoft.Storage/storageAccounts",
42+
metric_names=["Ingress"],
43+
timespan=timedelta(hours=2),
44+
granularity=timedelta(minutes=5),
45+
aggregations=[MetricAggregationType.AVERAGE],
46+
)
47+
48+
for metrics_query_result in response:
49+
for metric in metrics_query_result.metrics:
50+
print(metric.name + " -- " + metric.display_description)
51+
for time_series_element in metric.timeseries:
52+
for metric_value in time_series_element.data:
53+
print("The ingress at {} is {}".format(metric_value.timestamp, metric_value.average))
54+
except HttpResponseError as err:
55+
print("something fatal happened")
56+
print(err)
57+
# [END send_metrics_batch_query]

0 commit comments

Comments
 (0)