Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
15 changes: 9 additions & 6 deletions sdk/monitor/azure-monitor-query/azure/monitor/query/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,27 +11,30 @@
LogsQueryResults,
LogsQueryResultTable,
LogsQueryResultColumn,
MetricsResponse,
MetricsResult,
LogsBatchResponseError,
LogsQueryRequest,
LogsQueryBody,
LogsBatchResponse
LogsBatchResponse,
MetricNamespace,
MetricDefinition
)

from ._generated.models import MetricNamespaceCollection

from ._version import VERSION

__all__ = [
"LogsClient",
"LogsBatchResponse",
"LogsBatchResponseError",
"LogsQueryResults",
"LogsQueryResultColumn",
"LogsQueryResultTable",
"LogsQueryRequest",
"LogsQueryBody",
"MetricsClient",
"MetricsResponse",
"MetricNamespaceCollection"
"MetricNamespace",
"MetricDefinition",
"MetricsResult",
]

__version__ = VERSION
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

from ._generated._monitor_query_client import MonitorQueryClient

from ._generated.models import BatchRequest, QueryBody
from ._generated.models import BatchRequest
from ._helpers import get_authentication_policy
from ._models import LogsQueryResults, LogsQueryRequest, LogsQueryBody

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
if TYPE_CHECKING:
from azure.core.credentials import TokenCredential
from azure.core.paging import ItemPaged
from ._models import MetricsResponse, MetricNamespace, MetricDefinition
from ._models import MetricsResult, MetricNamespace, MetricDefinition


class MetricsClient(object):
Expand All @@ -40,7 +40,7 @@ def __init__(self, credential, **kwargs):
self._definitions_op = self._client.metric_definitions

def query(self, resource_uri, metricnames, **kwargs):
# type: (str, list, Any) -> MetricsResponse
# type: (str, list, Any) -> MetricsResult
"""Lists the metric values for a resource.

:param resource_uri: The identifier of the resource.
Expand Down Expand Up @@ -78,7 +78,7 @@ def query(self, resource_uri, metricnames, **kwargs):
:keyword metricnamespace: Metric namespace to query metric definitions for.
:paramtype metricnamespace: str
:return: Response, or the result of cls(response)
:rtype: ~azure.monitor.query.MetricsResponse
:rtype: ~azure.monitor.query.MetricsResult
:raises: ~azure.core.exceptions.HttpResponseError
"""
kwargs.setdefault("metricnames", ",".join(metricnames))
Expand All @@ -97,7 +97,7 @@ def list_metric_namespaces(self, resource_uri, **kwargs):
:rtype: ~azure.core.paging.ItemPaged[~azure.monitor.query.MetricNamespace]
:raises: ~azure.core.exceptions.HttpResponseError
"""
return self._namespace_op.list(resource_uri)
return self._namespace_op.list(resource_uri, **kwargs)

def list_metric_definitions(self, resource_uri, **kwargs):
# type: (str, Any) -> ItemPaged[MetricDefinition]
Expand All @@ -111,7 +111,7 @@ def list_metric_definitions(self, resource_uri, **kwargs):
:rtype: ~azure.core.paging.ItemPaged[~azure.monitor.query.MetricDefinition]
:raises: ~azure.core.exceptions.HttpResponseError
"""
return self._namespace_op.list(resource_uri)
return self._namespace_op.list(resource_uri, **kwargs)

def close(self):
# type: () -> None
Expand Down
112 changes: 103 additions & 9 deletions sdk/monitor/azure-monitor-query/azure/monitor/query/_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@
BatchResponse as InternalBatchResponse,
BatchResponseError as InternalBatchResponseError,
LogQueryRequest as InternalLogQueryRequest,
MetricNamespace as InternalMetricNamespace,
MetricDefinition as InternalMetricDefinition,

)


Expand All @@ -28,7 +31,7 @@ class LogsQueryResultTable(InternalTable):
:keyword name: Required. The name of the table.
:paramtype name: str
:keyword columns: Required. The list of columns in this table.
:paramtype columns: list[~monitor_query_client.models.Column]
:paramtype columns: list[~azure.monitor.query.LogsQueryResultColumn]
:keyword rows: Required. The resulting rows from this query.
:paramtype rows: list[list[str]]
"""
Expand Down Expand Up @@ -95,7 +98,7 @@ def __init__(self, **kwargs):
self.errors = kwargs.get("errors", None)


class MetricsResponse(InternalResponse):
class MetricsResult(InternalResponse):
"""The response to a metrics query.

