Skip to content
Merged

timespan #19110

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
19 changes: 18 additions & 1 deletion sdk/monitor/azure-monitor-query/azure/monitor/query/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------

import re
from typing import TYPE_CHECKING
from azure.core.exceptions import HttpResponseError
from azure.core.pipeline.policies import BearerTokenCredentialPolicy
from msrest import Serializer

if TYPE_CHECKING:
from azure.core.credentials import TokenCredential
Expand Down Expand Up @@ -48,3 +49,19 @@ def order_results(request_order, responses):
mapping = {item.id: item for item in responses}
ordered = [mapping[id] for id in request_order]
return ordered

def construct_iso8601(start=None, end=None, duration=None):
if start is not None:
start = Serializer.serialize_iso(start)
if end is not None:
end = Serializer.serialize_iso(end)
return start + '/' + end
elif duration is not None:
return start + '/' + duration
else:
raise ValueError("Start time must be provided aling with duration or end time.")
elif end is not None:
end = Serializer.serialize_iso(end)
return duration + '/' + end
else:
return duration
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from ._generated._monitor_query_client import MonitorQueryClient

from ._generated.models import BatchRequest
from ._helpers import get_authentication_policy, process_error
from ._helpers import get_authentication_policy, process_error, construct_iso8601
from ._models import LogsQueryResults, LogsQueryRequest, LogsQueryBody, LogsBatchResults

if TYPE_CHECKING:
Expand Down Expand Up @@ -51,9 +51,13 @@ def query(self, workspace_id, query, **kwargs):
:param query: The Analytics query. Learn more about the `Analytics query syntax
<https://azure.microsoft.com/documentation/articles/app-insights-analytics-reference/>`_.
:type query: str
:keyword str timespan: Optional. The timespan over which to query data. This is an ISO8601 time
period value. This timespan is applied in addition to any that are specified in the query
expression.
:keyword datetime start_time: The start time from which to query the data. This should be accompanied
with either end_time or duration.
:keyword datetime end_time: The end time till which to query the data. This should be accompanied
with either start_time or duration.
:keyword str duration: 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. This should be provided in a ISO8601 string format like 'PT1H', 'P1Y2M10DT2H30M'.
:keyword int server_timeout: the server timeout in seconds. The default timeout is 3 minutes,
and the maximum timeout is 10 minutes.
:keyword bool include_statistics: To get information about query statistics.
Expand All @@ -72,7 +76,10 @@ def query(self, workspace_id, query, **kwargs):
:rtype: ~azure.monitor.query.LogsQueryResults
:raises: ~azure.core.exceptions.HttpResponseError
"""
timespan = kwargs.pop("timespan", None)
start = kwargs.pop('start_time', None)
end = kwargs.pop('end_time', None)
duration = kwargs.pop('duration', None)
timespan = construct_iso8601(start, end, duration)
include_statistics = kwargs.pop("include_statistics", False)
include_render = kwargs.pop("include_render", False)
server_timeout = kwargs.pop("server_timeout", None)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,14 @@

# pylint: disable=anomalous-backslash-in-string

from datetime import time
from typing import TYPE_CHECKING, Any

from ._generated._monitor_query_client import (
MonitorQueryClient,
)

from ._models import MetricsResult, MetricDefinition, MetricNamespace
from ._helpers import get_metrics_authentication_policy
from ._helpers import get_metrics_authentication_policy, construct_iso8601

if TYPE_CHECKING:
from azure.core.credentials import TokenCredential
Expand Down Expand Up @@ -44,17 +43,21 @@ def __init__(self, credential, **kwargs):
self._namespace_op = self._client.metric_namespaces
self._definitions_op = self._client.metric_definitions

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

:param resource_uri: The identifier of the resource.
:type resource_uri: str
:param metric_names: The names of the metrics to retrieve.
:type metric_names: list
:param timespan: The timespan of the query. It is a string with the following format
'startDateTime_ISO/endDateTime_ISO'.
:type timespan: str
:keyword datetime start_time: The start time from which to query the data. This should be accompanied
with either end_time or duration.
:keyword datetime end_time: The end time till which to query the data. This should be accompanied
with either start_time or duration.
:keyword str duration: 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. This should be provided in a ISO8601 string format like 'PT1H', 'P1Y2M10DT2H30M'.
:keyword interval: The interval (i.e. timegrain) of the query.
:paramtype interval: ~datetime.timedelta
:keyword aggregation: The list of aggregation types (comma separated) to retrieve.
Expand Down Expand Up @@ -86,6 +89,10 @@ def query(self, resource_uri, metric_names, timespan=None, **kwargs):
:rtype: ~azure.monitor.query.MetricsResult
:raises: ~azure.core.exceptions.HttpResponseError
"""
start = kwargs.pop('start_time', None)
end = kwargs.pop('end_time', None)
duration = kwargs.pop('duration', None)
timespan = construct_iso8601(start, end, duration)
kwargs.setdefault("metricnames", ",".join(metric_names))
kwargs.setdefault("timespan", timespan)
generated = self._metrics_op.list(resource_uri, connection_verify=False, **kwargs)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from .._generated.aio._monitor_query_client import MonitorQueryClient

