Linux环境Dotnet-Isolated消费计划Azure Function无法查看文件系统日志
问题描述
我有一个将日志发送至Azure Application Insights的Azure Function App,但无法查看任何控制台日志(见下图)。在使用Azure Functions Core Tools进行本地开发时,我可以看到通过ILogger<T>.LogInformation()等方法打印的控制台日志。通常在查看Premium级Azure Function App的文件系统日志时,会先显示“Connected!”,随后立即出现其他语句,但此处卡在“Connected!”。请问如何在Linux和dotnet-isolated的Consumption计划下成功查看文件系统日志?
代码示例
var host = new HostBuilder() .ConfigureFunctionsWebApplication((context, builder) => { }) .ConfigureAppConfiguration((context, builder) => { var environment = context.Configuration.GetValue<string>("ENVIRONMENT", "development"); builder.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{environment}.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables(); }) .ConfigureServices((context, services) => { services.AddApplicationInsightsTelemetryWorkerService(); services.ConfigureFunctionsApplicationInsights(); services.Configure<WorkerOptions>(options => { options.EnableUserCodeException = true; }); ... }) .ConfigureLogging(builder => { builder.Services.Configure<LoggerFilterOptions>(options => { // Default ApplicationInsights logging filter LoggerFilterRule defaultRule = options.Rules.FirstOrDefault(rule => rule.ProviderName == "Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider"); if (defaultRule is not null) { options.Rules.Remove(defaultRule); } }); builder.AddFilter<ApplicationInsightsLoggerProvider>("", LogLevel.Information); }) .Build();
日志截图

解决方案
针对Linux + .NET Isolated模式的Consumption计划Azure Function无法查看文件系统日志的问题,可按以下步骤修复:
1. 修正日志过滤规则
你的代码移除了Application Insights的默认过滤规则,但未配置控制台日志的输出权限。在ConfigureLogging中添加控制台日志的过滤配置:
builder.AddFilter<ConsoleLoggerProvider>("", LogLevel.Information);
确保全局日志级别未设置过高,避免拦截Info及以下级别的日志。
2. 配置Azure门户中的日志设置
进入Function App的Azure门户页面:
- 前往监控 > 日志,确认文件系统日志已启用(Consumption计划默认启用,可检查日志保留时间和级别)
- 打开配置 > 应用程序设置,添加/修改以下配置项:
AzureFunctionsJobHost__logging__console__isEnabled:trueAzureFunctionsJobHost__logging__logLevel__Default:Information- 验证
APPINSIGHTS_INSTRUMENTATIONKEY配置正确,避免因AI初始化异常导致日志丢失
3. 调整.NET Isolated Worker的日志配置
在ConfigureServices中为Worker添加控制台日志支持:
services.Configure<WorkerOptions>(options => { options.EnableUserCodeException = true; options.Logging.AddConsole(); // 确保Worker日志能输出到控制台 });
同时确认appsettings.json包含正确的日志配置:
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" }, "Console": { "IncludeScopes": true } } }
4. 注意Consumption计划的日志限制
Consumption计划下文件系统日志有特殊限制:
- 日志仅保留15分钟,且仅在函数运行期间生成
- 函数空闲时日志会话会中断,需先触发函数再查看日志
- Linux环境下日志输出可能有1-2分钟延迟,刷新页面等待即可
5. 替代日志查看方式
如果文件系统日志仍无法正常显示,可使用以下方式:
- 在监控 > 日志中用Kusto查询Application Insights日志:
traces | where timestamp > ago(1h) | order by timestamp desc - 使用Azure CLI拉取实时日志:
az functionapp log tail --name <你的函数应用名称> --resource-group <你的资源组名称>
内容的提问来源于stack exchange,提问作者Shuzheng
相关产品推荐
相关产品推荐