All required parameters must be populated in order to send to Azure.
Expand Down Expand Up @@ -135,7 +138,7 @@ class MetricsResponse(InternalResponse):

def __init__(self, **kwargs):
# type: (Any) -> None
super(MetricsResponse, self).__init__(**kwargs)
super(MetricsResult, self).__init__(**kwargs)
self.cost = kwargs.get("cost", None)
self.timespan = kwargs["timespan"]
self.interval = kwargs.get("interval", None)
Expand Down Expand Up @@ -170,7 +173,8 @@ def __init__(self, **kwargs):


class LogsQueryBody(InternalQueryBody):
"""The Analytics query. Learn more about the `Analytics query syntax <https://azure.microsoft.com/documentation/articles/app-insights-analytics-reference/>`_.
"""The Analytics query. Learn more about the
`Analytics query syntax <https://azure.microsoft.com/documentation/articles/app-insights-analytics-reference/>`_.

All required parameters must be populated in order to send to Azure.

Expand All @@ -192,7 +196,7 @@ class LogsQueryBody(InternalQueryBody):

def __init__(self, query, **kwargs):
# type: (str, Any) -> None
super(QueryBody, self).__init__(**kwargs)
super(LogsQueryBody, self).__init__(**kwargs)
kwargs.setdefault("query", query)
self.timespan = kwargs.get("timespan", None)
self.workspaces = kwargs.get("workspaces", None)
Expand All @@ -207,12 +211,12 @@ class LogsBatchResponse(InternalBatchResponse):
:keyword responses: An array of responses corresponding to each individual request in a batch.
:paramtype responses: list[~monitor_query_client.models.LogQueryResponse]
:keyword error: Error response for a batch request.
:paramtype error: ~monitor_query_client.models.BatchResponseError
:paramtype error: ~azure.monitor.query.LogsBatchResponseError
"""

_attribute_map = {
"responses": {"key": "responses", "type": "[LogQueryResponse]"},
"error": {"key": "error", "type": "BatchResponseError"},
"error": {"key": "error", "type": "LogsBatchResponseError"},
}

def __init__(self, **kwargs):
Expand All @@ -222,7 +226,7 @@ def __init__(self, **kwargs):
self.error = kwargs.get("error", None)


class BatchResponseError(InternalBatchResponseError):
class LogsBatchResponseError(InternalBatchResponseError):
"""Error response for a batch request.

:param message: The error message describing the cause of the error.
Expand All @@ -241,7 +245,97 @@ class BatchResponseError(InternalBatchResponseError):

def __init__(self, **kwargs):
# type: (Any) -> None
super(BatchResponseError, self).__init__(**kwargs)
super(LogsBatchResponseError, self).__init__(**kwargs)
self.message = kwargs.get("message", None)
self.code = kwargs.get("code", None)
self.inner_error = kwargs.get("inner_error", None)

class MetricNamespace(InternalMetricNamespace):
"""Metric namespace class specifies the metadata for a metric namespace.

:param id: The ID of the metricNamespace.
:type id: str
:param type: The type of the namespace.
:type type: str
:param name: The name of the namespace.
:type name: str
:param properties: Properties which include the fully qualified namespace name.
:type properties: ~monitor_query_client.models.MetricNamespaceName
"""

_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'properties': {'key': 'properties', 'type': 'MetricNamespaceName'},
}

