在Application Insights中将失败的请求记录在请求正文中的最佳实践是什么? [英] What is the best practice to log request body on failed requests in Application Insights?

查看:94
本文介绍了在Application Insights中将失败的请求记录在请求正文中的最佳实践是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请求失败时记录HTTP请求正文的最佳方法是什么?

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);
    }
}

使用上面的代码,请求内容始终为空.我还尝试了,但是由于调用GetBufferlessInputStream,这引发了不受支持的方法异常.所以那也不行.

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.

我可以使用DelegatingHandler记录所有请求内容,但我只想将因未处理的异常导致的失败请求记录在请求正文中.

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.

有什么想法吗?

推荐答案

使用上面的代码,请求内容始终为空.

With the above code, the request content is always empty.

您可以使用ReadAsStreamAsync方法获取请求流,并重置该流的位置.之后,您可以使用StreamReader从此流中读取内容.以下代码供您参考.我对其进行了测试,并且对我而言效果很好.

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

这篇关于在Application Insights中将失败的请求记录在请求正文中的最佳实践是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