如何为.NET 5隔离进程的Azure Timer函数配置Application Insights
解决方案
你需要先安装.NET隔离进程模式专用的Application Insights NuGet包:Microsoft.Azure.Functions.Worker.ApplicationInsights,选择适配.NET 5的版本即可。
完整配置代码
你现有的启动代码只需在ConfigureServices块中添加对应的注册方法,效果完全等效于ASP.NET Core里的services.AddApplicationInsightsTelemetry():
var host = new HostBuilder() .ConfigureFunctionsWorkerDefaults() .ConfigureServices((hostBuilderContext, s) => { // Get IConfiguration var configuration = hostBuilderContext.Configuration; // 配置Application Insights,自动读取配置中的连接字符串/ instrumentation key s.AddApplicationInsightsTelemetryWorkerService(); // 可选:自定义配置项 s.Configure<ApplicationInsightsServiceOptions>(options => { // 比如设置采样率、禁用特定遥测收集等 options.EnableAdaptiveSampling = true; // 如果不想从配置读取,也可以手动指定连接字符串 // options.ConnectionString = "你的Application Insights连接字符串"; }); // Configure services based on config settings }) .Build();
注意事项
- 你需要在函数应用的配置中添加
APPLICATIONINSIGHTS_CONNECTION_STRING(推荐)或者APPINSIGHTS_INSTRUMENTATIONKEY配置项,值取Azure Portal中Application Insights资源的对应值即可,注册方法会自动读取该配置完成初始化。 - 如果需要自定义遥测处理逻辑,直接将自定义的
ITelemetryInitializer、ITelemetryProcessor实现注册为服务即可,会自动生效。
内容的提问来源于stack exchange,提问作者frosty
相关产品推荐
相关产品推荐

