ThreeMammals / Ocelot

.NET API Gateway
https://www.nuget.org/packages/Ocelot
MIT License
8.4k stars 1.64k forks source link

How to log request json body in case of error in ocelot #1218

Closed rajeshgithub001 closed 8 months ago

rajeshgithub001 commented 4 years ago

I am serilog to log error from ocelot in case of downstream giving any error. Using serilog i am sending the exception details to Application Insight.

Serilog configuration:

"Serilog": {
    "Using": [ "Serilog.Sinks.ApplicationInsights" ],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning"
      }
    },
    "WriteTo": [
      {
        "Name": "ApplicationInsights",
        "Args": {
          "instrumentationKey": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
          "telemetryConverter": "Serilog.Sinks.ApplicationInsights.Sinks.ApplicationInsights.TelemetryConverters.TraceTelemetryConverter, Serilog.Sinks.ApplicationInsights"
        }
      }
    ],
    "Enrich": [ "FromLogContext" ],
    "Properties": {
      "Application": "API GATEWAY"
    }
  }

Now i want to log request json body in case of error only , How will i do it ?

Middleware didn't work as it didn't catch any ocelot exception, so its out of question.

MirzaMerdovic commented 4 years ago

Maybe using DelegatingHandler can solve your problem? For example:

public class FakeHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        //do stuff and optionally call the base handler..
        var response = await base.SendAsync(request, cancellationToken);

        if (!response.IsSuccessStatusCode)
        {
            // TODO: Log stuff ... 
        }

        return response;
    }
}