-
-
Notifications
You must be signed in to change notification settings - Fork 205
/
SentryTracingMiddleware.cs
208 lines (182 loc) · 7.4 KB
/
SentryTracingMiddleware.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
using System.Runtime.ExceptionServices;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Sentry.AspNetCore.Extensions;
using Sentry.Extensibility;
namespace Sentry.AspNetCore
{
/// <summary>
/// Sentry tracing middleware for ASP.NET Core
/// </summary>
internal class SentryTracingMiddleware
{
internal const string UnknownRouteTransactionName = "Unknown Route";
private const string OperationName = "http.server";
private readonly RequestDelegate _next;
private readonly Func<IHub> _getHub;
private readonly SentryAspNetCoreOptions _options;
public SentryTracingMiddleware(
RequestDelegate next,
Func<IHub> getHub,
IOptions<SentryAspNetCoreOptions> options)
{
_next = next;
_getHub = getHub;
_options = options.Value;
}
private SentryTraceHeader? TryGetSentryTraceHeader(HttpContext context)
{
var value = context.Request.Headers.GetValueOrDefault(SentryTraceHeader.HttpHeaderName);
if (string.IsNullOrWhiteSpace(value))
{
return null;
}
_options.LogDebug("Received Sentry trace header '{0}'.", value);
try
{
return SentryTraceHeader.Parse(value);
}
catch (Exception ex)
{
_options.LogError("Invalid Sentry trace header '{0}'.", ex, value);
return null;
}
}
private ITransaction? TryStartTransaction(HttpContext context)
{
try
{
var hub = _getHub();
// Attempt to start a transaction from the trace header if it exists
var traceHeader = TryGetSentryTraceHeader(context);
// It's important to try and set the transaction name
// to some value here so that it's available for use
// in sampling.
// At a later stage, we will try to get the transaction name
// again, to account for the other middlewares that may have
// ran after ours.
var transactionName =
context.TryGetTransactionName();
var transactionContext = traceHeader is not null
? new TransactionContext(transactionName ?? string.Empty, OperationName, traceHeader)
: new TransactionContext(transactionName ?? string.Empty, OperationName);
var customSamplingContext = new Dictionary<string, object?>(3, StringComparer.Ordinal)
{
[SamplingExtensions.KeyForHttpMethod] = context.Request.Method,
[SamplingExtensions.KeyForHttpRoute] = context.TryGetRouteTemplate(),
[SamplingExtensions.KeyForHttpPath] = context.Request.Path.Value
};
var transaction = hub.StartTransaction(transactionContext, customSamplingContext);
_options.LogInfo(
"Started transaction with span ID '{0}' and trace ID '{1}'.",
transaction.SpanId,
transaction.TraceId);
return transaction;
}
catch (Exception ex)
{
_options.LogError("Failed to start transaction.", ex);
return null;
}
}
/// <summary>
/// Handles the <see cref="HttpContext"/>.
/// </summary>
public async Task InvokeAsync(HttpContext context)
{
var hub = _getHub();
if (!hub.IsEnabled)
{
await _next(context).ConfigureAwait(false);
return;
}
var transaction = TryStartTransaction(context);
var initialName = transaction?.Name;
// Expose the transaction on the scope so that the user
// can retrieve it and start child spans off of it.
hub.ConfigureScope(scope =>
{
scope.Transaction = transaction;
});
Exception? exception = null;
try
{
await _next(context).ConfigureAwait(false);
}
catch (Exception e)
{
exception = e;
}
finally
{
if (transaction is not null)
{
// The Transaction name was altered during the pipeline execution,
// That could be done by user interference or by some Event Capture
// That triggers ScopeExtensions.Populate.
if (transaction.Name != initialName)
{
_options.LogDebug(
"transaction name set from '{0}' to '{1}' during request pipeline execution.",
initialName,
transaction.Name);
}
// try to get the transaction name.
else if (context.TryGetTransactionName() is { } transactionName &&
!string.IsNullOrEmpty(transactionName))
{
_options.LogDebug(
"Changed transaction '{0}', name set to '{1}' after request pipeline executed.",
transaction.SpanId,
transactionName);
transaction.Name = transactionName;
}
var status = SpanStatusConverter.FromHttpStatusCode(context.Response.StatusCode);
// If no Name was found for Transaction, fallback to UnknownRoute name.
if (transaction.Name == string.Empty)
{
transaction.Name = UnknownRouteTransactionName;
}
if (exception is null)
{
transaction.Finish(status);
}
// Status code not yet changed to 500 but an exception does exist
// so lets avoid passing the misleading 200 down and close only with
// the exception instance that will be inferred as errored.
else if (status == SpanStatus.Ok)
{
transaction.Finish(exception);
}
else
{
transaction.Finish(exception, status);
}
}
if (exception is not null)
{
ExceptionDispatchInfo.Capture(exception).Throw();
}
}
}
}
}
namespace Microsoft.AspNetCore.Builder
{
using Sentry.AspNetCore;
/// <summary>
/// Extensions for enabling <see cref="SentryTracingMiddleware"/>.
/// </summary>
public static class SentryTracingMiddlewareExtensions
{
/// <summary>
/// Adds Sentry's tracing middleware to the pipeline.
/// Make sure to place this middleware after <c>UseRouting(...)</c>.
/// </summary>
public static IApplicationBuilder UseSentryTracing(this IApplicationBuilder builder)
{
builder.UseMiddleware<SentryTracingMiddleware>();
return builder;
}
}
}