Logging to Sentry in ASP.NET Core

Middleware

ASP.NET Core has a concept called middleware. Middleware is user code that runs as part of the request pipeline. It can obtain information about requests, modify the response, and virtually everything in between.

Logging exceptions

By default, ASP.NET Core comes with a DeveloperExceptionPageMiddleware. This component catches an exception and then renders it in a developer-friendly way. Fortunately for us, this component is open-source:

  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

Configuration in ASP.NET Core applications is specified in appSettings.json. In our case, we’ll need to be able to configure the Sentry DSN, which is just a string:

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

The Error Reporting class

Thanks to RavenSharp, writing the error reporting class is a breeze. All we’ll need to do is wrap the CaptureAsync method for at least Exception (though it’s useful to wrap the string overload as well for non-exception logging purposes)


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

Our Middleware

While we have a perfectly viable way of logging exceptions to Sentry at our disposal now, we’re doing this whole thing so we can handle those pesky unhandled exceptions that would otherwise go unnoticed.

Wiring it all up

All that’s left is to wire up the dependency injection and adding the middleware to the request pipeline.

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

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

app.UseMiddleware<SentryMiddleware>();

Conclusion

We’ve set up a middleware component that allows all exceptions that aren’t handled by user code to be reported directly to Sentry. This way you’ll always know what exceptions are being thrown in your exception, in nigh-realtime, allowing you to quickly fix any issues instead of relying on your users to report them to you.

--

--

Software Architect, Technology Writer, Philosophy Enthusiast

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

746 Followers

Software Architect, Technology Writer, Philosophy Enthusiast