DEV Community


Exception Logging in .NET Core APIs

cesarcodes profile image Cesar Codes ・1 min read

Exception logging in .NET Core APIs is pretty straight forward. I recently started working on a new API at my company and rolled mine like this.

First of all, I am a big fan of using extension methods in my configuration to make things neat. Therefore, on my Startup.Configure() method, I created one that in this example I am calling UseCesarCodesExceptionHandling. This is an extension method on a tuple of (IApplicationBuilder, ILogger) and it takes a parameter of isDevelopment. You could make this much simpler, but this works for me. The point is that I have an extension method on my configuration.

Inside of the extension method, I utilize IApplicationBuilder.UseExceptionHandler, which adds a middleware that basically catches all of your unhandled exceptions.

As you can see, I have a class called ExceptionLog that serves as a standardized logging unit for all my exceptions. I then utilize an extension method named ToExceptionLogJson() for uniformed serialization.

And finally, for other exceptions I handle myself, I can utilize custom extension methods that piggy back on this. In the following example, I have a FlurlHttpException that leverages this logic.

And there it is. Happy coding!

Discussion (0)

Editor guide