With the release of ASP.NET Core 6, a new Http Logging middleware became available. This middleware transmit requests as log messages through the Microsoft.Extensions.Logging framework.
To enable the middleware, add the following code to your Program.cs:
This file contains hidden or 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 builder = WebApplication.CreateBuilder(args); | |
app.UseStaticFiles(); | |
//Add this line: | |
app.UseHttpLogging(); | |
app.Run(); |
This will add an instance of the Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware class.
If you now run your application, you will notice no difference and nothing is logged. This is because the HTTP Logging messages are handled as informational messages and these are not enabled by default.
To adjust the log level, you can add the following line to the Logging > LogLevel configuration in the appsettings.json file:
This file contains hidden or 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
{ | |
"Logging": { | |
"LogLevel": { | |
"Default": "Information", | |
"Microsoft.AspNetCore": "Warning", | |
"Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware": "Information" | |
} | |
}, | |
"AllowedHosts": "*" | |
} |
You can further configure the logging through the AddHttpLogging method:
This file contains hidden or 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 builder = WebApplication.CreateBuilder(args); | |
builder.Services.AddHttpLogging(logging => | |
{ | |
logging.LoggingFields = HttpLoggingFields.All; | |
logging.RequestHeaders.Add("X-Request-Header"); | |
logging.RequestHeaders.Add("X-Response-Header"); | |
logging.RequestBodyLogLimit = 1024; | |
logging.ResponseBodyLogLimit = 1024; | |
}); |