如何从类库项目向App Insights发送ILogger产生的日志数据
解决方案
1. 检查日志过滤配置
这是最常见的问题原因,ASP.NET Core 日志系统默认会按命名空间匹配过滤规则,大概率你只给Web项目的命名空间开放了符合上报要求的日志级别,Business类库对应的命名空间日志级别被设得过高,导致日志被过滤未上报。
你可以检查appsettings.json里的Logging节点配置,以下是正确配置示例:
{ "Logging": { "IncludeScopes": false, "ApplicationInsights": { "LogLevel": { "Default": "Information", "Business": "Information", "Microsoft": "Warning", "System": "Warning" } }, "LogLevel": { "Default": "Information", "Business": "Information", "Microsoft": "Warning", "System": "Warning" } } }
注意:Logging下的全局LogLevel和ApplicationInsights节点下的LogLevel都会生效,后者优先级更高,建议两边同步配置类库的日志级别。
2. 确认App Insights注册配置
ASP.NET Core 2.x版本需要确保你在Program.cs的BuildWebHost方法中正确注册了App Insights的日志提供程序,示例配置如下:
public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .AddApplicationInsightsTelemetry() .ConfigureLogging(logging => { // 部分低版本需要显式加这行注册App Insights日志提供程序 logging.AddApplicationInsights(); }) .Build();
如果是在Startup.cs里注册服务,也要确保ConfigureServices方法中有services.AddApplicationInsightsTelemetry(Configuration);这行配置。
3. 检查采样过滤规则
如果你开启了App Insights的自适应采样或者固定采样,可能会导致部分日志被采样丢弃,可以临时关闭采样验证日志是否能正常上报,示例配置:
public void ConfigureServices(IServiceCollection services) { services.AddApplicationInsightsTelemetry(); // 将Trace类型日志排除在采样外,也可根据需求直接关闭采样 services.ConfigureTelemetryProcessorChainBuilder(builder => builder.UseAdaptiveSampling(maxTelemetryItemsPerSecond: 100, excludedTypes: "Trace") ); }
4. 验证类库的ILogger注入方式
确认Business类库中的类都是通过**构造函数注入ILogger<T>**的方式获取日志实例,不要手动构造Logger实例,手动构造的实例不会绑定到Web应用的日志管道,无法上报到App Insights。
内容的提问来源于stack exchange,提问作者Riz
相关产品推荐
相关产品推荐