from .._generated.models import BatchRequest
from .._helpers import get_authentication_policy, process_error
from .._helpers import get_authentication_policy, process_error, construct_iso8601
from .._models import LogsQueryResults, LogsQueryRequest, LogsQueryBody, LogsBatchResults

if TYPE_CHECKING:
Expand Down Expand Up @@ -47,9 +47,13 @@ async def query(self, workspace_id: str, query: str, **kwargs: Any) -> LogsQuery
:param query: The Analytics query. Learn more about the `Analytics query syntax
<https://azure.microsoft.com/documentation/articles/app-insights-analytics-reference/>`_.
:type query: str
:keyword ~datetime.timedelta timespan: Optional. The timespan over which to query data. This is an ISO8601 time
period value. This timespan is applied in addition to any that are specified in the query
expression.
:keyword datetime start_time: The start time from which to query the data. This should be accompanied
with either end_time or duration.
:keyword datetime end_time: The end time till which to query the data. This should be accompanied
with either start_time or duration.
:keyword str duration: 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. This should be provided in a ISO8601 string format like 'PT1H', 'P1Y2M10DT2H30M'.
:keyword int server_timeout: the server timeout. The default timeout is 3 minutes,
and the maximum timeout is 10 minutes.
:keyword bool include_statistics: To get information about query statistics.
Expand All @@ -68,7 +72,10 @@ async def query(self, workspace_id: str, query: str, **kwargs: Any) -> LogsQuery
:rtype: ~azure.monitor.query.LogsQueryResults
:raises: ~azure.core.exceptions.HttpResponseError
"""
timespan = kwargs.pop("timespan", None)
start = kwargs.pop('start_time', None)
end = kwargs.pop('end_time', None)
duration = kwargs.pop('duration', None)
timespan = construct_iso8601(start, end, duration)
include_statistics = kwargs.pop("include_statistics", False)
include_render = kwargs.pop("include_render", False)
server_timeout = kwargs.pop("server_timeout", None)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
MonitorQueryClient,
)
from .._models import MetricsResult, MetricDefinition, MetricNamespace
from .._helpers import get_metrics_authentication_policy
from .._helpers import get_metrics_authentication_policy, construct_iso8601

if TYPE_CHECKING:
from azure.core.credentials_async import AsyncTokenCredential
Expand All @@ -41,16 +41,20 @@ def __init__(self, credential: "AsyncTokenCredential", **kwargs: Any) -> None:
self._namespace_op = self._client.metric_namespaces
self._definitions_op = self._client.metric_definitions

async def query(self, resource_uri: str, metric_names: List, timespan :str = None, **kwargs: Any) -> MetricsResult:
async def query(self, resource_uri: str, metric_names: List, **kwargs: Any) -> MetricsResult:
"""Lists the metric values for a resource.

:param resource_uri: The identifier of the resource.
:type resource_uri: str
:param metric_names: The names of the metrics to retrieve.
:type metric_names: list
:param timespan: The timespan of the query. It is a string with the following format
'startDateTime_ISO/endDateTime_ISO'.
:type timespan: str
:keyword datetime start_time: The start time from which to query the data. This should be accompanied
with either end_time or duration.
:keyword datetime end_time: The end time till which to query the data. This should be accompanied
with either start_time or duration.
:keyword str duration: 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. This should be provided in a ISO8601 string format like 'PT1H', 'P1Y2M10DT2H30M'.
:keyword interval: The interval (i.e. timegrain) of the query.
:paramtype interval: ~datetime.timedelta
:keyword aggregation: The list of aggregation types (comma separated) to retrieve.
Expand Down Expand Up @@ -82,6 +86,10 @@ async def query(self, resource_uri: str, metric_names: List, timespan :str = Non
:rtype: ~azure.monitor.query.MetricsResult
:raises: ~azure.core.exceptions.HttpResponseError
"""
start = kwargs.pop('start_time', None)
end = kwargs.pop('end_time', None)
duration = kwargs.pop('duration', None)
timespan = construct_iso8601(start, end, duration)
kwargs.setdefault("metric_names", ",".join(metric_names))
kwargs.setdefault("timespan", timespan)
generated = await self._metrics_op.list(resource_uri, connection_verify=False, **kwargs)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

import os
import pandas as pd
from datetime import timedelta
from datetime import datetime
from azure.monitor.query import LogsQueryClient
from azure.identity import ClientSecretCredential

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
# Licensed under the MIT License.

import os
from datetime import datetime
import urllib3
from azure.monitor.query import MetricsQueryClient
from azure.identity import ClientSecretCredential
Expand All @@ -20,12 +21,13 @@
response = client.query(
metrics_uri,
metric_names=["PublishSuccessCount"],
timespan='P2D'
start_time=datetime(2021, 5, 25),
duration='P1D'
)

for metric in response.metrics:
print(metric.name)
for time_series_element in metric.timeseries:
for metric_value in time_series_element.data:
print(metric_value.time_stamp)