Skip to content

Commit

Permalink
[Instrumentation.AspNet] Fix metric http.server.duration always being…
Browse files Browse the repository at this point in the history
… zero (#1425)

Co-authored-by: Vishwesh Bankwar <[email protected]>
  • Loading branch information
qhris and vishweshbankwar authored Nov 6, 2023
1 parent 157412c commit 57a311c
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
4 changes: 4 additions & 0 deletions src/OpenTelemetry.Instrumentation.AspNet/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Web;
using OpenTelemetry.Context.Propagation;
using OpenTelemetry.Metrics;
Expand Down Expand Up @@ -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();
Expand All @@ -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;
Expand Down

0 comments on commit 57a311c

Please sign in to comment.