In .NET 7 and before the default request logging in ASP.NET Core is quite noisy, with multiple events emitted per request. That is one of the reasons why I use the Serilog.AspNetCore package.
By adding the following line to my ASP.NET Core application I can reduce the number of events to 1 per request.
The result looks like this in Seq:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var app = builder.Build(); | |
app.UseSerilogRequestLogging(); // <-- Add this line |
Starting from .NET 8 the HTTP logging middleware has several new capabilities and we no longer need Serilog to achieve the same result.
By configuring the following 2 options, we could achieve this:
HttpLoggingFields.Duration
: When enabled, this emits a new log at the end of the request/response measuring the total time in milliseconds taken for processing. This has been added to theHttpLoggingFields.All
set.HttpLoggingOptions.CombineLogs
: When enabled, the middleware will consolidate all of its enabled logs for a request/response into one log at the end. This includes the request, request body, response, response body, and duration.
Here is a code snippet:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.AspNetCore.HttpLogging; | |
var builder = WebApplication.CreateBuilder(args); | |
builder.Services.AddHttpLogging(logging => | |
{ | |
logging.LoggingFields = HttpLoggingFields.All //Includes HttpLoggingFields.Duration | |
logging.CombineLogs = true; | |
}); |
Nice!