class MetricsPerfTest(PerfStressTest):
    def __init__(self, arguments):
        super().__init__(arguments)

        # auth configuration
        self.metrics_uri = self.get_from_env('METRICS_RESOURCE_URI')
        self.names = ["MatchedEventCount"]
        self.aggregations = [MetricAggregationType.COUNT]

        # Create clients
        self.metrics_client = SyncMetricsQueryClient(
            credential=SyncDefaultAzureCredential())
        self.async_metrics_client = AsyncMetricsQueryClient(
            credential=AsyncDefaultAzureCredential())

    async def close(self):
        """This is run after cleanup.
        
        Use this to close any open handles or clients.
        """
        await self.async_metrics_client.close()
        await super().close()

    def run_sync(self):
        """The synchronous perf test.
        
        Try to keep this minimal and focused. Using only a single client API.
        Avoid putting any ancillary logic (e.g. generating UUIDs), and put this in the setup/init instead
        so that we're only measuring the client API call.
        """
        self.metrics_client.query_resource(self.metrics_uri,
                                           self.names,
                                           aggregations=self.aggregations)

    async def run_async(self):
        """The asynchronous perf test.
        
        Try to keep this minimal and focused. Using only a single client API.
        Avoid putting any ancillary logic (e.g. generating UUIDs), and put this in the setup/init instead
        so that we're only measuring the client API call.
        """
        await self.async_metrics_client.query_resource(
            self.metrics_uri, self.names, aggregations=self.aggregations)
def test_metrics_auth():
    credential = _credential()
    client = MetricsQueryClient(credential)
    response = client.query_resource(
        os.environ['METRICS_RESOURCE_URI'],
        metric_names=["MatchedEventCount"],
        timespan=timedelta(days=1),
        aggregations=[MetricAggregationType.COUNT])
    assert response
    assert response.metrics
def test_metrics_filter():
    credential = _credential()
    client = MetricsQueryClient(credential)
    response = client.query_resource(
        os.environ['METRICS_RESOURCE_URI'],
        metric_names=["MatchedEventCount"],
        timespan=timedelta(days=1),
        granularity=timedelta(minutes=5),
        filter="EventSubscriptionName eq '*'",
        aggregations=[MetricAggregationType.COUNT])
    assert response
    metric = response.metrics['MatchedEventCount']
    for t in metric.timeseries:
        assert t.metadata_values is not None
def test_metrics_list():
    credential = _credential()
    client = MetricsQueryClient(credential)
    response = client.query_resource(
        os.environ['METRICS_RESOURCE_URI'],
        metric_names=["MatchedEventCount"],
        timespan=timedelta(days=1),
        granularity=timedelta(minutes=5),
        aggregations=[MetricAggregationType.COUNT])
    assert response
    metrics = response.metrics
    assert len(metrics) == 1
    assert metrics[0].__class__ == Metric
    assert metrics['MatchedEventCount'].__class__ == Metric
    assert metrics['MatchedEventCount'] == metrics[0]
import urllib3
from azure.monitor.query import MetricsQueryClient, MetricAggregationType
from azure.identity import DefaultAzureCredential

# provide a cert or disable warnings to run this sample
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# [START metrics_client_auth_with_token_cred]
credential = DefaultAzureCredential()

client = MetricsQueryClient(credential)
# [END metrics_client_auth_with_token_cred]

# [START send_metrics_query]
metrics_uri = os.environ.get('METRICS_RESOURCE_URI')
response = client.query_resource(
    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))
# [END send_metrics_query]