在 ASP.NET Core 应用程序中使用 Application Insights 可能会导致重复的日志条目,这通常是由于 ILoggerFactory
的配置问题引起的。为避免这种情况,应在 Startup.cs
文件中调用 .AddApplicationInsights()
方法,而不是手动设置 ILoggerProvider
。下面是一个示例:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
//...
app.UseApplicationInsightsRequestTelemetry();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
});
loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Error);
}
在 loggerFactory.AddApplicationInsights()
方法中,可以设置日志记录级别(例如 LogLevel.Error
)。此外,还可以在 ILogger
实例上应用不同的级别:
private readonly ILogger _logger;
public MyController(ILogger logger)
{
_logger = logger;
}
public IActionResult Index()
{
_logger.LogInformation("This is an informational message");
_logger.LogError("This is an error message");
_logger.LogDebug("This is a debug message");
return View();
}
请注意,由于 Application Insights 不收集所有日志级别的数据,因此可能需要对其进行配置以包含所需的信息。