response elapsed time logging

This commit is contained in:
Timerix 2025-03-24 00:31:47 +05:00
parent a4c2ae3e28
commit 448161239e
2 changed files with 19 additions and 11 deletions

View File

@ -2,7 +2,7 @@
<PropertyGroup>
<!--package info-->
<PackageId>DTLib.Web</PackageId>
<Version>1.2.1</Version>
<Version>1.2.2</Version>
<Authors>Timerix</Authors>
<Description>HTTP Server with simple routing</Description>
<RepositoryType>GIT</RepositoryType>

View File

@ -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)
{
var ctx = await server.GetContextAsync().AsCancellable(_stopToken);
HandleRequestAsync(ctx, requestId);
requestId++;
}
// stop
try
{
while (!_stopToken.IsCancellationRequested)
{
var ctx = await server.GetContextAsync().AsCancellable(_stopToken);
HandleRequestAsync(ctx, requestId++);
}
}
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)
{