What is the best way to log the HTTP request body when a request fails?
I'm logging unhandled exceptions by overriding the Exception logger:
public class AiExceptionLogger : ExceptionLogger
{
public override void Log(ExceptionLoggerContext context)
{
if (context != null && context.Exception != null)
{
ExceptionTelemetry telemetry = new ExceptionTelemetry(context.Exception);
// the requestBody is always empty because the stream is non-rewinadable?
string requestBody = context.Request.Content.ReadAsStringAsync().Result;
telemetry.Properties.Add("Request Body", requestBody);
Logger.LogException(telemetry);
}
base.Log(context);
}
}
With the above code, the request content is always empty. I also tried this, but that throws an unsupported method exception due to calling GetBufferlessInputStream. So that doesn't work either.
I could log all request content using a DelegatingHandler, but I'd only like to log the request body on failed requests caused by unhandled exceptions.
Any ideas?
With the above code, the request content is always empty.
You could get the request stream using ReadAsStreamAsync method and reset the position of this stream. After that, you can read the content from this steam using StreamReader. Code below is for your reference. I tested it and it worked fine on my side.
ExceptionTelemetry telemetry = new ExceptionTelemetry(context.Exception);
//Get request stream and reset the position of this stream
Stream requestBodyStream = context.Request.Content.ReadAsStreamAsync().Result;
requestBodyStream.Position = 0;
string requestBody = string.Empty;
using (StreamReader sr = new StreamReader(requestBodyStream))
{
requestBody = sr.ReadToEnd();
}
telemetry.Properties.Add("Request Body", requestBody);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With