azure.monitor.query package

class azure.monitor.query.LogsBatchQuery(workspace_id: str, query: str, **kwargs: Any)[source]

A single request in a batch. The batch query API accepts a list of these objects.

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]) – Required. 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]

LogsQueryClient. Use this client to collect and organize log and performance data from monitored resources. Data from different sources such as platform logs from Azure services, log and performance data from virtual machines agents, and usage and performance data from apps can be consolidated into a single Azure Log Analytics workspace.

The various data types can be analyzed together using the [Kusto Query Language](https://docs.microsoft.com/azure/data-explorer/kusto/query/)

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_batch(queries: Union[Sequence[Dict], Sequence[LogsBatchQuery]], **kwargs: Any)List[Union[LogsQueryResult, LogsQueryPartialResult, LogsQueryError]][source]

Execute a list of Kusto queries. Each request can be either a LogsBatchQuery object or an equivalent serialized model.

NOTE: 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, LogsQueryPartialResult and LogsQueryError. For a given query, a LogsQueryResult is returned if the response is a success, LogsQueryPartialResult is returned when there is a partial success and a LogsQueryError is returned when there is a failure. The status of each response can be checked using LogsQueryStatus enum.

Return type

list[Union[LogsQueryResult, LogsQueryPartialResult, LogsQueryError]

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['LOGS_WORKSPACE_ID']
    ),
    LogsBatchQuery(
        query= """bad query""",
        timespan=timedelta(days=1),
        workspace_id= os.environ['LOGS_WORKSPACE_ID']
    ),
    LogsBatchQuery(
        query= """let Weight = 92233720368547758;
        range x from 1 to 3 step 1
        | summarize percentilesw(x, Weight * 100, 50)""",
        workspace_id= os.environ['LOGS_WORKSPACE_ID'],
        timespan=(datetime(2021, 6, 2, tzinfo=timezone.utc), datetime(2021, 6, 5, tzinfo=timezone.utc)), # (start, end)
        include_statistics=True
    ),
]
results = client.query_batch(requests)

for res in results:
    if res.status == LogsQueryStatus.FAILURE:
        # this will be a LogsQueryError
        print(res.message)
    elif res.status == LogsQueryStatus.PARTIAL:
        ## this will be a LogsQueryPartialResult
        print(res.partial_error.message)
        for table in res.partial_data:
            df = pd.DataFrame(table.rows, columns=table.columns)
            print(df)
    elif res.status == LogsQueryStatus.SUCCESS:
        ## this will be a LogsQueryResult
        table = res.tables[0]
        df = pd.DataFrame(table.rows, columns=table.columns)
        print(df)


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

Execute a Kusto query.

Executes a Kusto 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]) – Required. 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 if there is a success or LogsQueryPartialResult when there is a partial success.

Return type

Union[LogsQueryResult, LogsQueryPartialResult]

Raises

~azure.core.exceptions.HttpResponseError

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

The code and message for an error.

Variables
  • code (str) – A machine readable error code.

  • message (str) – A human readable error message.

  • status (LogsQueryStatus) – status for error item when iterating over list of results. Always “Failure” for an instance of a LogsQueryError.

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

The LogsQueryPartialResult type is returned when the response of a query is a partial success (or partial failure).

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

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

  • visualization (Mapping) – 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.

  • partial_error (LogsQueryError) – The partial errror info

  • status (LogsQueryStatus) – The status of the result. Always ‘PartialError’ for an instance of a LogsQueryPartialResult.

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

The LogsQueryResult type is returned when the response of a query is a success.

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

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

  • visualization (Mapping) – 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.

  • status (LogsQueryStatus) – The status of the result. Always ‘Success’ for an instance of a LogsQueryResult.

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

The status of the result object.

FAILURE = 'Failure'
PARTIAL = 'PartialError'
SUCCESS = 'Success'
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[str]) – The labels of columns in this table.

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

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

class azure.monitor.query.LogsTableRow(**kwargs: Any)[source]

Represents a single row in logs table. This type is gettable by both column name and column index.

Variables

index (int) – The index of the row in the table

class azure.monitor.query.Metric(**kwargs: Any)[source]

The result data of a single metric name.

Variables
  • id (str) – The metric Id.

  • type (str) – The resource type of the metric resource.

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

  • unit (str) – The unit of the metric. To access these values, use the MetricUnit enum. Possible values include: “Count”, “Bytes”, “Seconds”, “CountPerSecond”, “BytesPerSecond”, “Percent”, “MilliSeconds”, “ByteSeconds”, “Unspecified”, “Cores”, “MilliCores”, “NanoCores”, “BitsPerSecond”.

  • timeseries (list[TimeSeriesElement]) – 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.

  • retention (timedelta) – the retention period for the metric at the specified timegrain.

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.

Variables
  • timestamp (datetime) – The timestamp for the metric value.

  • 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]

MetricsQueryClient should be used to collect numeric data from monitored resources into a time series database. Metrics are numerical values that are collected at regular intervals and describe some aspect of a system at a particular time. Metrics are lightweight and capable of supporting near real-time scenarios, making them particularly useful for alerting and fast detection of issues.

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, **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 MetricDefinition 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(resource_uri: str, metric_names: List[str], **kwargs: Any)MetricsQueryResult[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 ‘*’. To use the split feature, set the value to * - for example, like “City eq ‘*’”

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

Returns

A MetricsQueryResult object.

Return type

MetricsQueryResult

Raises

~azure.core.exceptions.HttpResponseError

class azure.monitor.query.MetricsQueryResult(**kwargs: Any)[source]

The response to a metrics query.

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.