Skip to content

Commit e7240a4

Browse files
Custom middleware tracing (#4304)
Demonstrate how to add tracing for custom middleware Resolves #3423: - #3423 Co-authored-by: Bruno Garcia <bruno@brunogarcia.com>
1 parent de96ba3 commit e7240a4

1 file changed

Lines changed: 22 additions & 2 deletions

File tree

samples/Sentry.Samples.AspNetCore.Basic/Program.cs

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,7 @@
1919

2020
var app = builder.Build();
2121

22-
// An example ASP.NET Core middleware that throws an
23-
// exception when serving a request to path: /throw
22+
// An example ASP.NET Core endpoint that throws an exception when serving a request to path: /throw
2423
app.MapGet("/throw/{message?}", context =>
2524
{
2625
var exceptionMessage = context.GetRouteValue("message") as string;
@@ -48,4 +47,25 @@
4847
exceptionMessage ?? "An exception thrown from the ASP.NET Core pipeline");
4948
});
5049

50+
// Demonstrates how to add tracing in custom middleware
51+
app.Use(async (context, next) =>
52+
{
53+
var span = SentrySdk.StartSpan("CustomMiddlewareSpan", "middleware");
54+
try
55+
{
56+
var log = context.RequestServices.GetRequiredService<ILoggerFactory>()
57+
.CreateLogger<Program>();
58+
59+
log.LogInformation("Just chilling for a bit...");
60+
await Task.Delay(TimeSpan.FromMilliseconds(50)); // Simulate some work
61+
span.Finish();
62+
}
63+
catch (Exception e)
64+
{
65+
span.Finish(e);
66+
throw;
67+
}
68+
await next();
69+
});
70+
5171
app.Run();

0 commit comments

Comments
 (0)