.NET Core6 Azure Function ILogger日志未上报Application Insights
.NET 6 Azure Functions 自定义ILogger日志未上报Application Insights修复方案
核心原因
当前配置缺失Application Insights(AI)日志提供程序的独立过滤规则,且Startup类未做对应日志管道配置,导致运行时默认过滤掉用户自定义类别的ILogger输出,仅保留Host、Function内置类别的日志上报。触发器、执行结果日志属于内置类别,因此可以正常展示。
修复步骤
1. 修正host.json配置
全局logLevel配置仅作为所有日志提供程序的基础规则,AI日志提供程序有独立的过滤优先级,必须单独配置捕获级别。在logging.applicationInsights节点下补充logLevel配置,修改后完整配置如下:
{ "version": "2.0", "logging": { "applicationInsights": { "samplingSettings": { "isEnabled": false, "excludedTypes": "Request" }, "logLevel": { "default": "Information", "YourProjectRootNamespace.QueueWorker": "Trace" } }, "fileLoggingMode": "always", "logLevel": { "default": "Trace", "Host": "Trace", "Function": "Trace", "Host.Aggregator": "Trace" } } }
若不需要捕获自定义类的Trace级别调试日志,可以删除针对
QueueWorker的单独配置,保留default级别为Information即可覆盖LogInformation类别的业务日志。
2. 补全Startup类配置
如果项目使用FunctionsStartup做依赖注入注册,不要清空默认日志提供程序,同时显式配置AI日志提供程序的过滤规则,参考代码如下:
using Microsoft.Azure.Functions.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.ApplicationInsights; [assembly: FunctionsStartup(typeof(YourProjectNamespace.Startup))] namespace YourProjectNamespace { public class Startup : FunctionsStartup { public override void Configure(IFunctionsHostBuilder builder) { // 禁止调用builder.Services.ClearLoggingProviders(),该方法会清空内置的AI日志提供程序 builder.Services.AddLogging(logBuilder => { // 配置全局AI日志最低上报级别为Information logBuilder.AddFilter<ApplicationInsightsLoggerProvider>("", LogLevel.Information); // 如需捕获QueueWorker类的Trace级别日志,添加单独过滤规则 logBuilder.AddFilter<ApplicationInsightsLoggerProvider>(typeof(QueueWorker).FullName, LogLevel.Trace); }); // 其余业务服务注册逻辑保持不变 } } }
3. 前置校验项
- 确认NuGet包版本匹配:进程内(In-Process)模型需安装
Microsoft.Azure.WebJobs.Logging.ApplicationInsights,独立工作者(Isolated Worker)模型需安装Microsoft.Azure.Functions.Worker.ApplicationInsights,包版本需与.NET 6、Azure Functions SDK版本兼容。 - 确认函数应用配置中
APPLICATIONINSIGHTS_CONNECTION_STRING连接字符串填写正确,无拼写错误、权限问题。 - 本地调试时先检查控制台输出,若控制台可看到自定义日志但AI端无数据,可直接判定为上述日志过滤规则配置问题,无需排查链路连通性。
- 当前配置已关闭采样,不存在因采样丢弃业务日志的问题。
内容的提问来源于stack exchange,提问作者Darthg8r
相关产品推荐
相关产品推荐

