From 448161239e4fbfd09b4bf40e77066128058fc2ce Mon Sep 17 00:00:00 2001 From: Timerix Date: Mon, 24 Mar 2025 00:31:47 +0500 Subject: [PATCH] response elapsed time logging --- DTLib.Web/DTLib.Web.csproj | 2 +- DTLib.Web/WebApp.cs | 28 ++++++++++++++++++---------- 2 files changed, 19 insertions(+), 11 deletions(-) diff --git a/DTLib.Web/DTLib.Web.csproj b/DTLib.Web/DTLib.Web.csproj index 96e419b..15ad3ee 100644 --- a/DTLib.Web/DTLib.Web.csproj +++ b/DTLib.Web/DTLib.Web.csproj @@ -2,7 +2,7 @@ DTLib.Web - 1.2.1 + 1.2.2 Timerix HTTP Server with simple routing GIT diff --git a/DTLib.Web/WebApp.cs b/DTLib.Web/WebApp.cs index d1a83ea..0f7c423 100644 --- a/DTLib.Web/WebApp.cs +++ b/DTLib.Web/WebApp.cs @@ -6,6 +6,7 @@ global using System.Threading.Tasks; global using DTLib.Filesystem; global using DTLib.Logging; global using System.Net; +using System.Diagnostics; using DTLib.Extensions; using DTLib.Web.Routes; @@ -28,20 +29,24 @@ public class WebApp public async Task Run() { - _logger.LogInfo($"starting webserver at {_baseUrl} ..."); + _logger.LogInfo($"starting server at '{_baseUrl}'..."); HttpListener server = new HttpListener(); server.Prefixes.Add(_baseUrl); server.Start(); _logger.LogInfo("server started"); long requestId = 1; - while (!_stopToken.IsCancellationRequested) + + try { - var ctx = await server.GetContextAsync().AsCancellable(_stopToken); - HandleRequestAsync(ctx, requestId); - requestId++; + while (!_stopToken.IsCancellationRequested) + { + var ctx = await server.GetContextAsync().AsCancellable(_stopToken); + HandleRequestAsync(ctx, requestId++); + } } - - // stop + catch (OperationCanceledException) + {} + server.Stop(); _logger.LogInfo("server stopped"); } @@ -49,12 +54,15 @@ public class WebApp // ReSharper disable once AsyncVoidMethod private async void HandleRequestAsync(HttpListenerContext ctx, long requestId) { - string logContext = $"Request {requestId}"; + string logContext = $"Request-{requestId}"; try { - _logger.LogInfo(logContext, $"[{ctx.Request.HttpMethod}] {ctx.Request.RawUrl} from {ctx.Request.RemoteEndPoint} ..."); + _logger.LogInfo(logContext, $"[{ctx.Request.HttpMethod}] {ctx.Request.RawUrl} from {ctx.Request.RemoteEndPoint}..."); + var stopwatch = new Stopwatch(); + stopwatch.Start(); var status = await _router.Resolve(ctx); - _logger.LogInfo(logContext, $"{(int)status} ({status})"); + stopwatch.Stop(); + _logger.LogInfo(logContext, $"responded {(int)status} ({status}) in {stopwatch.ElapsedMilliseconds}ms"); } catch (Exception ex) {