diff --git a/src/OpenTelemetry.Instrumentation.AspNet.TelemetryHttpModule/ActivityHelper.cs b/src/OpenTelemetry.Instrumentation.AspNet.TelemetryHttpModule/ActivityHelper.cs index 569409aa3f..fadcd4b7fa 100644 --- a/src/OpenTelemetry.Instrumentation.AspNet.TelemetryHttpModule/ActivityHelper.cs +++ b/src/OpenTelemetry.Instrumentation.AspNet.TelemetryHttpModule/ActivityHelper.cs @@ -133,6 +133,13 @@ public static void StopAspNetActivity(TextMapPropagator textMapPropagator, Activ var currentActivity = Activity.Current; context.Items[ContextKey] = null; + // Make sure that the activity has a proper end time before onRequestStoppedCallback is called. + // Note that the activity must not be stopped before the callback is called. + if (aspNetActivity.Duration == TimeSpan.Zero) + { + aspNetActivity.SetEndTime(DateTime.UtcNow); + } + try { onRequestStoppedCallback?.Invoke(aspNetActivity, context); diff --git a/src/OpenTelemetry.Instrumentation.AspNet/CHANGELOG.md b/src/OpenTelemetry.Instrumentation.AspNet/CHANGELOG.md index ea5d2bd227..a12e1d0aa2 100644 --- a/src/OpenTelemetry.Instrumentation.AspNet/CHANGELOG.md +++ b/src/OpenTelemetry.Instrumentation.AspNet/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +* Fixed an issue that caused `http.server.duration` metric value to always be set + to `0`. The issue exists in `1.6.0-beta.1` version. + ([#1425](https://github.com/open-telemetry/opentelemetry-dotnet-contrib/pull/1425)) + ## 1.6.0-beta.1 Released 2023-Oct-11 diff --git a/test/OpenTelemetry.Instrumentation.AspNet.Tests/HttpInMetricsListenerTests.cs b/test/OpenTelemetry.Instrumentation.AspNet.Tests/HttpInMetricsListenerTests.cs index cd458aad73..a1cf7c1c24 100644 --- a/test/OpenTelemetry.Instrumentation.AspNet.Tests/HttpInMetricsListenerTests.cs +++ b/test/OpenTelemetry.Instrumentation.AspNet.Tests/HttpInMetricsListenerTests.cs @@ -16,6 +16,7 @@ using System.Collections.Generic; using System.IO; +using System.Threading; using System.Web; using OpenTelemetry.Context.Propagation; using OpenTelemetry.Metrics; @@ -56,6 +57,7 @@ public void HttpDurationMetricIsEmitted() .Build(); var activity = ActivityHelper.StartAspNetActivity(Propagators.DefaultTextMapPropagator, HttpContext.Current, TelemetryHttpModule.Options.OnRequestStartedCallback); + Thread.Sleep(1); // Make sure duration is always greater than 0 to avoid flakiness. ActivityHelper.StopAspNetActivity(Propagators.DefaultTextMapPropagator, activity, HttpContext.Current, TelemetryHttpModule.Options.OnRequestStoppedCallback); meterProvider.ForceFlush(); @@ -77,6 +79,7 @@ public void HttpDurationMetricIsEmitted() Assert.Equal("http.server.duration", exportedItems[0].Name); Assert.Equal(1L, count); Assert.Equal(duration, sum); + Assert.True(duration > 0, "Metric duration should be set."); Assert.Equal(3, metricPoints[0].Tags.Count); string? httpMethod = null;