Azure WebJobs如何禁用Application Insights的自适应采样功能?
问题描述
我曾查阅过相关MSDN文章,其介绍了如何为不同类型应用配置AppInsights采样功能,但未找到针对Azure WebJobs的配置方法。
通常WebJob的AppInsights配置代码如下:
static async Task Main() { var builder = new HostBuilder(); builder.UseEnvironment(EnvironmentName.Development); builder.ConfigureWebJobs(b => { b.AddAzureStorageCoreServices(); b.AddAzureStorage(); }); builder.ConfigureLogging((context, b) => { b.AddConsole(); // 若配置项中存在对应密钥,则通过该密钥启用Application Insights string instrumentationKey = context.Configuration["APPINSIGHTS_INSTRUMENTATIONKEY"]; if (!string.IsNullOrEmpty(instrumentationKey)) { b.AddApplicationInsightsWebJobs(o => o.InstrumentationKey = instrumentationKey); } }); var host = builder.Build(); using (host) { await host.RunAsync(); } }
相关核心代码如下:b.AddApplicationInsightsWebJobs(o => o.InstrumentationKey = instrumentationKey);
对应的配置项如下图所示:
请问在现有配置逻辑下是否可以禁用自适应采样?恳请提供解决方案,非常感谢!
解决方案
现有配置逻辑完全支持禁用自适应采样,共有两种常用实现方案:
方案1:代码直接配置(无需修改配置项)
先确保你已安装最新稳定版的Microsoft.Azure.WebJobs.Logging.ApplicationInsights NuGet包,之后在原有配置逻辑中新增ConfigureServices段关闭自适应采样开关即可,修改后的完整代码如下:
static async Task Main() { var builder = new HostBuilder(); builder.UseEnvironment(EnvironmentName.Development); builder.ConfigureWebJobs(b => { b.AddAzureStorageCoreServices(); b.AddAzureStorage(); }); builder.ConfigureLogging((context, b) => { b.AddConsole(); // 若配置项中存在对应密钥,则通过该密钥启用Application Insights string instrumentationKey = context.Configuration["APPINSIGHTS_INSTRUMENTATIONKEY"]; if (!string.IsNullOrEmpty(instrumentationKey)) { b.AddApplicationInsightsWebJobs(o => o.InstrumentationKey = instrumentationKey); } }); // 新增这段配置关闭自适应采样 builder.ConfigureServices(services => { services.Configure<Microsoft.ApplicationInsights.WorkerService.ApplicationInsightsServiceOptions>(options => { options.EnableAdaptiveSampling = false; }); }); var host = builder.Build(); using (host) { await host.RunAsync(); } }
方案2:配置项配置(无需修改代码)
如果不想改动业务代码,直接通过配置即可实现关闭:
- 本地开发使用
appsettings.json配置的场景,添加如下节点:
{ "ApplicationInsights": { "EnableAdaptiveSampling": false } }
- Azure门户部署的WebJob场景,直接在对应App Service的配置 > 应用设置中添加新配置:
- 键:
ApplicationInsights:EnableAdaptiveSampling - 值:
false
- 键:
配置完成后重启WebJob即可生效,你可以通过连续发送多批测试遥测数据,在App Insights控制台核对数据采集完整性,验证配置是否生效。
内容的提问来源于stack exchange,提问作者Cristian E.
相关产品推荐
相关产品推荐

