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

Improve transaction instrumentation on ASP.NET Core #766

Merged
merged 5 commits into from
Jan 27, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
- Integrate trace headers. (#758) @Tyrrrz
- Renamed Option `DiagnosticsLevel` to `DiagnosticLevel` (#759) @bruno-garcia
- Add additional data to transactions (#763) @Tyrrrz
- Improve transaction instrumentation on ASP.NET Core (#766) @Tyrrrz
- Add `Release` to `Scope` (#765) @Tyrrrz

## 3.0.0-beta.0
Expand Down
9 changes: 6 additions & 3 deletions src/Sentry.AspNetCore/Extensions/HttpContextExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ internal static class HttpContextExtensions
{
public static string? TryGetRouteTemplate(this HttpContext context)
{
#if !NETSTANDARD2_0
#if !NETSTANDARD2_0 // endpoint routing is only supported after ASP.NET Core 3.0
// Requires .UseRouting()/.UseEndpoints()
var endpoint = context.Features.Get<IEndpointFeature?>()?.Endpoint as RouteEndpoint;
var routePattern = endpoint?.RoutePattern.RawText;
Expand All @@ -22,8 +22,11 @@ internal static class HttpContextExtensions
}
#endif

// Requires legacy .UseMvc()
var routeData = context.Features.Get<IRoutingFeature?>()?.RouteData;
// Fallback for legacy .UseMvc().
// Uses context.Features.Get<IRoutingFeature?>() under the hood and CAN be null,
// despite the annotations claiming otherwise.
var routeData = context.GetRouteData();

var controller = routeData?.Values["controller"]?.ToString();
var action = routeData?.Values["action"]?.ToString();
var area = routeData?.Values["area"]?.ToString();
Expand Down
32 changes: 19 additions & 13 deletions src/Sentry.AspNetCore/SentryTracingMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,21 +33,27 @@ public async Task InvokeAsync(HttpContext context)
return;
}

var transaction = hub.StartTransaction(
context.GetTransactionName(),
"http.server"
);

try
{
await _next(context).ConfigureAwait(false);
}
finally
await hub.ConfigureScopeAsync(async scope =>
{
transaction.Finish(
GetSpanStatusFromCode(context.Response.StatusCode)
var transaction = hub.StartTransaction(
context.GetTransactionName(),
"http.server"
);
}

// Put the transaction on the scope
scope.Transaction = transaction;

try
{
await _next(context).ConfigureAwait(false);
}
finally
{
transaction.Finish(
GetSpanStatusFromCode(context.Response.StatusCode)
);
}
}).ConfigureAwait(false);
}

private static SpanStatus GetSpanStatusFromCode(int statusCode) => statusCode switch
Expand Down
49 changes: 49 additions & 0 deletions test/Sentry.AspNetCore.Tests/SentryTracingMiddlewareTests.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#if !NETCOREAPP2_1
using System;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
Expand Down Expand Up @@ -63,6 +64,54 @@ public async Task Transactions_are_grouped_by_route()
Arg.Is<Transaction>(transaction => transaction.Name == "GET /person/{id}")
);
}

[Fact]
public async Task Transaction_is_bound_on_the_scope_automatically()
{
// Arrange
ITransaction transaction = null;

var sentryClient = Substitute.For<ISentryClient>();

var hub = new Internal.Hub(sentryClient, new SentryOptions
{
Dsn = DsnSamples.ValidDsnWithoutSecret
});

var server = new TestServer(new WebHostBuilder()
.UseSentry()
.ConfigureServices(services =>
{
services.AddRouting();

services.RemoveAll(typeof(Func<IHub>));
services.AddSingleton<Func<IHub>>(() => hub);
})
.Configure(app =>
{
app.UseRouting();
app.UseSentryTracing();

app.UseEndpoints(routes =>
{
routes.Map("/person/{id}", _ =>
{
transaction = hub.ScopeManager.GetCurrent().Key.Transaction;
return Task.CompletedTask;
});
});
})
);

var client = server.CreateClient();

// Act
await client.GetStringAsync("/person/13");

// Assert
transaction.Should().NotBeNull();
transaction?.Name.Should().Be("GET /person/{id}");
}
}
}
#endif