How to use HTTP logging in ASP.NET Core 6

Posted on 20-07-2021 , by: admin , in , 0 Comments

When working in web applications in ASP.NET Core, you might often want to log the HTTP request and responses. The HTTP logging middleware included in ASP.NET Core allows you to log request and response data including headers, body, and common properties. This article talks about HTTP logging, why it is essential, and how you can use the HTTP logging middleware in ASP.NET Core 5.

To work with the code examples provided in this article, you should have Visual Studio 2022 installed in your system. If you don’t already have a copy, you can download Visual Studio 2022 here.

Create an ASP.NET Core MVC 6 project in Visual Studio 2022

First off, let’s create an ASP.NET Core project in Visual Studio 2022. Following these steps will create a new ASP.NET Core MVC 6 project in Visual Studio 2022.

  1. Launch the Visual Studio 2022 IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.NET Core Web App (Model-View-Controller)” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location for the new project.
  6. Optionally check the “Place solution and project in the same directory” check box, depending on your preferences.
  7. Click Next.
  8. In the “Additional Information” window shown next, select .NET 6.0 (Preview) as the target framework from the drop-down list at the top. Leave the “Authentication Type” as “None” (default).
  9. Ensure that the check boxes “Enable Docker,” “Configure for HTTPS,” and “Enable Razor runtime compilation” are unchecked as we won’t be using any of those features here.
  10. Click Create.

This will create a new ASP.NET Core MVC 6 project in Visual Studio 2022. We’ll use this project to work with HTTP logging in the subsequent sections of this article.

What is HTTP logging middleware?

The HTTP logging middleware in ASP.NET Core 6 can be used to log requests and responses in your ASP.NET 6 applications. HTTP logging can provide you with logs that include the following:

  • HTTP request information
  • HTTP response information
  • Headers
  • Body
  • Common properties

Enable HTTP logging in ASP.NET Core 6

You can enable HTTP logging using the UseHttpLogging extension method as shown in the code snippet given below.

app.UseHttpLogging();

In fact HTTP logging is enabled in ASP.NET Core by default. Here is the default code of the Configure method of the Startup class when the project is created.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseHttpLogging();
            app.UseStaticFiles();
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }

Configure HTTP logging middleware in ASP.NET Core 6

The HTTP logging middleware is available by default in ASP.NET Core 6—i.e., you don’t need to install any NuGet packages to work with it. To configure the HTTP logging middleware you need to invoke the AddHttpLogging extension method pertaining to the IServiceCollection interface. The following code shows how you can configure this middleware in the ConfigureServices method of the Startup class.

public void ConfigureServices(IServiceCollection services)
{
     services.AddHttpLogging(logging =>
     {
        //Write your code to configure the HttpLogging middleware here    
     });
 services.AddControllersWithViews();
}

To configure specific parts of the HTTP request and HTTP response, you can take advantage of the LoggingFields enum as shown in the ConfigureServices method as shown below.

httpLogging.LoggingFields = HttpLoggingFields.All;

Configure request headers in ASP.NET Core 6

The RequestHeaders collection comprises a set of request headers that can be logged. Note that you can log only those request header values for which the corresponding request header name has been added. The following code snippet illustrates how you can add a request header to the request headers collection of the instance of the HttpLoggingOptions class named httpLogging.

httpLogging.RequestHeaders.Add("Request-Header-Demo");

Configure response headers in ASP.NET Core 6

The ResponseHeaders collection comprises a set of response headers that can be logged. You can log only those response header values for which a corresponding response header name has been added. The following code snippet shows how you can add a response header to the response headers collection.

httpLogging.ResponseHeaders.Add("Response-Header-Demo");

Specify encoding using MediaTypeOptions in ASP.NET Core 6

You can specify the encoding you would like to use by using the AddText method of the MediaTypeOptions class. Here is a code example that illustrates this:

httpLogging.MediaTypeOptions.AddText("application/javascript");

Set request and response body log limit in ASP.NET Core 6

You can also set request and response body size limits using the RequestBodyLimit and ResponseBodyLimit properties of the HttpLoggingOptions class. The following code snippet illustrates how this can be accomplished.

httpLogging.RequestBodyLogLimit = 4096;
httpLogging.ResponseBodyLogLimit = 4096;

The default value for the request and response body limits is 32 KB, or 32768 bytes. You can change it to suit your needs.

Complete HTTP logging example in ASP.NET Core 6

The complete source code of the ConfigureServices method is given below for your reference.

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHttpLogging(httpLogging =>
            {
                httpLogging.LoggingFields = HttpLoggingFields.All;
                httpLogging.RequestHeaders.Add("Request-Header-Demo");
                httpLogging.ResponseHeaders.Add("Response-Header-Demo");
                httpLogging.MediaTypeOptions.
                AddText("application/javascript");
                httpLogging.RequestBodyLogLimit = 4096;
                httpLogging.ResponseBodyLogLimit = 4096;
            });
            services.AddControllersWithViews();
        }

Note that using HTTP logging could be detrimental to the performance of an application, particularly when logging the request and response bodies. Hence you should always consider the performance impact when choosing the fields to log.