我在 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> logger
实例同时具有“seq”和 aiTarget”目标 - 它会写入这两个位置。然而,稍后在代码中调用 _logger = LogManager.GetLogger("TraceLogger");
会返回一个不再写入“的实例” aiTarget”,仅进入“seq”。请问我应该如何修复此行为,同时保持与 .NET Framework 4.8 的向后兼容性?
我还想知道为什么开发环境中的
builder.Services.AddLogging(loggingBuilder => { loggingBuilder.AddNLog(); });
调用会加载 nlog.config
文件而不是 nlog.development.config
。
也许你需要设置
EnableActiveTelemetryConfigurationSetup
:
var appInsightsOptions = new ApplicationInsightsServiceOptions
{
EnableAdaptiveSampling = false,
ConnectionString = appInsightsConnectionString,
EnableActiveTelemetryConfigurationSetup = true,
};
builder.Services.AddApplicationInsightsTelemetry(appInsightsOptions);
另请参阅:https://github.com/microsoft/ApplicationInsights-dotnet/issues/2070
在 NLog 中排查日志记录时,查看 NLog 内部日志记录的输出也是一个好主意。