How to log request json body in case of error in Ocelot? #2012
Answered
by
raman-m
rajeshgithub001
asked this question in
Q&A
-
I am serilog to log error from ocelot in case of downstream giving any error. 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. |
Beta Was this translation helpful? Give feedback.
Answered by
raman-m
Mar 23, 2024
Replies: 1 comment 1 reply
-
Maybe using DelegatingHandler can solve your problem? 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;
}
} |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yes, but Not all errors will be caught by delegating handler ❗
My recommendation is using
PreErrorResponderMiddleware
injection. See Middleware Injection.It requires analysis of Ocelot error codes, with limited access to exception messages.
More advanced approach is replacing
IExceptionToErrorMapper
object in DI container.Just define new class inheriting the
IExceptionToErrorMapper
interface.Aggregate HttpExceptionToErrorMapper class member as private one.
Decorate behavior of the class or totally replace by new behavior of Decorator pattern.
So,
public Error Map(Exception exception)
method can be decorated like this: