如何将 CosmosDB 依赖项跟踪数据从 Azure Function Event Hub 触发器发送到 Application Insights

How to send CosmosDB dependency tracking data to Application Insights from Azure Function Event Hub Trigger

我有一个由 eventhub 触发并批量发送数据的 Azure Function。在函数内部,有多个调用将数据插入 CosmosDB。我添加了以下代码作为 App Insight 监控的一部分。

 builder.Services.AddApplicationInsightsTelemetry();

            builder.Services.ConfigureTelemetryModule<DependencyTrackingTelemetryModule>((module, o) =>
            {
                module.EnableW3CHeadersInjection = true;
            });

         
            builder.Services.ConfigureTelemetryModule<EventCounterCollectionModule>(
                    (module, o) =>
                    {
                        module.Counters.Add(new EventCounterCollectionRequest("System.Runtime", "gen-0-size"));
                    }
                );

我可以在 App Insight 中看到总响应时间,但无法弄清楚如何跟踪和发送每个插入查询所花费的时间 CosmosDB

这是 Azure Function

中的 C# 代码
var watch = System.Diagnostics.Stopwatch.StartNew();
                    
                    var DemoContainerData = new
                       {
                           id = Guid.NewGuid().ToString(),
                           UserId = userId,
                           // other properties 
                       };

                       _demoContainer.CreateItemAsync<object>(DemoContainerData);
                       
                       var DemoContainerData2 = new
                       {
                           id = Guid.NewGuid().ToString(),
                           ProductId = productId,
                           // other properties 
                       };

                       _productContainer.CreateItemAsync<object>(DemoContainerData2);
              /* var dependency = new DependencyTelemetry
               {
                   Name = "",
                   Target = "",
                   Data = ",
                   Timestamp = start,
                   Duration = DateTime.UtcNow - start,
                   Success = true
               };
               this._telemetryClient.TrackDependency(dependency);
               */                    
            watch.Stop();
            var elapsed = watch.Elapsed.TotalMilliseconds;
            log.LogInformation("Total Items {0} - Total Time {1}", Items.Length, elapsed);     

您的代码没有等待异步操作,您应该:

ItemResponse<object> response = await _demoContainer.CreateItemAsync<object>(DemoContainerData);

从响应中,您可以测量客户端延迟:

var elapsedTimeForOperation = response.Diagnostics.GetClientElapsedTime();

如果您想调查高延迟,我们建议您在请求超过某个阈值时记录诊断,例如:

if (response.Diagnostics.GetClientElapsedTime() > ConfigurableSlowRequestTimeSpan)
    {
        // Log the diagnostics and add any additional info necessary to correlate to other logs 
        log.LogWarning("Slow request {0}", response.Diagnostics);
    }

为了获得最佳延迟,请确保您遵循 https://docs.microsoft.com/azure/cosmos-db/sql/troubleshoot-dot-net-sdk-slow-request?tabs=cpu-new#application-design(主要是确保您使用的是 Singleton 客户端,使用 ApplicationRegionApplicationPreferredRegions 定义希望连接的首选区域是函数部署到的同一区域)。