ASP.NET Core: How to Implement Custom Middleware for Request Logging Without Performance Hit?
I'm following best practices but I've searched everywhere and can't find a clear answer. I'm trying to implement a custom middleware in my ASP.NET Core 6 application to log all incoming requests for debugging purposes... However, I'm concerned about the performance overhead that this might introduce, especially under high load conditions. So far, I've created the middleware and successfully logged the request details, but I noticed that response times have increased, particularly for large payloads. Hereβs the middleware I've set up: ```csharp public class RequestLoggingMiddleware { private readonly RequestDelegate _next; public RequestLoggingMiddleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext context) { var request = context.Request; var requestBody = string.Empty; // Read the request body (this is where the performance issue might be coming from) if (request.ContentLength > 0 && request.Body.CanRead) { using (var reader = new StreamReader(request.Body)) { requestBody = await reader.ReadToEndAsync(); request.Body.Position = 0; // Reset the stream position } } // Log request details Console.WriteLine($"Request: {request.Method} {request.Path} Body: {requestBody}"); await _next(context); } } ``` To register the middleware, I've added the following line in my `Startup.cs`: ```csharp public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseMiddleware<RequestLoggingMiddleware>(); // other middlewares... app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } ``` I've tested this by sending large JSON payloads, and the average response time has noticeably increased. I also implemented logging with `ILogger` for better performance, but the delay persists. I suspect that reading the request body is the culprit, but any suggestions on how I could optimize this logging process or alternative approaches would be greatly appreciated! Am I handling the request body correctly, or is there a different pattern I should consider for logging requests efficiently? My development environment is Ubuntu. Am I missing something obvious? This is my first time working with Csharp 3.9. Could this be a known issue?