本地运行的.NET 7 Azure Worker Function中Application Insights无法生效
以下是你配置中存在的问题及对应的解决步骤:
日志级别过滤导致日志无法上传
host.json的logLevel配置里,Function项被设为Error,而你代码中调用的LogInformation属于Information级别,低于Error,因此这类日志会被系统过滤,无法发送到Application Insights。修改Function的日志级别为Information:"logLevel": { "default": "Information", "Microsoft": "Warning", "System": "Warning", "Host": "Error", "Function": "Information", "Host.Aggregator": "Information" }采样配置冲突导致数据丢失
你在服务注册时禁用了自适应采样,但host.json中applicationInsights.samplingSettings.isEnabled仍为true,采样机制会过滤部分数据。将host.json中的采样设置改为禁用:"applicationInsights": { "samplingSettings": { "isEnabled": false } }确认Worker模式专属依赖包已安装
必须安装Microsoft.Azure.Functions.Worker.ApplicationInsightsNuGet包,这是Worker类型Function集成Application Insights的专属包,不能用普通的Application Insights包替代。Serilog未配置Application Insights输出端
你的配置使用了Serilog,但未将日志输出到Application Insights。需要安装Serilog.Sinks.ApplicationInsights包,并在Serilog的WriteTo节点添加对应配置:"Serilog": { "MinimumLevel": "Information", "WriteTo": [ { "Name": "Console", "Args": { "outputTemplate": "{Timestamp:HH:mm:ss} {Level} | {RequestId} - {Message}{NewLine}{Exception}" } }, { "Name": "ApplicationInsights", "Args": { "connectionString": "你的连接字符串", "telemetryConverter": "Serilog.Sinks.ApplicationInsights.TelemetryConverters.TraceTelemetryConverter, Serilog.Sinks.ApplicationInsights" } } ] }本地运行时验证连接字符串有效性
本地调试时,确保配置的Application Insights连接字符串正确无误,也可通过设置环境变量APPINSIGHTS_CONNECTION_STRING来传递,避免硬编码可能带来的错误。
内容的提问来源于stack exchange,提问作者Paul

