/// <summary> /// Queries Azure Monitor to get the latest value for a specific metric /// </summary> /// <param name="metricName">Name of the metric</param> /// <param name="metricDimension">Name of dimension to split metric on</param> /// <param name="aggregationType">Aggregation for the metric to use</param> /// <param name="aggregationInterval">Interval that is used to aggregate metrics</param> /// <param name="resourceId">Id of the resource to query</param> /// <param name="metricFilter">Optional filter to filter out metrics</param> /// <returns>Latest representation of the metric</returns> public async Task <List <MeasuredMetric> > QueryMetricAsync(string metricName, string metricDimension, AggregationType aggregationType, TimeSpan aggregationInterval, string resourceId, string metricFilter = null) { Guard.NotNullOrWhitespace(metricName, nameof(metricName)); Guard.NotNullOrWhitespace(resourceId, nameof(resourceId)); // Get all metrics var startQueryingTime = DateTime.UtcNow; var metricsDefinitions = await _authenticatedAzureSubscription.MetricDefinitions.ListByResourceAsync(resourceId); var metricDefinition = metricsDefinitions.SingleOrDefault(definition => definition.Name.Value.ToUpper() == metricName.ToUpper()); if (metricDefinition == null) { throw new MetricNotFoundException(metricName); } var closestAggregationInterval = DetermineAggregationInterval(metricName, aggregationInterval, metricDefinition.MetricAvailabilities); // Get the most recent metric var relevantMetric = await GetRelevantMetric(metricName, aggregationType, closestAggregationInterval, metricFilter, metricDimension, metricDefinition, startQueryingTime); if (relevantMetric.Timeseries.Count < 1) { throw new MetricInformationNotFoundException(metricName, "No time series was found"); } var measuredMetrics = new List <MeasuredMetric>(); foreach (var timeseries in relevantMetric.Timeseries) { // Get the most recent value for that metric, that has a finished time series // We need to shift the time to ensure that the time series is finalized and not report invalid values var maxTimeSeriesTime = startQueryingTime.AddMinutes(closestAggregationInterval.TotalMinutes); var mostRecentMetricValue = GetMostRecentMetricValue(metricName, timeseries, maxTimeSeriesTime); // Get the metric value according to the requested aggregation type var requestedMetricAggregate = InterpretMetricValue(aggregationType, mostRecentMetricValue); var measuredMetric = string.IsNullOrWhiteSpace(metricDimension) ? MeasuredMetric.CreateWithoutDimension(requestedMetricAggregate) : MeasuredMetric.CreateForDimension(requestedMetricAggregate, metricDimension, timeseries); measuredMetrics.Add(measuredMetric); } return(measuredMetrics); }