CodexBloom - Programming Q&A Platform

ASP.NET Core 6: Challenge with Custom Middleware for Request Logging and Performance Metrics

πŸ‘€ Views: 98 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-14
asp.net-core middleware logging performance C#

I'm refactoring my project and I'm working on a project and hit a roadblock. I'm confused about Quick question that's been bugging me - This might be a silly question, but I'm encountering difficulty while implementing a custom middleware for logging request details and measuring performance metrics in my ASP.NET Core 6 application. The middleware is meant to log the request path, headers, and response time for each incoming request. However, I noticed that the logged times seem inconsistent and occasionally reference the wrong request duration. Here’s a simplified version of my middleware: ```csharp public class RequestLoggingMiddleware { private readonly RequestDelegate _next; public RequestLoggingMiddleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext context) { var stopwatch = Stopwatch.StartNew(); await _next(context); stopwatch.Stop(); var logDetails = new { Path = context.Request.Path, Headers = context.Request.Headers, ResponseTime = stopwatch.ElapsedMilliseconds }; Console.WriteLine(JsonSerializer.Serialize(logDetails)); } } ``` I am using this middleware in the `Startup.cs` file like this: ```csharp public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseMiddleware<RequestLoggingMiddleware>(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } ``` The issue arises when I test it with multiple concurrent requests. Sometimes, the response times logged appear to be aggregated or inconsistent across different requests. For instance, a request that should take around 200ms is sometimes logged as taking 800ms. I've tried logging the request ID and correlating it with the response, but that doesn't seem to solve it. I also confirmed that there are no other middlewares interfering by commenting them out one by one. Any insight on how to ensure the stopwatch only tracks the elapsed time for the current request would be greatly appreciated! Is there a better way to implement this logging while ensuring accuracy? Thanks in advance! I'm working on a application that needs to handle this. Thanks in advance! My development environment is macOS. What am I doing wrong?