Exception Logger Middleware and Request Logging

Exception catching and logging in .Net projects

Yazının Türkçe versiyonuna bu link aracılığıyla ulaşabilirsiniz.

One of the most striking components in .Net Core and .Net project structure is the middleware. This component allows us to perform the actions we want before the arriving request reaches the controller or before the response from the controller reaches the client. In short, we can say that it has interceptor behavior. Thanks to this behavior, the middleware component becomes the ideal point where different operations such as caching, access permission management, error management can be done.

In this article, we will look at how we can catch the errors in a single point and log them with the request.

ExceptionLoggerMiddleware

First of all, we create our class in accordance with the middleware structure.

1- We get the next object (RequestDelegate) that we will wake up via the constructor method with the name next.

2- We write our code in Invoke method to forward the request to the next component.

3- We include our class in the system in application startup.

You can set a break-point to the Invoke method in its current form. You can see that with every request to your project, your code will stop when it reaches this break-point.

Now we can start coding the operations that our class should do.

1- In order to catch the errors, we start by taking the part that we call the _next object into the try-catch block.

2- The request object we access as httpContext.Request can be read once. In case of an error, we want to read httpContext.Request object again and log some data that it contains. To achieve this, we need to use the EnableBuffering method.

1- In the HandleAsync method, we first obtain the text version of the request. Then, we save this text value with the exception to our error log.

2- In the RequestAsTextAsync method, the request information (for example; URL value, header information and request body) is combined together.

3- In the GetRawBodyAsync method, we first pull the cursor position to 0 in order to be able to read the request body from the beginning. Then, we create an object of type StreamReader. We read the request body via this object. Then, we move the cursor back to the beginning of the request body. Finally, we return the request body information we read.

You can access the latest version of the ExceptionLoggerMiddleware class via this link. In another article; we will look at how to mask critical information such as phone number, email, password in the log record.

I hope it was a useful article. You can click this link to check out my other articles.

--

--

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