如何在 Net Core HostBuilder 上配置 Application Insights 采样?

Ern*_*dob 3 azure azure-application-insights .net-core

我正在使用 ApplicationInsights.WorkerService nuget 包构建 .Net Core 后台服务。有关采样配置的文档表示请参考此: https: //learn.microsoft.com/en-us/azure/azure-monitor/app/sampling#configure-sampling-settings

它显示了这一点:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, TelemetryConfiguration configuration)
{
  var builder = configuration.DefaultTelemetrySink.TelemetryProcessorChainBuilder;
  // For older versions of the Application Insights SDK, use the following line instead:
  // var builder = configuration.TelemetryProcessorChainBuilder;

  // Using adaptive sampling
  builder.UseAdaptiveSampling(maxTelemetryItemsPerSecond:5);

  // Alternately, the following configures adaptive sampling with 5 items per second, and also excludes DependencyTelemetry from being subject to sampling.
  // builder.UseAdaptiveSampling(maxTelemetryItemsPerSecond:5, excludedTypes: "Dependency");

  // If you have other telemetry processors:
  builder.Use((next) => new AnotherProcessor(next));

  builder.Build();

  // ...
}
Run Code Online (Sandbox Code Playgroud)

现在在 HostBuilder 上我没有看到任何可以为我提供 TelemetryConfiguration 的扩展方法,nuget 的源代码也没有它: https://github.com/microsoft/ApplicationInsights-aspnetcore/blob/develop/NETCORE/ src/Microsoft.ApplicationInsights.WorkerService/ApplicationInsightsExtensions.cs

那么如何在 HostBuilder 上获取 TelemetryConfiguration 或 TelemetryProcessorChainBuilder 呢?目前它看起来像这样:

Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddHostedService<Worker>();
                    services.AddApplicationInsightsTelemetryWorkerService();
                });
Run Code Online (Sandbox Code Playgroud)

Iva*_*ang 7

您应该按如下方式使用它:

Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddHostedService<Worker>();

                    services.Configure<TelemetryConfiguration>((config)=>
                    {
                        var builder = config.DefaultTelemetrySink.TelemetryProcessorChainBuilder;

                        builder.UseAdaptiveSampling(maxTelemetryItemsPerSecond: 5);
                        builder.Build();
                    }                    
                    );

                   // Your other code
                });
Run Code Online (Sandbox Code Playgroud)

  • 我希望某处有可用的工作示例。我浪费了很多时间试图让它与 App Insights 配置的特性一起工作:( (2认同)