|
| 1 | +# Azure Monitor Query client library for Python |
| 2 | + |
| 3 | +Azure Monitor helps you maximize the availability and performance of your applications and services. It delivers a comprehensive solution for collecting, analyzing, and acting on telemetry from your cloud and on-premises environments. |
| 4 | + |
| 5 | +All data collected by Azure Monitor fits into one of two fundamental types, metrics and logs. Metrics are numerical values that describe some aspect of a system at a particular point in time. They are lightweight and capable of supporting near real-time scenarios. Logs contain different kinds of data organized into records with different sets of properties for each type. Telemetry such as events and traces are stored as logs in addition to performance data so that it can all be combined for analysis. |
| 6 | + |
| 7 | +[Source code][python-query-src] | [Package (PyPI)][python-query-pypi] | [API reference documentation][python-query-ref-docs] | [Product documentation][python-query-product-docs] | [Samples][python-query-samples] | [Changelog][python-query-changelog] |
| 8 | + |
| 9 | +## Getting started |
| 10 | + |
| 11 | +### Prerequisites |
| 12 | +* Python 2.7, or 3.6 or later is required to use this package. |
| 13 | +* You must have an [Azure subscription][azure_subscription]. |
| 14 | + |
| 15 | + |
| 16 | +### Install the package |
| 17 | +Install the Azure Monitor Query client library for Python with [pip][pip]: |
| 18 | + |
| 19 | +```bash |
| 20 | +pip install azure-monitor-query --pre |
| 21 | +``` |
| 22 | + |
| 23 | +### Authenticate the client |
| 24 | +A **token credential** is necessary to instantiate both the LogsQueryClient and the MetricsQueryClient object. |
| 25 | + |
| 26 | +```Python |
| 27 | +from azure.monitor.query import LogsQueryClient |
| 28 | +from azure.identity import ClientSecretCredential |
| 29 | + |
| 30 | + |
| 31 | +credential = ClientSecretCredential( |
| 32 | + client_id = os.environ['AZURE_CLIENT_ID'], |
| 33 | + client_secret = os.environ['AZURE_CLIENT_SECRET'], |
| 34 | + tenant_id = os.environ['AZURE_TENANT_ID'] |
| 35 | + ) |
| 36 | + |
| 37 | +client = LogsQueryClient(credential) |
| 38 | +``` |
| 39 | + |
| 40 | +```Python |
| 41 | +from azure.monitor.query import MetricsQueryClient |
| 42 | +from azure.identity import ClientSecretCredential |
| 43 | + |
| 44 | + |
| 45 | +credential = ClientSecretCredential( |
| 46 | + client_id = os.environ['AZURE_CLIENT_ID'], |
| 47 | + client_secret = os.environ['AZURE_CLIENT_SECRET'], |
| 48 | + tenant_id = os.environ['AZURE_TENANT_ID'] |
| 49 | + ) |
| 50 | + |
| 51 | +client = MetricsQueryClient(credential) |
| 52 | +``` |
| 53 | + |
| 54 | +## Key concepts |
| 55 | + |
| 56 | +### Logs |
| 57 | + |
| 58 | +Azure Monitor Logs is a feature of Azure Monitor that collects and organizes log and performance data from monitored |
| 59 | +resources. Data from different sources such as platform logs from Azure services, log and performance data from virtual |
| 60 | +machines agents, and usage and performance data from applications can be consolidated into a single workspace so they |
| 61 | +can be analyzed together using a sophisticated query language that's capable of quickly analyzing millions of records. |
| 62 | +You may perform a simple query that just retrieves a specific set of records or perform sophisticated data analysis to |
| 63 | +identify critical patterns in your monitoring data. |
| 64 | + |
| 65 | +#### Log Analytics workspaces |
| 66 | + |
| 67 | +Data collected by Azure Monitor Logs is stored in one or more Log Analytics workspaces. The workspace defines the |
| 68 | +geographic location of the data, access rights defining which users can access data, and configuration settings such as |
| 69 | +the pricing tier and data retention. |
| 70 | + |
| 71 | +You must create at least one workspace to use Azure Monitor Logs. A single workspace may be sufficient for all of your |
| 72 | +monitoring data, or may choose to create multiple workspaces depending on your requirements. For example, you might have |
| 73 | +one workspace for your production data and another for testing. |
| 74 | + |
| 75 | +#### Log queries |
| 76 | + |
| 77 | +Data is retrieved from a Log Analytics workspace using a log query which is a read-only request to process data and |
| 78 | +return results. Log queries are written |
| 79 | +in [Kusto Query Language (KQL)](https://docs.microsoft.com/azure/data-explorer/kusto/query/), which is the same query |
| 80 | +language used by Azure Data Explorer. You can write log queries in Log Analytics to interactively analyze their results, |
| 81 | +use them in alert rules to be proactively notified of issues, or include their results in workbooks or dashboards. |
| 82 | +Insights include prebuilt queries to support their views and workbooks. |
| 83 | + |
| 84 | +### Metrics |
| 85 | + |
| 86 | +Azure Monitor Metrics is a feature of Azure Monitor that collects numeric data from monitored resources into a time |
| 87 | +series database. Metrics are numerical values that are collected at regular intervals and describe some aspect of a |
| 88 | +system at a particular time. Metrics in Azure Monitor are lightweight and capable of supporting near real-time scenarios |
| 89 | +making them particularly useful for alerting and fast detection of issues. You can analyze them interactively with |
| 90 | +metrics explorer, be proactively notified with an alert when a value crosses a threshold, or visualize them in a |
| 91 | +workbook or dashboard. |
| 92 | + |
| 93 | +#### Metrics data structure |
| 94 | + |
| 95 | +Data collected by Azure Monitor Metrics is stored in a time-series database which is optimized for analyzing |
| 96 | +time-stamped data. Each set of metric values is a time series with the following properties: |
| 97 | + |
| 98 | +- The time the value was collected |
| 99 | +- The resource the value is associated with |
| 100 | +- A namespace that acts like a category for the metric |
| 101 | +- A metric name |
| 102 | +- The value itself |
| 103 | +- Some metrics may have multiple dimensions as described in Multi-dimensional metrics. Custom metrics can have up to 10 |
| 104 | + dimensions. |
| 105 | + |
| 106 | + |
| 107 | +## Examples |
| 108 | + |
| 109 | +### Get logs for a query |
| 110 | + |
| 111 | +```Python |
| 112 | +import os |
| 113 | +import pandas as pd |
| 114 | +from azure.monitor.query import LogsQueryClient |
| 115 | +from azure.identity import ClientSecretCredential |
| 116 | + |
| 117 | + |
| 118 | +credential = ClientSecretCredential( |
| 119 | + client_id = os.environ['AZURE_CLIENT_ID'], |
| 120 | + client_secret = os.environ['AZURE_CLIENT_SECRET'], |
| 121 | + tenant_id = os.environ['AZURE_TENANT_ID'] |
| 122 | + ) |
| 123 | + |
| 124 | +client = LogsQueryClient(credential) |
| 125 | + |
| 126 | +# Response time trend |
| 127 | +# request duration over the last 12 hours. |
| 128 | +query = """AppRequests | |
| 129 | +where TimeGenerated > ago(12h) | |
| 130 | +summarize avgRequestDuration=avg(DurationMs) by bin(TimeGenerated, 10m), _ResourceId""" |
| 131 | + |
| 132 | +# returns LogsQueryResults |
| 133 | +response = client.query(os.environ['LOG_WORKSPACE_ID'], query) |
| 134 | + |
| 135 | +if not response.tables: |
| 136 | + print("No results for the query") |
| 137 | + |
| 138 | +for table in response.tables: |
| 139 | + df = pd.DataFrame(table.rows, columns=[col.name for col in table.columns]) |
| 140 | + print(df) |
| 141 | +``` |
| 142 | + |
| 143 | +### Get Logs for multiple queries |
| 144 | + |
| 145 | +```Python |
| 146 | +import os |
| 147 | +import pandas as pd |
| 148 | +from azure.monitor.query import LogsQueryClient, LogsQueryRequest |
| 149 | +from azure.identity import ClientSecretCredential |
| 150 | + |
| 151 | + |
| 152 | +credential = ClientSecretCredential( |
| 153 | + client_id = os.environ['AZURE_CLIENT_ID'], |
| 154 | + client_secret = os.environ['AZURE_CLIENT_SECRET'], |
| 155 | + tenant_id = os.environ['AZURE_TENANT_ID'] |
| 156 | + ) |
| 157 | + |
| 158 | +client = LogsQueryClient(credential) |
| 159 | + |
| 160 | +requests = [ |
| 161 | + LogsQueryRequest( |
| 162 | + query="AzureActivity | summarize count()", |
| 163 | + timespan="PT1H", |
| 164 | + workspace= os.environ['LOG_WORKSPACE_ID'] |
| 165 | + ), |
| 166 | + LogsQueryRequest( |
| 167 | + query= """AppRequests | take 10 | |
| 168 | + summarize avgRequestDuration=avg(DurationMs) by bin(TimeGenerated, 10m), _ResourceId""", |
| 169 | + timespan="PT1H", |
| 170 | + workspace= os.environ['LOG_WORKSPACE_ID'] |
| 171 | + ), |
| 172 | + LogsQueryRequest( |
| 173 | + query= "AppRequests | take 2", |
| 174 | + workspace= os.environ['LOG_WORKSPACE_ID'] |
| 175 | + ), |
| 176 | +] |
| 177 | +response = client.batch_query(requests) |
| 178 | + |
| 179 | +for response in response.responses: |
| 180 | + body = response.body |
| 181 | + if not body.tables: |
| 182 | + print("Something is wrong") |
| 183 | + else: |
| 184 | + for table in body.tables: |
| 185 | + df = pd.DataFrame(table.rows, columns=[col.name for col in table.columns]) |
| 186 | + print(df) |
| 187 | +``` |
| 188 | + |
| 189 | +### Get logs with server timeout |
| 190 | + |
| 191 | +```Python |
| 192 | +import os |
| 193 | +import pandas as pd |
| 194 | +from azure.monitor.query import LogsQueryClient |
| 195 | +from azure.identity import ClientSecretCredential |
| 196 | + |
| 197 | + |
| 198 | +credential = ClientSecretCredential( |
| 199 | + client_id = os.environ['AZURE_CLIENT_ID'], |
| 200 | + client_secret = os.environ['AZURE_CLIENT_SECRET'], |
| 201 | + tenant_id = os.environ['AZURE_TENANT_ID'] |
| 202 | + ) |
| 203 | + |
| 204 | +client = LogsQueryClient(credential) |
| 205 | + |
| 206 | +response = client.query( |
| 207 | + os.environ['LOG_WORKSPACE_ID'], |
| 208 | + "Perf | summarize count() by bin(TimeGenerated, 4h) | render barchart title='24H Perf events'", |
| 209 | + server_timeout=10, |
| 210 | + ) |
| 211 | + |
| 212 | +for table in response.tables: |
| 213 | + df = pd.DataFrame(table.rows, columns=[col.name for col in table.columns]) |
| 214 | + print(df) |
| 215 | +``` |
| 216 | + |
| 217 | +### Get Metrics |
| 218 | + |
| 219 | +```Python |
| 220 | +import os |
| 221 | +from azure.monitor.query import MetricsQueryClient |
| 222 | +from azure.identity import ClientSecretCredential |
| 223 | + |
| 224 | + |
| 225 | +credential = ClientSecretCredential( |
| 226 | + client_id = os.environ['AZURE_CLIENT_ID'], |
| 227 | + client_secret = os.environ['AZURE_CLIENT_SECRET'], |
| 228 | + tenant_id = os.environ['AZURE_TENANT_ID'] |
| 229 | + ) |
| 230 | + |
| 231 | +client = MetricsQueryClient(credential) |
| 232 | +response = client.query(os.environ['METRICS_RESOURCE_URI'], metric_names=["Microsoft.CognitiveServices/accounts"]) |
| 233 | +``` |
| 234 | + |
| 235 | +## Troubleshooting |
| 236 | + |
| 237 | +- Enable `azure.monitor.query` logger to collect traces from the library. |
| 238 | + |
| 239 | +### General |
| 240 | +Monitor Query client library will raise exceptions defined in [Azure Core][azure_core_exceptions]. |
| 241 | + |
| 242 | +### Logging |
| 243 | +This library uses the standard |
| 244 | +[logging][python_logging] library for logging. |
| 245 | +Basic information about HTTP sessions (URLs, headers, etc.) is logged at INFO |
| 246 | +level. |
| 247 | + |
| 248 | +### Optional Configuration |
| 249 | + |
| 250 | +Optional keyword arguments can be passed in at the client and per-operation level. |
| 251 | +The azure-core [reference documentation][azure_core_ref_docs] |
| 252 | +describes available configurations for retries, logging, transport protocols, and more. |
| 253 | + |
| 254 | +## Next steps |
| 255 | + |
| 256 | +### Additional documentation |
| 257 | + |
| 258 | +For more extensive documentation on Azure Monitor Query, see the [Monitor Query documentation][python-query-product-docs] on docs.microsoft.com. |
| 259 | + |
| 260 | +## Contributing |
| 261 | +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]. |
| 262 | + |
| 263 | +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 repos using our CLA. |
| 264 | + |
| 265 | +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. |
| 266 | + |
| 267 | +<!-- LINKS --> |
| 268 | + |
| 269 | +[azure_cli_link]: https://pypi.org/project/azure-cli/ |
| 270 | +[python-query-src]: https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/monitor/azure-monitor-query/ |
| 271 | +[python-query-pypi]: https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/monitor/azure-monitor-query/ |
| 272 | +[python-query-product-docs]: https://docs.microsoft.com/rest/api/monitor/metrics |
| 273 | +[python-query-ref-docs]: https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/monitor/azure-monitor-query/ |
| 274 | +[python-query-samples]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/monitor/azure-monitor-query/samples |
| 275 | +[python-query-changelog]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/monitor/azure-monitor-query/CHANGELOG.md |
| 276 | +[pip]: https://pypi.org/project/pip/ |
| 277 | + |
| 278 | +[azure_core_exceptions]: https://aka.ms/azsdk/python/core/docs#module-azure.core.exceptions |
| 279 | +[python_logging]: https://docs.python.org/3/library/logging.html |
| 280 | +[azure_core_ref_docs]: https://aka.ms/azsdk/python/core/docs |
| 281 | +[azure_subscription]: https://azure.microsoft.com/free/ |
| 282 | + |
| 283 | +[cla]: https://cla.microsoft.com |
| 284 | +[code_of_conduct]: https://opensource.microsoft.com/codeofconduct/ |
| 285 | +[coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ |
| 286 | +[coc_contact]: mailto:opencode@microsoft.com |
0 commit comments