.NET 6中控制器ILogger日志无法写入Application Insights的问题
.NET 6中Application Insights无法捕获控制器ILogger日志的排查与解决
问题描述
我用.NET 6开发应用,已引入2.21.0版本的Microsoft.ApplicationInsights.AspNetCore和Microsoft.ApplicationInsights.DependencyCollector NuGet包,配置了经典Application Insights连接字符串。目前Program.cs中的日志能正常写入AI,但控制器通过构造注入ILogger输出的日志无法同步到AI服务,求排查原因。
相关代码
项目文件引用
<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.21.0" /> <PackageReference Include="Microsoft.ApplicationInsights.DependencyCollector" Version="2.21.0" />
Program.cs代码
using Microsoft.ApplicationInsights.Extensibility; using Microsoft.ApplicationInsights; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging.ApplicationInsights; using Microsoft.ApplicationInsights.AspNetCore.Extensions; var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllersWithViews(); builder.Services?.AddApplicationInsightsTelemetry(new ApplicationInsightsServiceOptions { ConnectionString = "InstrumentationKey=19233009-a529-494c-9b4b-3fd57d363357;IngestionEndpoint=https://centralus-0.in.applicationinsights.azure.com/;LiveEndpoint=https://centralus.livediagnostics.monitor.azure.com/" }); var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.Logger.LogInformation("TEST LOGS"); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run();
控制器代码
public class MyController : Controller { private readonly ILogger<MyController> _logger; public MyController(ILogger<MyController> logger) { _logger = logger; } public IActionResult Index() { _logger.LogInformation("From myController, running Index."); return View(); // 补充:原代码缺少返回语句,可能导致请求未正常完成 } }
排查与解决方案
1. 日志级别过滤配置问题
默认情况下,Application Insights日志收集器可能仅捕获Warning及以上级别的日志,而你使用的是LogInformation。需调整日志过滤规则:
- 在
appsettings.json中添加配置:
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" }, "ApplicationInsights": { "LogLevel": { "Default": "Information" } } } }
2. 服务注册顺序问题
当前代码先注册MVC服务,再注册Application Insights,可能导致日志提供者未正确关联到控制器的依赖注入容器。调整注册顺序:
var builder = WebApplication.CreateBuilder(args); // 先注册Application Insights builder.Services.AddApplicationInsightsTelemetry(new ApplicationInsightsServiceOptions { ConnectionString = "你的连接字符串" }); builder.Services.AddControllersWithViews(); // 再注册MVC服务 var app = builder.Build(); // 后续代码不变
3. 验证控制器路由访问
当前路由默认指向Home/Index,需确认你实际访问的是/My/Index,否则控制器的日志代码根本不会执行。
4. 补充控制器返回语句
原控制器代码的Index方法缺少return View();或其他返回结果,导致请求未正常完成,日志可能被中断发送。需补充返回逻辑。
5. 手动验证日志提供者
在控制器中注入ILoggerFactory,检查是否包含Application Insights日志提供者:
public MyController(ILogger<MyController> logger, ILoggerFactory loggerFactory) { _logger = logger; var hasAiProvider = loggerFactory.GetProviders().Any(p => p.GetType().Name == "ApplicationInsightsLoggerProvider"); // 调试查看hasAiProvider是否为true }
内容的提问来源于stack exchange,提问作者roney
相关产品推荐
相关产品推荐

