|
| 1 | +# Azure Monitor Query Metrics client library for Python |
| 2 | + |
| 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: |
| 4 | + |
| 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. |
| 6 | + |
| 7 | +**Resources:** |
| 8 | + |
| 9 | +<!-- TODO: Add PyPI, Conda, Ref Docs, Samples links--> |
| 10 | +- [Source code][source] |
| 11 | +- [Service documentation][azure_monitor_overview] |
| 12 | +- [Change log][changelog] |
| 13 | + |
| 14 | +## Getting started |
| 15 | + |
| 16 | +### Prerequisites |
| 17 | + |
| 18 | +- Python 3.9 or later |
| 19 | +- An [Azure subscription][azure_subscription] |
| 20 | +- 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. |
| 21 | +- An Azure resource of any kind (Storage Account, Key Vault, Cosmos DB, etc.). |
| 22 | + |
| 23 | +### Install the package |
| 24 | + |
| 25 | +Install the Azure Monitor Query Metrics client library for Python with [pip][pip]: |
| 26 | + |
| 27 | +```bash |
| 28 | +pip install azure-monitor-querymetrics |
| 29 | +``` |
| 30 | + |
| 31 | +### Create the client |
| 32 | + |
| 33 | +An authenticated client is required to query Metrics. The library includes both synchronous and asynchronous forms of the client. To authenticate, create an instance of a token credential. Use that instance when creating a `MetricsClient`. The following examples use `DefaultAzureCredential` from the [azure-identity](https://pypi.org/project/azure-identity/) package. |
| 34 | + |
| 35 | +#### Synchronous client |
| 36 | + |
| 37 | +Consider the following example, which creates a synchronous client for Metrics querying: |
| 38 | + |
| 39 | +```python |
| 40 | +from azure.identity import DefaultAzureCredential |
| 41 | +from azure.monitor.querymetrics import MetricsClient |
| 42 | + |
| 43 | +credential = DefaultAzureCredential() |
| 44 | +metrics_client = MetricsClient("https://<regional endpoint>", credential) |
| 45 | +``` |
| 46 | + |
| 47 | +#### Asynchronous client |
| 48 | + |
| 49 | +The asynchronous form of the client API is found in the `.aio`-suffixed namespace. For example: |
| 50 | + |
| 51 | +```python |
| 52 | +from azure.identity.aio import DefaultAzureCredential |
| 53 | +from azure.monitor.querymetrics.aio import MetricsClient |
| 54 | + |
| 55 | +credential = DefaultAzureCredential() |
| 56 | +async_metrics_client = MetricsClient("https://<regional endpoint>", credential) |
| 57 | +``` |
| 58 | + |
| 59 | +To use the asynchronous clients, you must also install an async transport, such as [aiohttp](https://pypi.org/project/aiohttp/). |
| 60 | + |
| 61 | +```sh |
| 62 | +pip install aiohttp |
| 63 | +``` |
| 64 | + |
| 65 | +#### Configure client for Azure sovereign cloud |
| 66 | + |
| 67 | +By default, the client is configured to use the Azure public cloud. To use a sovereign cloud, provide the correct `audience` argument when creating the `MetricsClient`. For example: |
| 68 | + |
| 69 | +```python |
| 70 | +from azure.identity import AzureAuthorityHosts, DefaultAzureCredential |
| 71 | +from azure.monitor.querymetrics import MetricsClient |
| 72 | + |
| 73 | +# Authority can also be set via the AZURE_AUTHORITY_HOST environment variable. |
| 74 | +credential = DefaultAzureCredential(authority=AzureAuthorityHosts.AZURE_GOVERNMENT) |
| 75 | + |
| 76 | +metrics_client = MetricsClient( |
| 77 | + "https://usgovvirginia.metrics.monitor.azure.us", credential, audience="https://metrics.monitor.azure.us" |
| 78 | +) |
| 79 | +``` |
| 80 | + |
| 81 | +### Execute the query |
| 82 | + |
| 83 | +For examples of Metrics queries, see the [Examples](#examples) section. |
| 84 | + |
| 85 | +## Key concepts |
| 86 | + |
| 87 | +### Metrics data structure |
| 88 | + |
| 89 | +Each set of metric values is a time series with the following characteristics: |
| 90 | + |
| 91 | +- The time the value was collected |
| 92 | +- The resource associated with the value |
| 93 | +- A namespace that acts like a category for the metric |
| 94 | +- A metric name |
| 95 | +- The value itself |
| 96 | +- Some metrics have multiple dimensions as described in multi-dimensional metrics. |
| 97 | + |
| 98 | +## Examples |
| 99 | + |
| 100 | +- [Metrics query](#metrics-query) |
| 101 | + - [Handle metrics query response](#handle-metrics-query-response) |
| 102 | + |
| 103 | +### Metrics query |
| 104 | + |
| 105 | +To query metrics for one or more Azure resources, use the `query_resources` method of `MetricsClient`. This method requires a regional endpoint when creating the client. For example, "https://westus3.metrics.monitor.azure.com". |
| 106 | + |
| 107 | +Each Azure resource must reside in: |
| 108 | + |
| 109 | +- The same region as the endpoint specified when creating the client. |
| 110 | +- The same Azure subscription. |
| 111 | + |
| 112 | +The resource IDs must be that of the resources for which metrics are being queried. It's normally of the format `/subscriptions/<id>/resourceGroups/<rg-name>/providers/<source>/topics/<resource-name>`. |
| 113 | + |
| 114 | +To find the resource ID/URI: |
| 115 | + |
| 116 | +1. Navigate to your resource's page in the Azure portal. |
| 117 | +1. Select the **JSON View** link in the **Overview** section. |
| 118 | +1. Copy the value in the **Resource ID** text box at the top of the JSON view. |
| 119 | + |
| 120 | +Furthermore: |
| 121 | + |
| 122 | +- The user must be authorized to read monitoring 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 to be queried. |
| 123 | +- The metric namespace containing the metrics to be queried must be provided. For a list of metric namespaces, see [Supported metrics and log categories by resource type][metric_namespaces]. |
| 124 | + |
| 125 | +```python |
| 126 | +from datetime import timedelta |
| 127 | +import os |
| 128 | + |
| 129 | +from azure.core.exceptions import HttpResponseError |
| 130 | +from azure.identity import DefaultAzureCredential |
| 131 | +from azure.monitor.querymetrics import MetricsClient, MetricAggregationType |
| 132 | + |
| 133 | +endpoint = "https://westus3.metrics.monitor.azure.com" |
| 134 | +credential = DefaultAzureCredential() |
| 135 | +client = MetricsClient(endpoint, credential) |
| 136 | + |
| 137 | +resource_ids = [ |
| 138 | + "/subscriptions/<id>/resourceGroups/<rg-name>/providers/<source>/storageAccounts/<resource-name-1>", |
| 139 | + "/subscriptions/<id>/resourceGroups/<rg-name>/providers/<source>/storageAccounts/<resource-name-2>" |
| 140 | +] |
| 141 | + |
| 142 | +response = client.query_resources( |
| 143 | + resource_ids=resource_ids, |
| 144 | + metric_namespace="Microsoft.Storage/storageAccounts", |
| 145 | + metric_names=["UsedCapacity"], |
| 146 | + timespan=timedelta(hours=2), |
| 147 | + granularity=timedelta(minutes=5), |
| 148 | + aggregations=[MetricAggregationType.AVERAGE], |
| 149 | +) |
| 150 | + |
| 151 | +for metrics_query_result in response: |
| 152 | + for metric in metrics_query_result.metrics: |
| 153 | + print(f"Metric: {metric.name}") |
| 154 | + for time_series in metric.timeseries: |
| 155 | + for metric_value in time_series.data: |
| 156 | + if metric_value.average is not None: |
| 157 | + print(f"Average: {metric_value.average}") |
| 158 | +``` |
| 159 | + |
| 160 | +#### Handle metrics query response |
| 161 | + |
| 162 | +The metrics query API returns a list of `MetricsQueryResult` objects. The `MetricsQueryResult` object contains properties such as a list of `Metric`-typed objects, `granularity`, `namespace`, and `timespan`. The `Metric` objects list can be accessed using the `metrics` param. Each `Metric` object in this list contains a list of `TimeSeriesElement` objects. Each `TimeSeriesElement` object contains `data` and `metadata_values` properties. In visual form, the object hierarchy of the response resembles the following structure: |
| 163 | + |
| 164 | +``` |
| 165 | +MetricsQueryResult |
| 166 | +|---granularity |
| 167 | +|---timespan |
| 168 | +|---cost |
| 169 | +|---namespace |
| 170 | +|---resource_region |
| 171 | +|---metrics (list of `Metric` objects) |
| 172 | + |---id |
| 173 | + |---type |
| 174 | + |---name |
| 175 | + |---unit |
| 176 | + |---timeseries (list of `TimeSeriesElement` objects) |
| 177 | + |---metadata_values |
| 178 | + |---data (list of data points) |
| 179 | +``` |
| 180 | + |
| 181 | +**Note:** Each `MetricsQueryResult` is returned in the same order as the corresponding resource in the `resource_ids` parameter. If multiple different metrics are queried, the metrics are returned in the order of the `metric_names` sent. |
| 182 | + |
| 183 | +**Example of handling response** |
| 184 | + |
| 185 | +```python |
| 186 | +import os |
| 187 | +from azure.monitor.querymetrics import MetricsClient, MetricAggregationType |
| 188 | +from azure.identity import DefaultAzureCredential |
| 189 | + |
| 190 | +credential = DefaultAzureCredential() |
| 191 | +client = MetricsClient("https://<regional endpoint>", credential) |
| 192 | + |
| 193 | +metrics_uri = os.environ['METRICS_RESOURCE_URI'] |
| 194 | +response = client.query_resource( |
| 195 | + metrics_uri, |
| 196 | + metric_names=["PublishSuccessCount"], |
| 197 | + aggregations=[MetricAggregationType.AVERAGE] |
| 198 | +) |
| 199 | + |
| 200 | +for metrics_query_result in response: |
| 201 | + for metric in metrics_query_result.metrics: |
| 202 | + print(f"Metric: {metric.name}") |
| 203 | + for time_series in metric.timeseries: |
| 204 | + for metric_value in time_series.data: |
| 205 | + if metric_value.average is not None: |
| 206 | + print(f"Average: {metric_value.average}") |
| 207 | +``` |
| 208 | + |
| 209 | +## Troubleshooting |
| 210 | + |
| 211 | +See our [troubleshooting guide][troubleshooting_guide] for details on how to diagnose various failure scenarios. |
| 212 | + |
| 213 | +## Next steps |
| 214 | + |
| 215 | +To learn more about Azure Monitor, see the [Azure Monitor service documentation][azure_monitor_overview]. |
| 216 | + |
| 217 | +### Samples |
| 218 | + |
| 219 | +The following code samples show common scenarios with the Azure Monitor Query Metrics client library. |
| 220 | + |
| 221 | +#### Metrics query samples |
| 222 | + |
| 223 | +To be added. |
| 224 | + |
| 225 | +## Contributing |
| 226 | + |
| 227 | +This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit [cla.microsoft.com][cla]. |
| 228 | + |
| 229 | +When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repositories using our CLA. |
| 230 | + |
| 231 | +This project has adopted the [Microsoft Open Source Code of Conduct][code_of_conduct]. For more information see the [Code of Conduct FAQ][coc_faq] or contact [opencode@microsoft.com][coc_contact] with any additional questions or comments. |
| 232 | + |
| 233 | +<!-- LINKS --> |
| 234 | + |
| 235 | +[azure_core_exceptions]: https://aka.ms/azsdk/python/core/docs#module-azure.core.exceptions |
| 236 | +[azure_core_ref_docs]: https://aka.ms/azsdk/python/core/docs |
| 237 | +[azure_monitor_overview]: https://learn.microsoft.com/azure/azure-monitor/ |
| 238 | +[azure_subscription]: https://azure.microsoft.com/free/python/ |
| 239 | +[changelog]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/monitor/azure-monitor-querymetrics/CHANGELOG.md |
| 240 | +[metric_namespaces]: https://learn.microsoft.com/azure/azure-monitor/reference/supported-metrics/metrics-index#supported-metrics-and-log-categories-by-resource-type |
| 241 | +[pip]: https://pypi.org/project/pip/ |
| 242 | +[python_logging]: https://docs.python.org/3/library/logging.html |
| 243 | +[samples]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/monitor/azure-monitor-querymetrics/samples |
| 244 | +[source]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/monitor/azure-monitor-querymetrics/ |
| 245 | +[troubleshooting_guide]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/monitor/azure-monitor-querymetrics/TROUBLESHOOTING.md |
| 246 | + |
| 247 | +[cla]: https://cla.microsoft.com |
| 248 | +[code_of_conduct]: https://opensource.microsoft.com/codeofconduct/ |
| 249 | +[coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ |
| 250 | +[coc_contact]: mailto:opencode@microsoft.com |
0 commit comments