ASP.NET Core 8中NLog无法写入ApplicationInsightsTarget的问题
ASP.NET Core 8.0中NLog日志异常问题及疑问
问题背景
在ASP.NET Core 8.0应用中遇到以下异常行为,该问题在.NET Framework 4.8中不存在:
相关配置
使用的相关NuGet包(原文提及有图示),当前采用nlog.development.config配置文件,内容如下:
<nlog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <extensions> <add assembly="NLog.Web.AspNetCore"/> <add assembly="Seq.Client.NLog" /> <add assembly="Microsoft.ApplicationInsights.NLogTarget" /> </extensions> <targets> <target name="seq" xsi:type="Seq" serverUrl="http://localhost:5341" /> <target name="aiTarget" xsi:type="ApplicationInsightsTarget" /> </targets> <rules> <logger name="*" minlevel="Trace" writeTo="seq" /> <logger name="*" minlevel="Info" writeTo="aiTarget" /> </rules> </nlog>
Main方法中的日志配置代码:
var appInsightsConnectionString = builder.Configuration["AppInsightsConnectionString"]; var appInsightsOptions = new ApplicationInsightsServiceOptions { EnableAdaptiveSampling = false, ConnectionString = appInsightsConnectionString }; builder.Services.AddApplicationInsightsTelemetry(appInsightsOptions); var nlogConfigFile = builder.Environment.IsDevelopment() ? "nlog.development.config" : "nlog.config"; LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration(nlogConfigFile); builder.Services.AddLogging(loggingBuilder => { loggingBuilder.AddNLog(); });
具体问题
- 注入到
ScheduleController的ILogger<ScheduleController>实例可同时写入seq和aiTarget,但通过LogManager.GetLogger("TraceLogger")获取的实例仅能写入seq,无法写入aiTarget。需修复此问题并保持与.NET Framework 4.8的向后兼容性。 - 开发环境中执行
builder.Services.AddLogging(loggingBuilder => { loggingBuilder.AddNLog(); })时,为何加载nlog.config而非nlog.development.config?
内容的提问来源于stack exchange,提问作者eugen_nw
相关产品推荐
相关产品推荐

