Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trace all HTTP requests in .net core 2.1 globally?

I want to log all HTTP requests in a dotnet core 2.1 application. Logging should include HTTP headers, body and the host address. I need to bind my logging code globally without changing the existing code.

I tried this example https://www.azurefromthetrenches.com/capturing-and-tracing-all-http-requests-in-c-and-net/, but no HTTP event came to the Listener.

Is there any way to listen to HTTP events on dotnet core 2.1 globally?

like image 627
cengaver Avatar asked Jul 09 '19 08:07

cengaver


2 Answers

This is a good blog post on HttpClient logging in .Net Core 2.1 by Steve Gordon.

In essence, you need to set the logging level of System.Net.Http.HttpClient to Trace to get detailed information about requests and response.

A sample of the required section in your appsettings.json is below:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning",
      "System.Net.Http.HttpClient": "Trace"
    }
  }

This will show all trace logging for all HttpClient requests and responses.

like image 82
Jacques Snyman Avatar answered Oct 21 '22 01:10

Jacques Snyman


You can log all http request informations in middleware. Take a look at the example below

1.Create a class RequestHandlerMiddleware.cs

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.IO;
using System.Threading.Tasks;

namespace Onsolve.ONE.WebApi.Middlewares
{
    public sealed class RequestHandlerMiddleware
    {
        private readonly RequestDelegate next;
        private readonly ILogger logger;

        public RequestHandlerMiddleware(ILogger<RequestHandlerMiddleware> logger, RequestDelegate next)
        {
            this.next = next;
            this.logger = logger;
        }

        public async Task Invoke(HttpContext context)
        {
            logger.LogInformation($"Header: {JsonConvert.SerializeObject(context.Request.Headers, Formatting.Indented)}");

            context.Request.EnableBuffering();
            var body = await new StreamReader(context.Request.Body).ReadToEndAsync();
            logger.LogInformation($"Body: {body}");
            context.Request.Body.Position = 0;

            logger.LogInformation($"Host: {context.Request.Host.Host}");
            logger.LogInformation($"Client IP: {context.Connection.RemoteIpAddress}");
            await next(context);
        }

    }
}

2.Add RequestHandlerMiddleware to Configure method in Startup.cs

app.UseMiddleware<RequestHandlerMiddleware>();

or simpler

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILogger<Startup> logger)
{
    app.Use(async (context, next) =>
    {
        logger.LogInformation($"Header: {JsonConvert.SerializeObject(context.Request.Headers, Formatting.Indented)}");

        context.Request.EnableBuffering();
        var body = await new StreamReader(context.Request.Body).ReadToEndAsync();
        logger.LogInformation($"Body: {body}");
        context.Request.Body.Position = 0;

        logger.LogInformation($"Host: {context.Request.Host.Host}");
        logger.LogInformation($"Client IP: {context.Connection.RemoteIpAddress}");
        await next.Invoke();
    });
}

Reference:

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-2.2

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/write?view=aspnetcore-2.2

like image 23
Hung Quach Avatar answered Oct 21 '22 03:10

Hung Quach