azure.monitor.query package

class azure.monitor.query.LogsBatchQuery(workspace_id: str, query: str, **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.

Keyword Arguments
  • timespan (timedelta or tuple[datetime, timedelta] or tuple[datetime, datetime]) – The timespan for which to query the data. This can be a timedelta, a timedelta and a start datetime, or a start datetime/end datetime.

  • additional_workspaces (list[str]) – A list of workspaces that are included in the query. These can be qualified workspace names, workspace Ids, or Azure resource Ids.

  • 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_visualization (bool) – In the query language, it is possible to specify different visualization options. By default, the API does not return information regarding the type of visualization to show.

class azure.monitor.query.LogsQueryClient(credential: TokenCredential, **kwargs: Any)[source]
Creating the LogsQueryClient with a TokenCredential.
credential  = DefaultAzureCredential()

client = LogsQueryClient(credential)
Parameters

credential (TokenCredential) – The credential to authenticate the client.

Keyword Arguments

endpoint (str) – The endpoint to connect to. Defaults to ‘https://api.loganalytics.io’.

close()None[source]

Close the LogsQueryClient session.

query(workspace_id: str, query: str, **kwargs: Any)LogsQueryResult[source]

Execute an Analytics query.

Executes an Analytics query for data.

Parameters
  • workspace_id (str) – ID of the workspace. This is Workspace ID from the Properties blade in the Azure portal.

  • query (str) – The Kusto query. Learn more about the Kusto query syntax.

Keyword Arguments
  • timespan (timedelta or tuple[datetime, timedelta] or tuple[datetime, datetime]) – The timespan for which to query the data. This can be a timedelta, a timedelta and a start datetime, or a start datetime/end datetime.

  • 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_visualization (bool) – In the query language, it is possible to specify different visualization 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, workspace Ids, or Azure resource Ids.

Returns

LogsQueryResult, or the result of cls(response)

Return type

LogsQueryResult

Raises

~azure.core.exceptions.HttpResponseError

Get a response for a single Log Query
query = """AppRequests |
summarize avgRequestDuration=avg(DurationMs) by bin(TimeGenerated, 10m), _ResourceId"""

# returns LogsQueryResult 
response = client.query(os.environ['LOG_WORKSPACE_ID'], query, timespan=timedelta(days=1))

if not response.tables:
    print("No results for the query")

for table in response.tables:
    try:
        df = pd.DataFrame(table.rows, columns=table.columns)
        print(df)
    except TypeError:
        print(response.error)
query_batch(queries: Union[Sequence[Dict], Sequence[LogsBatchQuery]], **kwargs: Any)List[LogsQueryResult][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[LogsBatchQuery]) – The list of Kusto queries to execute.

Returns

List of LogsQueryResult, or the result of cls(response)

Return type

list[LogsQueryResult]

Raises

~azure.core.exceptions.HttpResponseError

Get a response for multiple Log Queries.
requests = [
    LogsBatchQuery(
        query="AzureActivity | summarize count()",
        timespan=timedelta(hours=1),
        workspace_id= os.environ['LOG_WORKSPACE_ID']
    ),
    LogsBatchQuery(
        query= """AppRequests | take 10  |
            summarize avgRequestDuration=avg(DurationMs) by bin(TimeGenerated, 10m), _ResourceId""",
        timespan=(datetime(2021, 6, 2), timedelta(hours=1)),
        workspace_id= os.environ['LOG_WORKSPACE_ID']
    ),
    LogsBatchQuery(
        query= "AppRequests | take 5",
        workspace_id= os.environ['LOG_WORKSPACE_ID'],
        timespan=(datetime(2021, 6, 2), datetime(2021, 6, 3)),
        include_statistics=True
    ),
]
responses = client.query_batch(requests)

for response in responses:
    try:
        table = response.tables[0]
        df = pd.DataFrame(table.rows, columns=table.columns)
        print(df)
        print("\n\n-------------------------\n\n")
    except TypeError:
        print(response.error.innererror)

class azure.monitor.query.LogsQueryResult(**kwargs)[source]

The LogsQueryResult.

Variables
  • tables (list[LogsTable]) – The list of tables, columns and rows.

  • statistics (object) – This will include a statistics property in the response that describes various performance statistics such as query execution time and resource usage.

  • visualization (object) – This will include a visualization property in the response that specifies the type of visualization selected by the query and any properties for that visualization.

  • error (HttpResponseError) – Any error info.

class azure.monitor.query.LogsTable(**kwargs: Any)[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.

Variables
  • name (str) – Required. The name of the table.

  • columns (list[object]) – The labels of columns in this table.

  • column_types – The types of columns in this table.

  • rows (list[list[object]]) – Required. The resulting rows from this query.

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.

Variables
  • 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.

  • display_description (str) – Detailed description of this metric.

class azure.monitor.query.MetricAggregationType(value)[source]

The aggregation type of the metric.

AVERAGE = 'Average'
COUNT = 'Count'
MAXIMUM = 'Maximum'
MINIMUM = 'Minimum'
NONE = 'None'
TOTAL = 'Total'
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.

Variables
  • granularity (timedelta) – the time grain specifies the aggregation interval for the metric. Expressed as a duration ‘PT1M’, ‘P1D’, etc.

  • retention (timedelta) – the retention period for the metric at the specified timegrain. Expressed as a duration ‘PT1M’, ‘P1D’, etc.

class azure.monitor.query.MetricClass(value)[source]

The class of the metric.

AVAILABILITY = 'Availability'
ERRORS = 'Errors'
LATENCY = 'Latency'
SATURATION = 'Saturation'
TRANSACTIONS = 'Transactions'
class azure.monitor.query.MetricDefinition(**kwargs: Any)[source]

Metric definition class specifies the metadata for a metric.

Variables
  • 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 MetricUnit) – 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 MetricAggregationType) – the primary aggregation type value defining how to use the values for display. Possible values include: “None”, “Average”, “Count”, “Minimum”, “Maximum”, “Total”.

  • metric_class (str or MetricClass) – The class of the metric. Possible values include: “Availability”, “Transactions”, “Errors”, “Latency”, “Saturation”.

  • supported_aggregation_types (list[str or MetricAggregationType]) – 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.

