dotnet http logging
out of the box we can have detailed logs for each and every http request
using System.Net;
using System.Net.Http.Headers;
using Microsoft.Net.Http.Headers;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpLogging(options => {
options.LoggingFields = Microsoft.AspNetCore.HttpLogging.HttpLoggingFields.All;
options.RequestHeaders.Add(HeaderNames.Authorization);
});
var app = builder.Build();
app.UseHttpLogging();
app.MapGet("/", () => "Hello World!");
app.Run();
but make sure that your appsettings files has something like:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Information"
}
}
}
or you can be more concrete and leave everything as is but define log level for http logs like so:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Microsoft.AspNetCore.HttpLogging": "Information"
}
}
}
if everything is done right you will see following for requests:
info: Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware[1]
Request:
Protocol: HTTP/1.1
Method: GET
Scheme: http
PathBase:
Path: /
Accept: */*
Host: localhost:5000
User-Agent: curl/7.84.0
and this one for responses:
info: Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware[2]
Response:
StatusCode: 200
Content-Type: text/plain; charset=utf-8
also consider that library by default does not pring all header and perform some kind of anonymisation, so you may see [Redacted]
use something like:
options.RequestHeaders.Add(HeaderNames.Authorization);