You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 14:25:18