Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

OWIN HTTP server metrics #1335

Merged
merged 27 commits into from
Sep 20, 2023
Merged
Show file tree
Hide file tree
Changes from 22 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
fa1937a
http duration when tracing is active
matt-hensley Aug 29, 2023
f734900
modify tests to add metrics, and metrics + traces
matt-hensley Aug 29, 2023
1e825c1
stopwatch logic when tracing isn't active / trace was filtered
matt-hensley Aug 29, 2023
88276d4
mark MetricProviderBuilder extension as part of public API
matt-hensley Aug 29, 2023
9857844
changelog entry
matt-hensley Aug 29, 2023
35ffb29
taglist -> individual tags for perf
matt-hensley Aug 30, 2023
8977a90
remove stopwatch allocation, manually calculate duration
matt-hensley Aug 30, 2023
9a0f425
ticks -> ms
matt-hensley Aug 31, 2023
71ed715
give extension class a unique name for docs generation
matt-hensley Aug 31, 2023
38fb761
simplify conditional
matt-hensley Aug 31, 2023
4d8d3b7
Merge branch 'main' into owinmetrics
matt-hensley Aug 31, 2023
551a912
fix public api for renamed class
matt-hensley Sep 1, 2023
bb6fa24
Merge branch 'owinmetrics' of https://github.com/matt-hensley/opentel…
matt-hensley Sep 1, 2023
29093a2
missed TagList usage
matt-hensley Sep 7, 2023
12dc9e0
Merge branch 'main' into owinmetrics
matt-hensley Sep 7, 2023
b9c284c
correct name in file header
matt-hensley Sep 12, 2023
8350c46
Merge branch 'main' into owinmetrics
matt-hensley Sep 12, 2023
8b69c44
change metric unit to seconds
matt-hensley Sep 13, 2023
35f36e6
use 1.21.0 semantic convention names
matt-hensley Sep 13, 2023
2658c94
correct meter name
matt-hensley Sep 15, 2023
51e3091
correct metric name in test
matt-hensley Sep 17, 2023
f0c94dd
Merge branch 'main' into owinmetrics
utpilla Sep 18, 2023
62b340d
fix unit in test
matt-hensley Sep 19, 2023
9f529e3
Merge branch 'main' into owinmetrics
matt-hensley Sep 19, 2023
326e9e0
ammend docs with metrics, include note about metrics/traces being sep…
matt-hensley Sep 19, 2023
c7ac227
fix markdown linting errors
matt-hensley Sep 20, 2023
283e80f
Merge branch 'main' into owinmetrics
utpilla Sep 20, 2023
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
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@ OpenTelemetry.Instrumentation.Owin.OwinInstrumentationOptions.Filter.set -> void
OpenTelemetry.Instrumentation.Owin.OwinInstrumentationOptions.OwinInstrumentationOptions() -> void
OpenTelemetry.Instrumentation.Owin.OwinInstrumentationOptions.RecordException.get -> bool
OpenTelemetry.Instrumentation.Owin.OwinInstrumentationOptions.RecordException.set -> void
OpenTelemetry.Metrics.OwinInstrumentationMeterProviderBuilderExtensions
OpenTelemetry.Trace.TracerProviderBuilderExtensions
Owin.AppBuilderExtensions
static OpenTelemetry.Metrics.OwinInstrumentationMeterProviderBuilderExtensions.AddOwinInstrumentation(this OpenTelemetry.Metrics.MeterProviderBuilder builder) -> OpenTelemetry.Metrics.MeterProviderBuilder
static OpenTelemetry.Trace.TracerProviderBuilderExtensions.AddOwinInstrumentation(this OpenTelemetry.Trace.TracerProviderBuilder builder) -> OpenTelemetry.Trace.TracerProviderBuilder
static OpenTelemetry.Trace.TracerProviderBuilderExtensions.AddOwinInstrumentation(this OpenTelemetry.Trace.TracerProviderBuilder builder, System.Action<OpenTelemetry.Instrumentation.Owin.OwinInstrumentationOptions> configure) -> OpenTelemetry.Trace.TracerProviderBuilder
static Owin.AppBuilderExtensions.UseOpenTelemetry(this Owin.IAppBuilder appBuilder) -> Owin.IAppBuilder
2 changes: 2 additions & 0 deletions src/OpenTelemetry.Instrumentation.Owin/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
([#1344](https://github.com/open-telemetry/opentelemetry-dotnet-contrib/pull/1344))
* Removes `AddOwinInstrumentation` method with default configure parameter.
([#929](https://github.com/open-telemetry/opentelemetry-dotnet-contrib/pull/929))
* Adds HTTP server metrics via `AddOwinInstrumentation` extension method on `MeterProviderBuilder`
([#1335](https://github.com/open-telemetry/opentelemetry-dotnet-contrib/pull/1335))

## 1.0.0-rc.3

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
using System.Threading.Tasks;
using Microsoft.Owin;
using OpenTelemetry.Context.Propagation;
using OpenTelemetry.Instrumentation.Owin.Implementation;
using OpenTelemetry.Trace;

namespace OpenTelemetry.Instrumentation.Owin;
Expand All @@ -46,15 +47,23 @@ public DiagnosticsMiddleware(OwinMiddleware next)
/// <inheritdoc />
public override async Task Invoke(IOwinContext owinContext)
{
long startTimestamp = -1;

try
{
BeginRequest(owinContext);

if (OwinInstrumentationMetrics.HttpServerDuration.Enabled && !owinContext.Environment.ContainsKey(ContextKey))
{
startTimestamp = Stopwatch.GetTimestamp();
}

await this.Next.Invoke(owinContext).ConfigureAwait(false);
RequestEnd(owinContext, null);
RequestEnd(owinContext, null, startTimestamp);
}
catch (Exception ex)
{
RequestEnd(owinContext, ex);
RequestEnd(owinContext, ex, startTimestamp);
throw;
}
}
Expand Down Expand Up @@ -151,7 +160,7 @@ private static void BeginRequest(IOwinContext owinContext)
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void RequestEnd(IOwinContext owinContext, Exception exception)
private static void RequestEnd(IOwinContext owinContext, Exception exception, long startTimestamp)
{
if (owinContext.Environment.TryGetValue(ContextKey, out object context)
&& context is Activity activity)
Expand Down Expand Up @@ -199,11 +208,32 @@ private static void RequestEnd(IOwinContext owinContext, Exception exception)

activity.Stop();

if (OwinInstrumentationMetrics.HttpServerDuration.Enabled)
{
OwinInstrumentationMetrics.HttpServerDuration.Record(
activity.Duration.TotalSeconds,
new(SemanticConventions.AttributeHttpRequestMethod, owinContext.Request.Method),
new(SemanticConventions.AttributeUrlScheme, owinContext.Request.Scheme),
new(SemanticConventions.AttributeHttpResponseStatusCode, owinContext.Response.StatusCode));
}

if (!(Propagators.DefaultTextMapPropagator is TraceContextPropagator))
{
Baggage.Current = default;
}
}
else if (OwinInstrumentationMetrics.HttpServerDuration.Enabled)
{
var endTimestamp = Stopwatch.GetTimestamp();
var duration = endTimestamp - startTimestamp;
var durationS = duration / Stopwatch.Frequency;

OwinInstrumentationMetrics.HttpServerDuration.Record(
durationS,
new(SemanticConventions.AttributeHttpRequestMethod, owinContext.Request.Method),
new(SemanticConventions.AttributeUrlScheme, owinContext.Request.Scheme),
new(SemanticConventions.AttributeHttpResponseStatusCode, owinContext.Response.StatusCode));
}
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// <copyright file="OwinInstrumentationMetrics.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>

using System.Diagnostics.Metrics;
using System.Reflection;

namespace OpenTelemetry.Instrumentation.Owin.Implementation;

internal static class OwinInstrumentationMetrics
{
internal static readonly AssemblyName AssemblyName = typeof(OwinInstrumentationMetrics).Assembly.GetName();

public static string MeterName => AssemblyName.Name;

public static Meter Instance => new Meter(MeterName, AssemblyName.Version.ToString());

public static Histogram<double> HttpServerDuration => Instance.CreateHistogram<double>("http.server.request.duration", "s", "Measures the duration of inbound HTTP requests.");
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// <copyright file="OwinInstrumentationMeterProviderBuilderExtensions.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>

using OpenTelemetry.Instrumentation.Owin.Implementation;
using OpenTelemetry.Internal;

namespace OpenTelemetry.Metrics;

/// <summary>
/// Extension methods to simplify registering of OWIN request instrumentation.
/// </summary>
public static class OwinInstrumentationMeterProviderBuilderExtensions
{
/// <summary>
/// Enables the incoming requests automatic data collection for OWIN.
/// </summary>
/// <param name="builder"><see cref="MeterProviderBuilder"/> being configured.</param>
/// <returns>The instance of <see cref="MeterProviderBuilder"/> to chain the calls.</returns>
public static MeterProviderBuilder AddOwinInstrumentation(
this MeterProviderBuilder builder)
{
Guard.ThrowIfNull(builder);

builder.AddMeter(OwinInstrumentationMetrics.MeterName);
return builder;
}
}
6 changes: 6 additions & 0 deletions src/Shared/SemanticConventions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,5 +108,11 @@ internal static class SemanticConventions
public const string AttributeExceptionType = "exception.type";
public const string AttributeExceptionMessage = "exception.message";
public const string AttributeExceptionStacktrace = "exception.stacktrace";

// v1.21.0
// https://github.com/open-telemetry/semantic-conventions/blob/v1.21.0/docs/http/http-metrics.md#http-server
public const string AttributeHttpRequestMethod = "http.request.method"; // replaces: "http.method" (AttributeHttpMethod)
public const string AttributeHttpResponseStatusCode = "http.response.status_code"; // replaces: "http.status_code" (AttributeHttpStatusCode)
public const string AttributeUrlScheme = "url.scheme"; // replaces: "http.scheme" (AttributeHttpScheme)
#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
using System.Web.Http;
using Microsoft.Owin;
using Microsoft.Owin.Hosting;
using OpenTelemetry.Instrumentation.Owin.Implementation;
using OpenTelemetry.Metrics;
using OpenTelemetry.Trace;
using Owin;
using Xunit;
Expand Down Expand Up @@ -106,27 +108,43 @@ public void Dispose()
}

[Theory]
[InlineData(true, false)]
[InlineData(true, true)]
[InlineData(false)]
[InlineData(true, false, false)]
[InlineData(true, false, true)]
[InlineData(true, false, true, true)]
[InlineData(true, false, false, false, true)]
[InlineData(true, false, false, false, true, true)]
[InlineData(true, false, false, true)]
[InlineData(true, false, false, true, true)]
[InlineData(true, false, false, false, false, true)]
[InlineData(true, false, false, false, false, true, true)]
[InlineData(true, true, false)]
[InlineData(true, true, true)]
[InlineData(true, true, false, true)]
[InlineData(true, true, false, true, true)]
[InlineData(true, true, false, false, false, true)]
[InlineData(true, true, false, false, false, true, true)]
[InlineData(false, true, false)]
[InlineData(false, true, true)]
[InlineData(false, true, false, true)]
[InlineData(false, true, false, true, true)]
[InlineData(false, true, false, false, false, true)]
[InlineData(false, true, false, false, false, true, true)]
[InlineData(false, false)]
public async Task OutgoingRequestInstrumentationTest(
bool instrument,
bool instrumentTraces,
bool instrumentMetrics,
bool filter = false,
bool enrich = false,
bool enrichmentException = false,
bool generateRemoteException = false,
bool recordException = false)
{
List<Activity> stoppedActivities = new List<Activity>();
List<Metric> exportedMetrics = new List<Metric>();

var builder = Sdk.CreateTracerProviderBuilder()
.AddInMemoryExporter(stoppedActivities);
var meterBuilder = Sdk.CreateMeterProviderBuilder()
.AddInMemoryExporter(exportedMetrics);

if (instrument)
if (instrumentTraces)
{
builder
.AddOwinInstrumentation(options =>
Expand Down Expand Up @@ -159,7 +177,13 @@ public async Task OutgoingRequestInstrumentationTest(
});
}

if (instrumentMetrics)
{
meterBuilder.AddOwinInstrumentation();
}

using TracerProvider tracerProvider = builder.Build();
using MeterProvider meterProvider = meterBuilder.Build();

using HttpClient client = new HttpClient();

Expand All @@ -177,7 +201,7 @@ Owin has finished to inspect the activity status. */

Assert.True(this.requestCompleteHandle.WaitOne(3000));

if (instrument)
if (instrumentTraces)
{
if (!filter)
{
Expand Down Expand Up @@ -222,5 +246,63 @@ Owin has finished to inspect the activity status. */
{
Assert.Empty(stoppedActivities);
}

if (instrumentMetrics)
{
meterProvider.Dispose();
var metric = exportedMetrics[0];
var metricPoints = this.GetMetricPoints(metric);
var metricPoint = Assert.Single(metricPoints);

Assert.Equal(OwinInstrumentationMetrics.MeterName, metric.MeterName);
Assert.Equal("http.server.request.duration", metric.Name);
Assert.Equal(MetricType.Histogram, metric.MetricType);
Assert.Equal(1, metricPoint.GetHistogramCount());
Assert.Equal(3, metricPoint.Tags.Count);

foreach (var tag in metricPoint.Tags)
{
switch (tag.Key)
{
case SemanticConventions.AttributeHttpMethod:
Assert.Equal("GET", tag.Value);
break;
case SemanticConventions.AttributeHttpScheme:
Assert.Equal(requestUri.Scheme, tag.Value);
break;
case SemanticConventions.AttributeHttpStatusCode:
Assert.Equal(generateRemoteException ? 500 : 200, tag.Value);
break;
}
}
}
else
{
Assert.Empty(exportedMetrics);
}

if (instrumentMetrics && instrumentTraces && !filter)
{
var metric = Assert.Single(exportedMetrics);
var activity = Assert.Single(stoppedActivities);
var metricPoints = this.GetMetricPoints(metric);
var metricPoint = Assert.Single(metricPoints);

// metric value and span duration should match
// https://github.com/open-telemetry/semantic-conventions/blob/main/docs/http/http-metrics.md#metric-httpserverrequestduration
Assert.Equal(activity.Duration.TotalMilliseconds, metricPoint.GetHistogramSum());
matt-hensley marked this conversation as resolved.
Show resolved Hide resolved
matt-hensley marked this conversation as resolved.
Show resolved Hide resolved
}
}

private List<MetricPoint> GetMetricPoints(Metric metric)
{
List<MetricPoint> metricPoints = new();

foreach (var metricPoint in metric.GetMetricPoints())
{
metricPoints.Add(metricPoint);
}

return metricPoints;
}
}
Loading