Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update and improve README #19903

Merged
merged 6 commits into from
Jul 23, 2021
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 82 additions & 2 deletions sdk/monitor/azure-monitor-query/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ Install the Azure Monitor Query client library for Python with [pip][pip]:
pip install azure-monitor-query --pre
```

### Authenticate the client
### Create and Authenticate the client
A **token credential** is necessary to instantiate both the LogsQueryClient and the MetricsQueryClient object.

```Python
Expand Down Expand Up @@ -102,6 +102,11 @@ time-stamped data. Each set of metric values is a time series with the following

This sample shows getting a log query. to handle the response and view it in a tabular form, the [pandas](https://pypi.org/project/pandas/) library is used. Please look at the samples if you don't want to use the pandas library.

#### Specifying a duration

The `duration` parameter can be used to specify the time duration for which to query the data. This can also be accompanied with either `start_time` or `end_time`. If either `start_time` or `end_time` are not provided, the current time is taken as the end time.
Alternatively, the `start_time` and `end_time` keyword arguments can be provided together instead of `duration` parameter like shown in the example below.

```Python
import os
import pandas as pd
Expand All @@ -117,7 +122,6 @@ client = LogsQueryClient(credential)
# Response time trend
# request duration over the last 12 hours.
query = """AppRequests |
where TimeGenerated > ago(12h) |
summarize avgRequestDuration=avg(DurationMs) by bin(TimeGenerated, 10m), _ResourceId"""

# returns LogsQueryResults
Expand All @@ -136,6 +140,19 @@ for table in response.tables:
print(df)
```

#### Single query on multiple workspaces.

`additional_workspaces` param can be used to pass a list of workspaces that are included in the query when querying a single query over multiple workspaces. These can be qualified workspace names, workspsce Ids or Azure resource Ids.
rakshith91 marked this conversation as resolved.
Show resolved Hide resolved
Note that a primary `workspace_id` must still be provided when querying additional workspaces like in the snippet below.

```Python
client.query(
<primary_workspace_id>,
query,
additional_workspaces=['<workspace 1>', '<workspace 2>']
)
```

### Get Logs for multiple queries

This sample shows sending multiple queries at the same time using batch query API. For each query, a `LogQueryRequest` object can be used. Alternatively, a dictionary can be used as well.
Expand Down Expand Up @@ -208,6 +225,8 @@ response = client.query(

This example shows getting the metrics for an EventGrid subscription. The resource URI is that of an eventgrid topic.

**Note** The resource URI must be that of the resource for which metrics are being queried. It's normally of the format, `/subscriptions/<id>/resourceGroups/<rg-name>/providers/<source>/topics/<resource-name>`.

```Python
import os
from datetime import timedelta
Expand All @@ -234,6 +253,67 @@ for metric in response.metrics:
print(metric_value.time_stamp)
```

### Handling the response for metrics

The metrics query API returns a `MetricsResult` object. This object has a list of `Metric` type along with other params like `interval`, `namespace` and `timespan`.
rakshith91 marked this conversation as resolved.
Show resolved Hide resolved

This cab ne fetched using the `metrics` param.
rakshith91 marked this conversation as resolved.
Show resolved Hide resolved

Each of the item in this list is a `Metric` object that contains a list of `TimeSeriesElement`. Each of the timeseries elements contain `data` and `metadata_values` params.
rakshith91 marked this conversation as resolved.
Show resolved Hide resolved


#### Object heirarchy of the response

```
MetricsResult
|---interval
|---timespan
|---cost
|---namespace
|---resourceregion
|---metrics (list of `Metric` objects)
|---id
|---type
|---name
|---unit
|---timeseries (list of `TimeSeriesElement` objects)
|---metadata_values
|---data (list of data points represented by `MetricValue` objects)
```

#### Sample usage of the API to handle response.

```Python
import os
from datetime import datetime, timedelta
from azure.monitor.query import MetricsQueryClient, AggregationType
from azure.identity import DefaultAzureCredential

credential = DefaultAzureCredential()
client = MetricsQueryClient(credential)

metrics_uri = os.environ['METRICS_RESOURCE_URI']
response = client.query(
metrics_uri,
metric_names=["MatchedEventCount"],
start_time=datetime(2021, 6, 21),
duration=timedelta(days=1),
aggregations=[AggregationType.COUNT]
)

for metric in response.metrics:
print(metric.name)
for time_series_element in metric.timeseries:
for metric_value in time_series_element.data:
if metric_value.count != 0:
print(
"There are {} matched events at {}".format(
metric_value.count,
metric_value.time_stamp
)
)
```

## Troubleshooting

- Enable `azure.monitor.query` logger to collect traces from the library.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -483,7 +483,7 @@ class TimeSeriesElement(object):

:keyword metadata_values: the metadata values returned if $filter was specified in the call.
:paramtype metadata_values: list[~monitor_query_client.models.MetadataValue]
:keyword data: An array of data points representing the metric values. This is only returned if
:keyword data: An array of data points representing the metric values. This is only returned if
a result type of data is specified.
:paramtype data: list[~monitor_query_client.models.MetricValue]
"""
Expand Down