In this article, we will know about a .NET6 feature that is 'UseHttpLogging' middleware for logging HTTP requests and responses.
UseHttpLogging Middleware:
The .NET6 providing a built-in middleware for HTTP logs that is 'UseHttpLogging'. So this middleware provide log information on 'HTTP Request and Response Information', 'Headers' and 'Request Body Information', etc.
Create A .NET6 Application:
This 'UseHttpLogging' middleware can be configured to any .NET application like MVC, Razor Pages, API, etc. Let's create a .Net6 API sample project to accomplish our demo. We can use either Visual Studio 2022 or Visual Studio Code(using .NET CLI commands) to create any.Net6 application. For this demo, I'm using the 'Visual Studio Code'(using the .NET CLI command) editor.
CLI command For Minimal API Project
dotnet new webapi -o Your_Project_Name
dotnet new webapi -o Your_Project_Name
Configure UseHttpLogging Middleware:
Now configure the 'UseHttpLogging' middleware inside of the 'Program.cs'.
Program.cs:
app.UseHttpLogging();Now in 'appsetings.{environmental_variable}.json' we have to configure namespace like 'Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware' at 'Information' level.
appsettings.Development.json:
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning", "Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware": "Information" } } }Now run the application and check the terminal we can observe the HTTP request and response logging.
Customizing HTTP Logging:
We can customize some options in HTTP logging by explicitly registering the 'AddHttpLoging' service. So here we can explicitly configure like 'what information need to be logged', 'restriction on the size of request and response', etc.
Program.cs:
builder.Services.AddHttpLogging(logging => { logging.LoggingFields = Microsoft.AspNetCore.HttpLogging.HttpLoggingFields.ResponseBody; });
- Here configured to log only HTTP Response.
Support Me!
Buy Me A Coffee
PayPal Me
Video Session:
Wrapping Up:
Hopefully, I think this article delivered some useful information on UseHttpLogging middleware. I love to have your feedback, suggestions, and better techniques in the comment section below.
Comments
Post a Comment