From 14757c3efe57f9d3175a44a19ec58ada6742c589 Mon Sep 17 00:00:00 2001 From: Mate Farkas Date: Wed, 17 Apr 2024 17:30:18 +0200 Subject: [PATCH] Add request logging --- Program.cs | 21 +++++++++++++++++++-- appsettings.json | 4 +++- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/Program.cs b/Program.cs index bc29797..176ac7f 100644 --- a/Program.cs +++ b/Program.cs @@ -2,6 +2,7 @@ using ConnectionsAPI.Config; using ConnectionsAPI.Database; using ConnectionsAPI.Utility; using Microsoft.EntityFrameworkCore; +using System.Net; namespace ConnectionsAPI { @@ -55,10 +56,26 @@ namespace ConnectionsAPI app.UsePathBase("/connections-api"); } - //app.UseHttpsRedirection(); - app.UseFastEndpoints(); + // middleware to log requests and their resulting statuses + var loggerFactory = app.Services.GetRequiredService(); + var requestLogger = loggerFactory.CreateLogger("ConnectionsAPI.RequestLogger"); + app.Use(async (ctx, next) => + { + await next(); + if (ctx != null) + { + // log the path and status of the request/response + requestLogger.LogTrace( + "{requestPath} -- {requestStatusCode} {requestStatusText}", + ctx.Request.Path, + ctx.Response.StatusCode, + ((HttpStatusCode)ctx.Response.StatusCode).ToString() + ); + } + }); + // if not dev env, migrate database if (!app.Environment.IsDevelopment()) { diff --git a/appsettings.json b/appsettings.json index 10f68b8..7c55157 100644 --- a/appsettings.json +++ b/appsettings.json @@ -2,7 +2,9 @@ "Logging": { "LogLevel": { "Default": "Information", - "Microsoft.AspNetCore": "Warning" + "Microsoft.AspNetCore": "Warning", + "ConnectionsAPI.RequestLogger": "Trace", + "Microsoft.EntityFrameworkCore.Database.Command": "Warning" } }, "AllowedHosts": "*"