Azure隔离式工作进程自定义遥测无法写入Application Insights问题
修复Azure Durable Functions隔离进程自定义遥测问题
1. 补充必要的NuGet包
在你的csproj中添加隔离进程专用的App Insights集成包:
<PackageReference Include="Microsoft.Azure.Functions.Worker.ApplicationInsights" Version="1.0.0" />
该版本与你当前使用的
Microsoft.Azure.Functions.Worker 1.10.0版本兼容。
2. 修改Program.cs配置
必须先初始化Worker默认配置,再注册App Insights服务和自定义遥测初始化器,确保服务加载顺序正确:
var host = new HostBuilder() .ConfigureFunctionsWorkerDefaults() // 初始化隔离进程基础服务(日志、绑定等) .ConfigureServices((_, services) => { services .AddHttpClient() .AddApplicationInsightsTelemetryWorkerService() // 注册App Insights Worker服务 .AddSingleton<ITelemetryInitializer, CustomTelemetry>(); // 添加自定义遥测初始化器 }) .Build(); host.Run();
3. 修复CustomTelemetry中的重复键问题
避免因重复添加相同键的属性导致运行时异常,添加前先检查键是否存在:
public class CustomTelemetry : ITelemetryInitializer { public void Initialize(ITelemetry telemetry) { // 全局属性:先检查再添加 if (!telemetry.Context.GlobalProperties.ContainsKey("GlobalProperties")) { telemetry.Context.GlobalProperties.Add("GlobalProperties", "FromCustomTelemetryYeeeeeeyyy"); } if (telemetry is TraceTelemetry traceTelemetry) { if (!traceTelemetry.Context.GlobalProperties.ContainsKey("GlobalProperties")) { traceTelemetry.Context.GlobalProperties.Add("GlobalProperties", "FromCustomTelemetryYeeeeeeyyy"); } if (!traceTelemetry.Properties.ContainsKey("CustomTraceTelemetry")) { traceTelemetry.Properties.Add("CustomTraceTelemetry", "FromCustomTelemetryYeeeeeeyyy"); } } if (telemetry is ISupportProperties itemProperties) { if (!itemProperties.Properties.ContainsKey("customProp")) { itemProperties.Properties["customProp"] = "customValue"; } } if (telemetry is RequestTelemetry requestTelemetry) { if (!requestTelemetry.Context.GlobalProperties.ContainsKey("GlobalProperties")) { requestTelemetry.Context.GlobalProperties.Add("GlobalProperties", "FromCustomTelemetryYeeeeeeyyy"); } if (!requestTelemetry.Properties.ContainsKey("LoggedInUserName")) { requestTelemetry.Properties.Add("LoggedInUserName", "DummyUser"); } } } }
4. 配置host.json确保日志流向App Insights
在项目根目录的host.json中添加日志规则,确保App Insights能捕获到函数日志:
{ "version": "2.0", "logging": { "applicationInsights": { "samplingSettings": { "isEnabled": true, "excludedTypes": "Request" }, "enableLiveMetricsFilters": true }, "logLevel": { "default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } } }
5. 验证配置
部署或本地运行函数后,触发Http函数,在Application Insights的日志中执行以下Kusto查询验证自定义属性:
traces | where customDimensions contains "customProp" | project timestamp, message, customDimensions
查询结果应包含你定义的所有自定义属性。
本地运行时,需确保
local.settings.json中配置了APPINSIGHTS_INSTRUMENTATIONKEY或APPLICATIONINSIGHTS_CONNECTION_STRING。
内容的提问来源于stack exchange,提问作者Serhat
相关产品推荐
相关产品推荐

