azure.monitor.query package¶
-
class
azure.monitor.query.
LogsBatchResultError
(**kwargs: Any)[source]¶ Error response for a batch request.
-
class
azure.monitor.query.
LogsBatchResults
(**kwargs: Any)[source]¶ Response to a batch.
- Keyword Arguments
responses (list[azure.monitor.query.LogsQueryResult]) – An array of responses corresponding to each individual request in a batch.
error (LogsBatchResultError) – Error response for a batch request.
-
class
azure.monitor.query.
LogsQueryClient
(credential: TokenCredential, **kwargs: Any)[source]¶ - Parameters
credential (TokenCredential) – The credential to authenticate the client
- Keyword Arguments
endpoint (str) – The endpoint to connect to. Defaults to ‘https://api.loganalytics.io’.
credential = DefaultAzureCredential() client = LogsQueryClient(credential)
-
batch_query
(queries: Union[Sequence[Dict], Sequence[azure.monitor.query._models.LogsQueryRequest]], **kwargs: Any) → azure.monitor.query._models.LogsBatchResults[source]¶ Execute a list of analytics queries. Each request can be either a LogQueryRequest object or an equivalent serialized model.
The response is returned in the same order as that of the requests sent.
- Parameters
queries (list[dict] or list[LogsQueryRequest]) – The list of queries that should be processed
- Returns
BatchResponse, or the result of cls(response)
- Return type
- Raises
~azure.core.exceptions.HttpResponseError
requests = [ LogsQueryRequest( query="AzureActivity | summarize count()", duration=timedelta(hours=1), workspace_id= os.environ['LOG_WORKSPACE_ID'] ), LogsQueryRequest( query= """AppRequests | take 10 | summarize avgRequestDuration=avg(DurationMs) by bin(TimeGenerated, 10m), _ResourceId""", duration=timedelta(hours=1), start_time=datetime(2021, 6, 2), workspace_id= os.environ['LOG_WORKSPACE_ID'] ), LogsQueryRequest( query= "AppRequests", workspace_id= os.environ['LOG_WORKSPACE_ID'], include_statistics=True ), ] response = client.batch_query(requests) for response in response.responses: body = response.body print(response.id) if not body.tables: print("Something is wrong") else: for table in body.tables: df = pd.DataFrame(table.rows, columns=[col.name for col in table.columns]) print(df)
-
close
() → None[source]¶ Close the
LogsQueryClient
session.
-
query
(workspace_id: str, query: str, duration: Optional[timedelta] = None, **kwargs: Any) → LogsQueryResults[source]¶ Execute an Analytics query.
Executes an Analytics query for data.
Note: Although the start_time, end_time, duration are optional parameters, it is highly recommended to specify the timespan. If not, the entire dataset is queried.
- Parameters
workspace_id (str) – ID of the workspace. This is Workspace ID from the Properties blade in the Azure portal.
query (str) – The Analytics query. Learn more about the Analytics query syntax.
duration (timedelta) – The duration for which to query the data. This can also be accompanied with either start_time or end_time. If start_time or end_time is not provided, the current time is taken as the end time.
- Keyword Arguments
start_time (datetime) – The start time from which to query the data. This should be accompanied with either end_time or duration.
end_time (datetime) – The end time till which to query the data. This should be accompanied with either start_time or duration.
server_timeout (int) – the server timeout in seconds. The default timeout is 3 minutes, and the maximum timeout is 10 minutes.
include_statistics (bool) – To get information about query statistics.
include_render (bool) – In the query language, it is possible to specify different render options. By default, the API does not return information regarding the type of visualization to show. If your client requires this information, specify the preference
additional_workspaces (list[str]) – A list of workspaces that are included in the query. These can be qualified workspace names, workspsce Ids or Azure resource Ids.
- Returns
QueryResults, or the result of cls(response)
- Return type
- Raises
~azure.core.exceptions.HttpResponseError
query = """AppRequests | summarize avgRequestDuration=avg(DurationMs) by bin(TimeGenerated, 10m), _ResourceId""" end_time = datetime.now(UTC()) # returns LogsQueryResults response = client.query(os.environ['LOG_WORKSPACE_ID'], query, duration=timedelta(days=1), end_time=end_time) 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)
-
class
azure.monitor.query.
LogsQueryRequest
(query: str, workspace_id: str, duration: Optional[str] = None, **kwargs: Any)[source]¶ A single request in a batch.
Variables are only populated by the server, and will be ignored when sending a request.
- Parameters
workspace_id (str) – Workspace Id to be included in the query.
query (str) –
The Analytics query. Learn more about the Analytics query syntax.
duration (timedelta) – The duration for which to query the data. This can also be accompanied with either start_time or end_time. If start_time or end_time is not provided, the current time is taken as the end time.
- Keyword Arguments
start_time (datetime) – The start time from which to query the data. This should be accompanied with either end_time or duration.
end_time (datetime) – The end time till which to query the data. This should be accompanied with either start_time or duration.
additional_workspaces (list[str]) – A list of workspaces that are included in the query. These can be qualified workspace names, workspsce Ids or Azure resource Ids.
request_id (str) – The error details.
server_timeout (int) – the server timeout. The default timeout is 3 minutes, and the maximum timeout is 10 minutes.
include_statistics (bool) – To get information about query statistics.
include_render (bool) – In the query language, it is possible to specify different render options. By default, the API does not return information regarding the type of visualization to show.
-
as_dict
(keep_readonly=True, key_transformer=<function attribute_transformer>, **kwargs)¶ Return a dict that can be JSONify using json.dump.
Advanced usage might optionaly use a callback as parameter:
Key is the attribute name used in Python. Attr_desc is a dict of metadata. Currently contains ‘type’ with the msrest type and ‘key’ with the RestAPI encoded key. Value is the current value in this object.
The string returned will be used to serialize the key. If the return type is a list, this is considered hierarchical result dict.
See the three examples in this file:
attribute_transformer
full_restapi_key_transformer
last_restapi_key_transformer
If you want XML serialization, you can pass the kwargs is_xml=True.
- Parameters
key_transformer (function) – A key transformer function.
- Returns
A dict JSON compatible object
- Return type
-
classmethod
deserialize
(data, content_type=None)¶ Parse a str using the RestAPI syntax and return a model.
-
classmethod
enable_additional_properties_sending
()¶
-
classmethod
from_dict
(data, key_extractors=None, content_type=None)¶ Parse a dict using given key extractor return a model.
By default consider key extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor and last_rest_key_case_insensitive_extractor)
-
classmethod
is_xml_model
()¶
-
serialize
(keep_readonly=False, **kwargs)¶ Return the JSON that would be sent to azure from this model.
This is an alias to as_dict(full_restapi_key_transformer, keep_readonly=False).
If you want XML serialization, you can pass the kwargs is_xml=True.
-
validate
()¶ Validate this model recursively and return a list of ValidationError.
- Returns
A list of validation error
- Return type
-
method
= 'POST'¶
-
path
= '/query'¶
-
class
azure.monitor.query.
LogsQueryResultColumn
(**kwargs: Any)[source]¶ A column in a table.
-
as_dict
(keep_readonly=True, key_transformer=<function attribute_transformer>, **kwargs)¶ Return a dict that can be JSONify using json.dump.
Advanced usage might optionaly use a callback as parameter:
Key is the attribute name used in Python. Attr_desc is a dict of metadata. Currently contains ‘type’ with the msrest type and ‘key’ with the RestAPI encoded key. Value is the current value in this object.
The string returned will be used to serialize the key. If the return type is a list, this is considered hierarchical result dict.
See the three examples in this file:
attribute_transformer
full_restapi_key_transformer
last_restapi_key_transformer
If you want XML serialization, you can pass the kwargs is_xml=True.
- Parameters
key_transformer (function) – A key transformer function.
- Returns
A dict JSON compatible object
- Return type
-
classmethod
deserialize
(data, content_type=None)¶ Parse a str using the RestAPI syntax and return a model.
-
classmethod
enable_additional_properties_sending
()¶
-
classmethod
from_dict
(data, key_extractors=None, content_type=None)¶ Parse a dict using given key extractor return a model.
By default consider key extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor and last_rest_key_case_insensitive_extractor)
-
classmethod
is_xml_model
()¶
-
serialize
(keep_readonly=False, **kwargs)¶ Return the JSON that would be sent to azure from this model.
This is an alias to as_dict(full_restapi_key_transformer, keep_readonly=False).
If you want XML serialization, you can pass the kwargs is_xml=True.
-
-
class
azure.monitor.query.
LogsQueryResultTable
(name: str, columns: List[azure.monitor.query._models.LogsQueryResultColumn], rows: List[List[str]])[source]¶ Contains the columns and rows for one table in a query response.
All required parameters must be populated in order to send to Azure.
-
class
azure.monitor.query.
LogsQueryResults
(**kwargs: Any)[source]¶ Contains the tables, columns & rows resulting from a query.
- Keyword Arguments
tables (list[LogsQueryResultTable]) – The list of tables, columns and rows.
statistics (object) – Any object.
render (object) – Any object.
-
class
azure.monitor.query.
Metric
(**kwargs: Any)[source]¶ The result data of a query.
All required parameters must be populated in order to send to Azure.
- Keyword Arguments
id (str) – Required. the metric Id.
type (str) – Required. the resource type of the metric resource.
name (str) – Required. the name of the metric.
unit (str) – Required. the unit of the metric. Possible values include: “Count”, “Bytes”, “Seconds”, “CountPerSecond”, “BytesPerSecond”, “Percent”, “MilliSeconds”, “ByteSeconds”, “Unspecified”, “Cores”, “MilliCores”, “NanoCores”, “BitsPerSecond”.
timeseries (list[TimeSeriesElement]) – Required. the time series returned when a data query is performed.
-
class
azure.monitor.query.
MetricAvailability
(**kwargs: Any)[source]¶ Metric availability specifies the time grain (aggregation interval or frequency) and the retention period for that time grain.
-
class
azure.monitor.query.
MetricDefinition
(**kwargs: Any)[source]¶ Metric definition class specifies the metadata for a metric.
- Keyword Arguments
is_dimension_required (bool) – Flag to indicate whether the dimension is required.
resource_id (str) – the resource identifier of the resource that emitted the metric.
namespace (str) – the namespace the metric belongs to.
name (str) – the name and the display name of the metric, i.e. it is a localizable string.
unit (str or Unit) – the unit of the metric. Possible values include: “Count”, “Bytes”, “Seconds”, “CountPerSecond”, “BytesPerSecond”, “Percent”, “MilliSeconds”, “ByteSeconds”, “Unspecified”, “Cores”, “MilliCores”, “NanoCores”, “BitsPerSecond”.
primary_aggregation_type (str or AggregationType) – the primary aggregation type value defining how to use the values for display. Possible values include: “None”, “Average”, “Count”, “Minimum”, “Maximum”, “Total”.
supported_aggregation_types (list[str or AggregationType]) – the collection of what aggregation types are supported.
metric_availabilities (list[MetricAvailability]) – the collection of what aggregation intervals are available to be queried.
id (str) – the resource identifier of the metric definition.
dimensions (list[str]) – the name and the display name of the dimension, i.e. it is a localizable string.
-
class
azure.monitor.query.
MetricNamespace
(**kwargs)[source]¶ Metric namespace class specifies the metadata for a metric namespace.
-
class
azure.monitor.query.
MetricValue
(**kwargs: Any)[source]¶ Represents a metric value.
All required parameters must be populated in order to send to Azure.
- Keyword Arguments
time_stamp (datetime) – Required. the timestamp for the metric value in ISO 8601 format.
average (float) – the average value in the time range.
minimum (float) – the least value in the time range.
maximum (float) – the greatest value in the time range.
total (float) – the sum of all of the values in the time range.
count (float) – the number of samples in the time range. Can be used to determine the number of values that contributed to the average value.
-
class
azure.monitor.query.
MetricsMetadataValue
(**kwargs: Any)[source]¶ Represents a metric metadata value.
-
class
azure.monitor.query.
MetricsQueryClient
(credential: TokenCredential, **kwargs: Any)[source]¶ - Parameters
credential (TokenCredential) – The credential to authenticate the client
- Keyword Arguments
endpoint (str) – The endpoint to connect to. Defaults to ‘https://management.azure.com’.
credential = DefaultAzureCredential() client = MetricsQueryClient(credential)
-
close
() → None[source]¶ Close the
MetricsQueryClient
session.
-
list_metric_definitions
(resource_uri: str, metric_namespace: str = None, **kwargs: Any) → ItemPaged[MetricDefinition][source]¶ Lists the metric definitions for the resource.
- Parameters
- Returns
An iterator like instance of either MetricDefinitionCollection or the result of cls(response)
- Return type
- Raises
~azure.core.exceptions.HttpResponseError
-
list_metric_namespaces
(resource_uri: str, **kwargs: Any) → ItemPaged[MetricNamespace][source]¶ Lists the metric namespaces for the resource.
- Parameters
resource_uri (str) – The identifier of the resource.
- Keyword Arguments
start_time (str) – The ISO 8601 conform Date start time from which to query for metric namespaces.
- Returns
An iterator like instance of either MetricNamespaceCollection or the result of cls(response)
- Return type
- Raises
~azure.core.exceptions.HttpResponseError
-
query
(resource_uri: str, metric_names: list, duration: Optional[timedelta] = None, **kwargs: Any) → MetricsResult[source]¶ Lists the metric values for a resource.
Note: Although the start_time, end_time, duration are optional parameters, it is highly recommended to specify the timespan. If not, the entire dataset is queried.
- Parameters
resource_uri (str) – The identifier of the resource.
metric_names (list[str]) – The names of the metrics to retrieve.
duration (timedelta) – The duration for which to query the data. This can also be accompanied with either start_time or end_time. If start_time or end_time is not provided, the current time is taken as the end time.
- Keyword Arguments
start_time (datetime) – The start time from which to query the data. This should be accompanied with either end_time or duration.
end_time (datetime) – The end time till which to query the data. This should be accompanied with either start_time or duration.
interval (timedelta) – The interval (i.e. timegrain) of the query.
aggregation (list[str]) – The list of aggregation types to retrieve.
top (int) – The maximum number of records to retrieve. Valid only if $filter is specified. Defaults to 10.
orderby (str) – The aggregation to use for sorting results and the direction of the sort. Only one order can be specified. Examples: sum asc.
filter (str) – The $filter is used to reduce the set of metric data returned.:code:<br>`Example::code:`<br>`Metric contains metadata A, B and C.:code:`<br>- Return all time series of C where A = a1 and B = b1 or b2:code:<br>$filter=A eq ‘a1’ and B eq ‘b1’ or B eq ‘b2’ and C eq ‘*’
<br>
- Invalid variant:<br>
$filter=A eq ‘a1’ and B eq ‘b1’ and C eq ‘*’ or B = ‘b2’<br>`This is invalid because the logical or operator cannot separate two different metadata names.:code:`<br>
- Return all time series where A = a1, B = b1 and C = c1:<br>
$filter=A eq ‘a1’ and B eq ‘b1’ and C eq ‘c1’<br>
- Return all time series where A = a1:code:<br>$filter=A eq ‘a1’ and B eq ‘*’ and C eq ‘*’.result_type (str or ResultType) – Reduces the set of data collected. The syntax allowed depends on the operation. See the operation’s description for details.
metric_namespace (str) – Metric namespace to query metric definitions for.
- Returns
Response, or the result of cls(response)
- Return type
- Raises
~azure.core.exceptions.HttpResponseError
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), aggregation=['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 ) )
-
class
azure.monitor.query.
MetricsResult
(**kwargs: Any)[source]¶ The response to a metrics query.
All required parameters must be populated in order to send to Azure.
- Keyword Arguments
cost (int) – The integer value representing the cost of the query, for data case.
timespan (str) – Required. The timespan for which the data was retrieved. Its value consists of two datetimes concatenated, separated by ‘/’. This may be adjusted in the future and returned back from what was originally requested.
interval (timedelta) – The interval (window size) for which the metric data was returned in. This may be adjusted in the future and returned back from what was originally requested. This is not present if a metadata request was made.
namespace (str) – The namespace of the metrics been queried.
resourceregion (str) – The region of the resource been queried for metrics.
metrics (list[Metric]) – Required. the value of the collection.
-
class
azure.monitor.query.
TimeSeriesElement
(**kwargs: Any)[source]¶ A time series result type. The discriminator value is always TimeSeries in this case.