|
| 1 | +// Copyright The OpenTelemetry Authors |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +using System.Diagnostics; |
| 5 | +using System.Diagnostics.CodeAnalysis; |
| 6 | +using System.Diagnostics.Metrics; |
| 7 | +using System.Reflection; |
| 8 | +using Microsoft.AspNetCore.Http; |
| 9 | +#if NET |
| 10 | +using Microsoft.AspNetCore.Diagnostics; |
| 11 | +using Microsoft.AspNetCore.Routing; |
| 12 | +#endif |
| 13 | +using OpenTelemetry.Internal; |
| 14 | +using OpenTelemetry.Trace; |
| 15 | + |
| 16 | +namespace OpenTelemetry.Instrumentation.AspNetCore.Implementation; |
| 17 | + |
| 18 | +internal sealed class HttpInMetricsListener : ListenerHandler |
| 19 | +{ |
| 20 | + internal const string HttpServerRequestDurationMetricName = "http.server.request.duration"; |
| 21 | + |
| 22 | + internal const string OnUnhandledHostingExceptionEvent = "Microsoft.AspNetCore.Hosting.UnhandledException"; |
| 23 | + internal const string OnUnhandledDiagnosticsExceptionEvent = "Microsoft.AspNetCore.Diagnostics.UnhandledException"; |
| 24 | + |
| 25 | + internal static readonly AssemblyName AssemblyName = typeof(HttpInListener).Assembly.GetName(); |
| 26 | + internal static readonly string InstrumentationName = AssemblyName.Name!; |
| 27 | + internal static readonly string InstrumentationVersion = AssemblyName.Version!.ToString(); |
| 28 | + internal static readonly Meter Meter = new(InstrumentationName, InstrumentationVersion); |
| 29 | + |
| 30 | + private const string OnStopEvent = "Microsoft.AspNetCore.Hosting.HttpRequestIn.Stop"; |
| 31 | + |
| 32 | + private static readonly PropertyFetcher<Exception> ExceptionPropertyFetcher = new("Exception"); |
| 33 | + private static readonly PropertyFetcher<HttpContext> HttpContextPropertyFetcher = new("HttpContext"); |
| 34 | + private static readonly object ErrorTypeHttpContextItemsKey = new(); |
| 35 | + |
| 36 | + private static readonly Histogram<double> HttpServerRequestDuration = Meter.CreateHistogram<double>(HttpServerRequestDurationMetricName, "s", "Duration of HTTP server requests."); |
| 37 | + |
| 38 | + internal HttpInMetricsListener(string name) |
| 39 | + : base(name) |
| 40 | + { |
| 41 | + } |
| 42 | + |
| 43 | + public static void OnExceptionEventWritten(string name, object? payload) |
| 44 | + { |
| 45 | + // We need to use reflection here as the payload type is not a defined public type. |
| 46 | + if (!TryFetchException(payload, out var exc) || !TryFetchHttpContext(payload, out var ctx)) |
| 47 | + { |
| 48 | + AspNetCoreInstrumentationEventSource.Log.NullPayload(nameof(HttpInMetricsListener), nameof(OnExceptionEventWritten), HttpServerRequestDurationMetricName); |
| 49 | + return; |
| 50 | + } |
| 51 | + |
| 52 | + ctx.Items.Add(ErrorTypeHttpContextItemsKey, exc.GetType().FullName); |
| 53 | + |
| 54 | + // See https://github.com/dotnet/aspnetcore/blob/690d78279e940d267669f825aa6627b0d731f64c/src/Hosting/Hosting/src/Internal/HostingApplicationDiagnostics.cs#L252 |
| 55 | + // and https://github.com/dotnet/aspnetcore/blob/690d78279e940d267669f825aa6627b0d731f64c/src/Middleware/Diagnostics/src/DeveloperExceptionPage/DeveloperExceptionPageMiddlewareImpl.cs#L174 |
| 56 | + // this makes sure that top-level properties on the payload object are always preserved. |
| 57 | +#if NET |
| 58 | + [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "The ASP.NET Core framework guarantees that top level properties are preserved")] |
| 59 | +#endif |
| 60 | + static bool TryFetchException(object? payload, [NotNullWhen(true)] out Exception? exc) |
| 61 | + { |
| 62 | + return ExceptionPropertyFetcher.TryFetch(payload, out exc) && exc != null; |
| 63 | + } |
| 64 | +#if NET |
| 65 | + [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "The ASP.NET Core framework guarantees that top level properties are preserved")] |
| 66 | +#endif |
| 67 | + static bool TryFetchHttpContext(object? payload, [NotNullWhen(true)] out HttpContext? ctx) |
| 68 | + { |
| 69 | + return HttpContextPropertyFetcher.TryFetch(payload, out ctx) && ctx != null; |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + public static void OnStopEventWritten(string name, object? payload) |
| 74 | + { |
| 75 | + if (payload is not HttpContext context) |
| 76 | + { |
| 77 | + AspNetCoreInstrumentationEventSource.Log.NullPayload(nameof(HttpInMetricsListener), nameof(OnStopEventWritten), HttpServerRequestDurationMetricName); |
| 78 | + return; |
| 79 | + } |
| 80 | + |
| 81 | + TagList tags = default; |
| 82 | + |
| 83 | + // see the spec https://github.com/open-telemetry/semantic-conventions/blob/v1.21.0/docs/http/http-spans.md |
| 84 | + tags.Add(new KeyValuePair<string, object?>(SemanticConventions.AttributeNetworkProtocolVersion, RequestDataHelper.GetHttpProtocolVersion(context.Request.Protocol))); |
| 85 | + tags.Add(new KeyValuePair<string, object?>(SemanticConventions.AttributeUrlScheme, context.Request.Scheme)); |
| 86 | + tags.Add(new KeyValuePair<string, object?>(SemanticConventions.AttributeHttpResponseStatusCode, TelemetryHelper.GetBoxedStatusCode(context.Response.StatusCode))); |
| 87 | + |
| 88 | + var httpMethod = TelemetryHelper.RequestDataHelper.GetNormalizedHttpMethod(context.Request.Method); |
| 89 | + tags.Add(new KeyValuePair<string, object?>(SemanticConventions.AttributeHttpRequestMethod, httpMethod)); |
| 90 | + |
| 91 | +#if NET |
| 92 | + // Check the exception handler feature first in case the endpoint was overwritten |
| 93 | + var route = (context.Features.Get<IExceptionHandlerPathFeature>()?.Endpoint as RouteEndpoint ?? |
| 94 | + context.GetEndpoint() as RouteEndpoint)?.RoutePattern.RawText; |
| 95 | + if (!string.IsNullOrEmpty(route)) |
| 96 | + { |
| 97 | + tags.Add(new KeyValuePair<string, object?>(SemanticConventions.AttributeHttpRoute, route)); |
| 98 | + } |
| 99 | +#endif |
| 100 | + if (context.Items.TryGetValue(ErrorTypeHttpContextItemsKey, out var errorType)) |
| 101 | + { |
| 102 | + tags.Add(new KeyValuePair<string, object?>(SemanticConventions.AttributeErrorType, errorType)); |
| 103 | + } |
| 104 | + |
| 105 | + // We are relying here on ASP.NET Core to set duration before writing the stop event. |
| 106 | + // https://github.com/dotnet/aspnetcore/blob/d6fa351048617ae1c8b47493ba1abbe94c3a24cf/src/Hosting/Hosting/src/Internal/HostingApplicationDiagnostics.cs#L449 |
| 107 | + // TODO: Follow up with .NET team if we can continue to rely on this behavior. |
| 108 | + HttpServerRequestDuration.Record(Activity.Current!.Duration.TotalSeconds, tags); |
| 109 | + } |
| 110 | + |
| 111 | + public override void OnEventWritten(string name, object? payload) |
| 112 | + { |
| 113 | + switch (name) |
| 114 | + { |
| 115 | + case OnUnhandledDiagnosticsExceptionEvent: |
| 116 | + case OnUnhandledHostingExceptionEvent: |
| 117 | + { |
| 118 | + OnExceptionEventWritten(name, payload); |
| 119 | + } |
| 120 | + |
| 121 | + break; |
| 122 | + case OnStopEvent: |
| 123 | + { |
| 124 | + OnStopEventWritten(name, payload); |
| 125 | + } |
| 126 | + |
| 127 | + break; |
| 128 | + default: |
| 129 | + break; |
| 130 | + } |
| 131 | + } |
| 132 | +} |
0 commit comments