Reputation: 2259
I currently have some error handling middleware in my API pipeline. I'm about to add a logging middleware. The goal will be to log all incoming requests and outgoing responses, along with logging any errors that occur.
Is this possible and in startup.cs does the logging middleware go before the error handling or vice versa?
Upvotes: 3
Views: 1888
Reputation: 93063
Yes, this is all possible. You can log the incoming request in your middleware before it gets passed along the pipeline and log the outgoing response as it comes back through the pipeline. To log the errors, wrap the middleware's call to next
with try
/catch
, log the exception and then rethrow for the error-handling middleware to pick it up.
Here's a rough example of what that might look like:
app.UseErrorHandler("/Home/Error");
app.Use(async (ctx, next) =>
{
try
{
// Log the incoming request.
await next();
// Log the outgoing response.
}
catch (Exception ex)
{
// Log the exception.
throw; // Rethrow. The error-handler will pick this up.
}
});
// e.g.
app.UseMvc();
Your logging middleware goes after the error-handler, so that it can log before the error-handler kicks in (on the way back through the pipeline). If you were to add the logging middleware before the error-handler, the exception would have already been converted into a response by the time your middleware saw it.
Upvotes: 2