def __init__(
self,
**kwargs
):
super(MetricNamespace, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
self.type = kwargs.get('type', None)
self.name = kwargs.get('name', None)
self.properties = kwargs.get('properties', None)

class MetricDefinition(InternalMetricDefinition):
"""Metric definition class specifies the metadata for a metric.

:param is_dimension_required: Flag to indicate whether the dimension is required.
:type is_dimension_required: bool
:param resource_id: the resource identifier of the resource that emitted the metric.
:type resource_id: str
:param namespace: the namespace the metric belongs to.
:type namespace: str
:param name: the name and the display name of the metric, i.e. it is a localizable string.
:type name: ~monitor_query_client.models.LocalizableString
:param unit: the unit of the metric. Possible values include: "Count", "Bytes", "Seconds",
"CountPerSecond", "BytesPerSecond", "Percent", "MilliSeconds", "ByteSeconds", "Unspecified",
"Cores", "MilliCores", "NanoCores", "BitsPerSecond".
:type unit: str or ~monitor_query_client.models.Unit
:param primary_aggregation_type: the primary aggregation type value defining how to use the
values for display. Possible values include: "None", "Average", "Count", "Minimum", "Maximum",
"Total".
:type primary_aggregation_type: str or ~monitor_query_client.models.AggregationType
:param supported_aggregation_types: the collection of what aggregation types are supported.
:type supported_aggregation_types: list[str or ~monitor_query_client.models.AggregationType]
:param metric_availabilities: the collection of what aggregation intervals are available to be
queried.
:type metric_availabilities: list[~monitor_query_client.models.MetricAvailability]
:param id: the resource identifier of the metric definition.
:type id: str
:param dimensions: the name and the display name of the dimension, i.e. it is a localizable
string.
:type dimensions: list[~monitor_query_client.models.LocalizableString]
"""

_attribute_map = {
'is_dimension_required': {'key': 'isDimensionRequired', 'type': 'bool'},
'resource_id': {'key': 'resourceId', 'type': 'str'},
'namespace': {'key': 'namespace', 'type': 'str'},
'name': {'key': 'name', 'type': 'LocalizableString'},
'unit': {'key': 'unit', 'type': 'str'},
'primary_aggregation_type': {'key': 'primaryAggregationType', 'type': 'str'},
'supported_aggregation_types': {'key': 'supportedAggregationTypes', 'type': '[str]'},
'metric_availabilities': {'key': 'metricAvailabilities', 'type': '[MetricAvailability]'},
'id': {'key': 'id', 'type': 'str'},
'dimensions': {'key': 'dimensions', 'type': '[LocalizableString]'},
}

def __init__(
self,
**kwargs
):
super(MetricDefinition, self).__init__(**kwargs)
self.is_dimension_required = kwargs.get('is_dimension_required', None)
self.resource_id = kwargs.get('resource_id', None)
self.namespace = kwargs.get('namespace', None)
self.name = kwargs.get('name', None)
self.unit = kwargs.get('unit', None)
self.primary_aggregation_type = kwargs.get('primary_aggregation_type', None)
self.supported_aggregation_types = kwargs.get('supported_aggregation_types', None)
self.metric_availabilities = kwargs.get('metric_availabilities', None)
self.id = kwargs.get('id', None)
self.dimensions = kwargs.get('dimensions', None)
12 changes: 3 additions & 9 deletions sdk/monitor/azure-monitor-query/samples/sample_batch_query.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
# Licensed under the MIT License.

import os
import pandas as pd
from azure.monitor.query import LogsClient
from azure.identity import ClientSecretCredential

Expand Down Expand Up @@ -45,17 +46,10 @@
response = client.batch_query(requests)

for response in response.responses:
print(response.id)
print(response.status)
body = response.body
if not body.tables:
print("Something is wrong")
else:
for table in body.tables:
for col in table.columns: #LogsQueryResultColumn
print(col.name + "/"+ col.type + " | ", end="")
print("\n")
for row in table.rows:
for item in row:
print(item + " | ", end="")
print("\n")
df = pd.DataFrame(table.rows, columns=[col.name for col in table.columns])
print(df)
13 changes: 13 additions & 0 deletions sdk/monitor/azure-monitor-query/samples/sample_log_query_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
# Licensed under the MIT License.

import os
import pandas as pd
from datetime import timedelta
from azure.monitor.query import LogsClient
from azure.identity import ClientSecretCredential
Expand All @@ -27,6 +28,18 @@
if not response.tables:
print("No results for the query")

for table in response.tables:
df = pd.DataFrame(table.rows, columns=[col.name for col in table.columns])
print(df)

"""
TimeGenerated _ResourceId avgRequestDuration
0 2021-05-27T08:40:00Z /subscriptions/faa080af-c1d8-40ad-9cce-e1a450c... 27.307699999999997
1 2021-05-27T08:50:00Z /subscriptions/faa080af-c1d8-40ad-9cce-e1a450c... 18.11655
2 2021-05-27T09:00:00Z /subscriptions/faa080af-c1d8-40ad-9cce-e1a450c... 24.5271
"""

# if you dont want to use pandas - here's how you can process it.

#response.tables is a LogsQueryResultTable
for table in response.tables:
Expand Down