Thursday, October 13, 2022

ASP.NET Core: HTTP Logging

In this post let's see how easy it is to set up HTTP Logging in an ASP.NET Core application.

You just need to add the HTTP Logging middleware to the HTTP pipeline.

WebApplication app = builder.Build();
 
// Enable HTTP Logging
app.UseHttpLogging();

The default logging configuration for Microsoft.AspNetCore is Warning. You might need to update appsettings.json as follows.

{
  "Logging": {
    "LogLevel": {
      "Default""Information",
      "Microsoft.AspNetCore""Warning",
      "Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware""Information"
    }
  }
}
And now we can see basic HTTP logging.
Default Logging
You can customize the HTTP logging options using HttpLoggingOptions. For example, the below specifies what fields to be logged.
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
 
// Customize HTTP Logging options
builder.Services.AddHttpLogging(logging =>
{
    logging.LoggingFields = HttpLoggingFields.RequestPath
        | HttpLoggingFields.RequestMethod
        | HttpLoggingFields.RequestScheme
        | HttpLoggingFields.ResponseStatusCode
        | HttpLoggingFields.Response;
    
    // TODO: Customize more options
});
And the output would be something like below.
Customized Logging
A couple of important things to note,
  • This feature is only available from ASP.NET Core 6.0 onwards.
  • By default, pre-defined sensitive fields will be Redacted (ex: Authorization header). Still, you might log sensitive information if you are logging request/response bodies. So look out for what you are logging.
  • HTTP Logging can reduce performance. For example, you might not want to log huge request/response bodies. Not only that, you can get a huge bill for your Log Analytics Workspace as well (if you are using Application Insights of course).

That's pretty straightforward, isn't it?

More read:
   HTTP Logging in ASP.NET Core

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment