Azure Flex Consumption Apps无法向App Insights写入日志求助
从2月20日左右开始,我们的Azure弹性消费函数应用不再向App Insights写入日志。同期Logic Apps因使用已弃用的App Insights检测密钥导致日志故障,切换为连接字符串后问题解决,但弹性消费应用始终配置了正确的APPLICATIONINSIGHTS_CONNECTION_STRING,却依然无法正常记录日志。目前部署后仅能看到启动跟踪日志,无请求日志记录,怀疑是平台迭代变更导致,以下是针对性排查方案:
当前配置信息
Program.cs关键代码段
var host = new HostBuilder() .ConfigureFunctionsWorkerDefaults() .ConfigureServices(s => { ... s.AddApplicationInsightsTelemetryWorkerService(); s.ConfigureFunctionsApplicationInsights(); s.Configure<LoggerFilterOptions>(o => { // The Application Insights SDK adds a default logging filter that instructs ILogger to capture only Warning and more severe logs. Application Insights requires an explicit override. // Log levels can also be configured using appsettings.json. For more information, see https://learn.microsoft.com/en-us/azure/azure-monitor/app/worker-service#ilogger-logs LoggerFilterRule defaultRule = o.Rules.FirstOrDefault(r => r.ProviderName == "Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider")!; if (defaultRule is not null) { o.Rules.Remove(defaultRule); } }); ... }) .Build(); host.Run();
相关NuGet包
<PackageReference Include="Microsoft.ApplicationInsights.WorkerService" Version="2.22.0" /> <PackageReference Include="Microsoft.Azure.Functions.Worker.ApplicationInsights" Version="2.0.0" />
Host.json配置
{ "version": "2.0", "logging": { "applicationInsights": { "samplingSettings": { "isEnabled": true, "excludedTypes": "Request" } } } }
排查方案
修正Host.json采样配置
当前配置中samplingSettings.excludedTypes设为Request,会直接排除请求类型日志写入App Insights。建议移除该配置项或设置为空值,重新部署后测试请求日志是否恢复。验证连接字符串权限
确认APPLICATIONINSIGHTS_CONNECTION_STRING对应的App Insights资源权限正常,函数应用的托管标识/服务主体拥有写入该资源的权限。可在Azure门户检查App Insights的IAM权限设置,确认无权限变更。升级NuGet包版本
当前使用的SDK版本相对老旧,弹性消费函数作为新服务可能对SDK版本有更高要求。尝试将Microsoft.ApplicationInsights.WorkerService升级至2.24.0+,Microsoft.Azure.Functions.Worker.ApplicationInsights升级至2.1.0+,重新部署后验证日志状态。检查平台侧日志限制
进入Azure门户函数应用的「监控」>「日志」面板,查看是否有平台级错误提示;同时检查「诊断设置」,确认针对App Insights的日志规则未被修改或禁用。补充显式日志级别配置
在Host.json中添加日志级别配置,确保请求相关日志能被捕获:{ "version": "2.0", "logging": { "logLevel": { "default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" }, "applicationInsights": { "samplingSettings": { "isEnabled": true } } } }本地调试验证
在本地运行函数应用,检查控制台是否输出请求日志,同时确认本地App Insights能否接收日志。若本地正常,问题大概率在Azure平台侧;若本地也异常,重点排查代码或SDK配置。查看平台原始日志
通过函数应用的「高级工具(Kudu)」进入调试控制台,查看D:\home\LogFiles\Application\Functions下的日志文件,检查是否存在App Insights连接失败、权限不足等错误信息。
内容的提问来源于stack exchange,提问作者Crwydryn

