如何在Application Insights中扩展对传出的HTTP请求的依赖性跟踪

时间:2018-12-27 23:32:39

标签: azure .net-core azure-application-insights

我有一个.NET核心API,该API执行与其他API的HTTP连接。我可以在Application Insights的“依赖事件类型”下可视化传出的HTTP请求,但是它只有基本信息。我正在研究如何添加有关传出HTTP调用的更多信息(例如HTTP标头)。

我研究了https://docs.microsoft.com/en-us/azure/azure-monitor/app/api-custom-events-metrics#trackdependency,但没有找到任何具体的方法。

1 个答案:

答案 0 :(得分:1)

我认为您正在寻找的是ITelemetryInitializer,它可以为依赖项遥测添加自定义属性。

对于.net核心Web项目,您可以参考此link

我编写了一个演示,如下所示:

1。创建一个自定义ITelemetryInitializer类以收集任何依赖项数据:

    public class MyTelemetryInitializer: ITelemetryInitializer
    {
        IHttpContextAccessor httpContextAccessor;

        public MyTelemetryInitializer(IHttpContextAccessor httpContextAccessor)
        {
            this.httpContextAccessor = httpContextAccessor;
        }

        public void Initialize(ITelemetry telemetry)
        {
            //only add custom property to dependency type, otherwise just return.
            var dependencyTelemetry = telemetry as DependencyTelemetry;
            if (dependencyTelemetry == null) return;

            if (!dependencyTelemetry.Context.Properties.ContainsKey("custom_dependency_headers_1"))
            {
                //the comment out code use to check the fields in Headers if you don't know
                //var s = httpContextAccessor.HttpContext.Request.Headers;
                //foreach (var s2 in s)
                //{
                //   var a1 = s2.Key;
                //    var a2 = s2.Value;
                //}

                dependencyTelemetry.Context.Properties["custom_dependency_headers_1"] = httpContextAccessor.HttpContext.Request.Headers["Connection"].ToString();
            }
        }

    }

2。然后在Startup.cs-> ConfigureServices方法中:

public void ConfigureServices(IServiceCollection services)
{
//other code

//add this line of code here
services.AddSingleton<ITelemetryInitializer, MyTelemetryInitializer>();
}

3。测试结果,检查是否将自定义属性添加到了Azure门户->“自定义属性”:

enter image description here