代码之家  ›  专栏  ›  技术社区  ›  kord

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

  •  0
  • kord  · 技术社区  · 6 年前

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

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

    1 回复  |  直到 6 年前
        1
  •  1
  •   Ivan Glasenberg    6 年前

    我想你要找的是 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