Skip to content

Commit 12dc44e

Browse files
author
Rakshith Bhyravabhotla
authored
Azure monitor query
* Azure monitor query (Azure#18022) * Initial commit * updates * packaging * namespace * oops * regenerate * shared reqs * sample test file * AAD support * samples * ci fix * lint * docs * models * more changes * update * minor update * batcg support * minor update * logs * mypy * more changes * definition * changes * sampes * lint * Feature/query sdk (Azure#18993) * lint * update samples * Feature/query sdk (Azure#19006) * query * add async * readme * Feature/query sdk (Azure#19007) * query * add async * aio * query (Azure#19056) add async metrics models models refactor samples fix * temporary readme links (Azure#19057) * lint (Azure#19058) * oops (Azure#19059) * lint 2 (Azure#19061) * Lint 3 (Azure#19073) * lint 2 * lint-3 * Add tests (Azure#19076) * Apply suggestions from code review * analyze + stubgen (Azure#19082) * snake case refactor (Azure#19084) * aio tests (Azure#19092) * Timespan (Azure#19100) * fix definitions * fix name space * aio namespace * order results * tests fix * py2 compat * azure monitor nspkg (Azure#19101) * Lint + feedback (Azure#19108) * Revert "azure monitor nspkg (Azure#19101)" This reverts commit c919183. * lint + feedback * timespan (Azure#19110) * Update sdk/monitor/azure-monitor-query/azure/monitor/query/_log_query_client.py * lint + async (Azure#19114) * Lint (Azure#19120) * lint + duration * changelog * Apply suggestions from code review * Apply suggestions from code review * Update sdk/monitor/azure-monitor-query/tests/conftest.py * Update sdk/monitor/azure-monitor-query/setup.py * freeze req (Azure#19124) * Update sdk/monitor/azure-monitor-query/samples/async_samples/sample_metric_definitions_async.py
1 parent 66858a1 commit 12dc44e

File tree

65 files changed

+8586
-1
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

65 files changed

+8586
-1
lines changed

eng/.docsettings.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ known_content_issues:
6969
- ['sdk/core/azure-common/README.md', '#4554']
7070
- ['sdk/core/azure-servicemanagement-legacy/README.md', '#4554']
7171
- ['sdk/eventgrid/azure-eventgrid/README.md', '#4554']
72+
- ['sdk/monitor/azure-monitor-query/README.md', '#4554']
7273
- ['sdk/graphrbac/azure-graphrbac/README.md', '#4554']
7374
- ['sdk/loganalytics/azure-loganalytics/README.md', '#4554']
7475
- ['sdk/servicebus/azure-servicebus/README.md', '#4554']
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
__path__ = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# Release History
2+
3+
## 1.0.0b1 (Unreleased)
4+
5+
**Features**
6+
- Version (1.0.0b1) is the first preview of our efforts to create a user-friendly and Pythonic client library for Azure Monitor Query.
7+
For more information about this, and preview releases of other Azure SDK libraries, please visit https://azure.github.io/azure-sdk/releases/latest/python.html.
8+
- Added `LogsQueryClient` to query log analytics.
9+
- Implements the `MetricsQueryClient` for querying metrics, listing namespaces and metric definitions.
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
recursive-include tests *.py *.yaml
2+
recursive-include samples *.py
3+
include *.md
4+
include azure/__init__.py
5+
include azure/monitor/__init__.py
Lines changed: 286 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,286 @@
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
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
__path__ = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
__path__ = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# coding=utf-8
2+
# --------------------------------------------------------------------------
3+
# Copyright (c) Microsoft Corporation. All rights reserved.
4+
# Licensed under the MIT License. See License.txt in the project root for license information.
5+
# --------------------------------------------------------------------------
6+
7+
from ._log_query_client import LogsQueryClient
8+
from ._metrics_query_client import MetricsQueryClient
9+
10+
from ._models import (
11+
LogsQueryResults,
12+
LogsQueryResultTable,
13+
LogsQueryResultColumn,
14+
MetricsResult,
15+
LogsBatchResultError,
16+
LogsQueryRequest,
17+
LogsBatchResults,
18+
LogsErrorDetails,
19+
MetricNamespace,
20+
MetricDefinition,
21+
MetricsMetadataValue,
22+
TimeSeriesElement,
23+
Metric,
24+
MetricValue,
25+
MetricAvailability
26+
)
27+
28+
from ._version import VERSION
29+
30+
__all__ = [
31+
"LogsQueryClient",
32+
"LogsBatchResults",
33+
"LogsBatchResultError",
34+
"LogsQueryResults",
35+
"LogsQueryResultColumn",
36+
"LogsQueryResultTable",
37+
"LogsQueryRequest",
38+
"LogsErrorDetails",
39+
"MetricsQueryClient",
40+
"MetricNamespace",
41+
"MetricDefinition",
42+
"MetricsResult",
43+
"MetricsMetadataValue",
44+
"TimeSeriesElement",
45+
"Metric",
46+
"MetricValue",
47+
"MetricAvailability"
48+
]
49+
50+
__version__ = VERSION
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# coding=utf-8
2+
# --------------------------------------------------------------------------
3+
# Copyright (c) Microsoft Corporation. All rights reserved.
4+
# Licensed under the MIT License. See License.txt in the project root for license information.
5+
# Code generated by Microsoft (R) AutoRest Code Generator.
6+
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
7+
# --------------------------------------------------------------------------
8+
9+
from ._monitor_query_client import MonitorQueryClient
10+
__all__ = ['MonitorQueryClient']
11+
12+
try:
13+
from ._patch import patch_sdk # type: ignore
14+
patch_sdk()
15+
except ImportError:
16+
pass

0 commit comments

Comments
 (0)