What is the best practice for registering a request body on failed requests in Application Insights?

What is the best way to register an HTTP request body when a request fails?

I register 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 contents of the request are always empty. I also tried this one , but this throws an unsupported method exception due to a call to GetBufferlessInputStream. So it doesn’t work either.

I can register all request content with the DelegatingHandler, but I would only like to register the request body with failed requests caused by unhandled exceptions.

Any ideas?

+4
3

.

, ReadAsStreamAsync, reset . , StreamReader. . , .

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);
+2

. reset Position , . .

if (context != null && context.Exception != null)
{
    HttpContent requestContent = new HttpContent();
    request.Content.CopyToAsync(requestContent);
    ExceptionTelemetry telemetry = new ExceptionTelemetry(context.Exception);

    // the requestBody is always empty because the stream is non-rewinadable?
    string requestBody = requestContent.ReadAsStringAsync().Result;
    telemetry.Properties.Add("Request Body", requestBody);

    Logger.LogException(context.Exception);
}
0

Amor - MSFT CopyTo

public class AiExceptionLogger : ExceptionLogger
{
    public  override async void Log(ExceptionLoggerContext context)
    {
        if (context != null && context.Exception != null)
        {
            ExceptionTelemetry telemetry = new ExceptionTelemetry(context.Exception);

            using (var ms = new MemoryStream())
            {
                await context.Request.Content.CopyToAsync(ms);
                var requestBody = Encoding.UTF8.GetString(ms.ToArray());
                telemetry.Properties.Add("Request Body", requestBody);
            }


            Logger.LogException(telemetry);
        }
        base.Log(context);
    }
}
0

Source: https://habr.com/ru/post/1676306/


All Articles