Logging to Sentry in ASP.NET Core

Middleware

Logging exceptions

  1. Configuration for our Sentry DSN
  2. A class to send our error reports to Sentry
  3. A middleware component to catch any unhandled exceptions

Configuration

 “Sentry”: {
“Dsn”: “{your_DSN_here}”
}
csharp
public class SentryOptions
{
public string Dsn { get; set; }
}
 services.Configure<SentryOptions>(Configuration.GetSection(“Sentry”));

The Error Reporting class


public interface IErrorReporter
{
Task CaptureAsync(Exception exception);
Task CaptureAsync(string message);
}

Our Middleware

Wiring it all up

 services.AddScoped<IErrorReporter, SentryErrorReporter>();
 app.UseMiddleware<SentryMiddleware>();

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler(“/Error”);
}

app.UseMiddleware<SentryMiddleware>();

Conclusion

--

--

--

Software Engineer writing about his daily software adventures, wherever they may lead.

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Martin Cerruti

Martin Cerruti

Software Engineer writing about his daily software adventures, wherever they may lead.

More from Medium

Use ASP.NET Core hosted services to run a background task

Application Insights: How to set the cloud role name in .NET Core & .NET 5

Unit Tests a .NET 6 project with Azure Pipelines DotNetCoreCLI@2

GitHub Gist focus image

What’s new in .NET 6