Variables
  • id (str) – The ID of the metricNamespace.

  • type (str) – The type of the namespace.

  • name (str) – The name of the namespace.

  • fully_qualified_namespace (str) – The fully qualified namespace name.

  • namespace_classification (str or MetricNamespaceClassification) – Kind of namespace. Possible values include: “Platform”, “Custom”, “Qos”.

class azure.monitor.query.MetricNamespaceClassification(value)[source]

Kind of namespace

CUSTOM = 'Custom'
PLATFORM = 'Platform'
QOS = 'Qos'
class azure.monitor.query.MetricUnit(value)[source]

The unit of the metric.

BITS_PER_SECOND = 'BitsPerSecond'
BYTES = 'Bytes'
BYTES_PER_SECOND = 'BytesPerSecond'
BYTE_SECONDS = 'ByteSeconds'
CORES = 'Cores'
COUNT = 'Count'
COUNT_PER_SECOND = 'CountPerSecond'
MILLI_CORES = 'MilliCores'
MILLI_SECONDS = 'MilliSeconds'
NANO_CORES = 'NanoCores'
PERCENT = 'Percent'
SECONDS = 'Seconds'
UNSPECIFIED = 'Unspecified'
class azure.monitor.query.MetricValue(**kwargs: Any)[source]

Represents a metric value.

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

Variables
  • timestamp (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.MetricsQueryClient(credential: TokenCredential, **kwargs: Any)[source]
Creating the MetricsQueryClient with a TokenCredential.
credential  = DefaultAzureCredential()

client = MetricsQueryClient(credential)
Parameters

credential (TokenCredential) – The credential to authenticate the client.

Keyword Arguments

endpoint (str) – The endpoint to connect to. Defaults to ‘https://management.azure.com’.

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

resource_uri (str) – The identifier of the resource.

Keyword Arguments

namespace (str) – Metric namespace to query metric definitions for.

Returns

An iterator like instance of either MetricDefinitionCollection or the result of cls(response)

Return type

ItemPaged[MetricDefinition]

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 (datetime) – The start time from which to query for metric namespaces. This should be provided as a datetime object.

Returns

An iterator like instance of either MetricNamespace or the result of cls(response)

Return type

ItemPaged[MetricNamespace]

Raises

~azure.core.exceptions.HttpResponseError

query(resource_uri: str, metric_names: list, **kwargs: Optional[timedelta])MetricsResult[source]

Lists the metric values for a resource.

Parameters
  • resource_uri (str) – The identifier of the resource.

  • metric_names (list[str]) – The names of the metrics to retrieve.

Keyword Arguments
  • timespan (timedelta or tuple[datetime, timedelta] or tuple[datetime, datetime]) – The timespan for which to query the data. This can be a timedelta, a timedelta and a start datetime, or a start datetime/end datetime.

  • granularity (timedelta) – The granularity (i.e. timegrain) of the query.

  • aggregations (list[str]) – The list of aggregation types to retrieve. Use azure.monitor.query.MetricAggregationType enum to get each aggregation type.

  • max_results (int) – The maximum number of records to retrieve. Valid only if $filter is specified. Defaults to 10.

  • order_by (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 ‘*’.

  • metric_namespace (str) – Metric namespace to query metric definitions for.

Returns

Response, or the result of cls(response)

Return type

MetricsResult

Raises

~azure.core.exceptions.HttpResponseError

Get a response for a single Metrics Query
metrics_uri = os.environ['METRICS_RESOURCE_URI']
response = client.query(
    metrics_uri,
    metric_names=["Ingress"],
    timespan=timedelta(hours=2),
    granularity=timedelta(minutes=5),
    aggregations=[MetricAggregationType.AVERAGE],
    )

for metric in response.metrics:
    print(metric.name + ' -- ' + metric.display_description)
    for time_series_element in metric.timeseries:
        for metric_value in time_series_element.data:
            print('The ingress at {} is {}'.format(
                metric_value.timestamp,
                metric_value.average
            ))
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.

Variables
  • 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.

  • granularity (timedelta) – The granularity (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 that has been queried.

  • resource_region (str) – The region of the resource that has 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.

Variables
  • metadata_values (dict(str, str)) – The metadata values returned if $filter was specified in the call.

  • data (list[MetricValue]) – An array of data points representing the metric values. This is only returned if a result type of data is specified.