Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure Application Insights sampling on Net Core HostBuilder?

I'm building .Net Core background service, using ApplicationInsights.WorkerService nuget package. The documentation regarding sampling configuration says to refer to this: https://learn.microsoft.com/en-us/azure/azure-monitor/app/sampling#configure-sampling-settings

And it shows this:

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

  // ...
}

Now on HostBuilder I don't see any extension methods that would give me the TelemetryConfiguration, source code of the nuget doesn't have it either: https://github.com/microsoft/ApplicationInsights-aspnetcore/blob/develop/NETCORE/src/Microsoft.ApplicationInsights.WorkerService/ApplicationInsightsExtensions.cs

So how do I get either TelemetryConfiguration or TelemetryProcessorChainBuilder on a HostBuilder? At the moment it looks like this:

Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddHostedService<Worker>();
                    services.AddApplicationInsightsTelemetryWorkerService();
                });
like image 335
Erndob Avatar asked Sep 16 '25 18:09

Erndob


1 Answers

You should use it as below:

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
                });
like image 96
Ivan Yang Avatar answered Sep 19 '25 07:09

Ivan Yang