为什么 NLog 在控制器中工作而不在 Program.cs 中工作?

Why does NLog work in controllers and not in Program.cs?

我已将 NLog 添加到我的 MVC Core 2.2 项目中,除应用程序启动日志记录外,一切正常。日志在控制器中写得很好,但在 Program.cs 中却不好。 这是我的主要方法,所有 NLog 内容都取自 NLog 文档:

public static void Main(string[] args)
{
    // NLog: setup the logger first to catch all errors
    var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
    try
    {
        logger.Info("Starting app");
        CreateWebHostBuilder(args).Build().Run();
    }
    catch (Exception ex)
    {
        // NLog: catch setup errors
        logger.Error(ex, "App failed to start");
        throw;
    }
    finally
    {
        // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
        NLog.LogManager.Shutdown();
    }
}

NLog自己的日志显示如下:

Error Error has been raised. Exception: System.ArgumentException: The path is not of a legal form. at NLog.Targets.FileTarget.Write(LogEventInfo logEvent) at NLog.Targets.Target.Write(AsyncLogEventInfo logEvent)

这很奇怪,因为日志在我定义的文件路径中被正确写入。

这是我的 nlog.config :

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      internalLogLevel="Info"
      internalLogFile="c:\temp\nlog.log"
      throwConfigExceptions="true">

  <!-- enable asp.net core layout renderers -->
  <extensions>
    <add assembly="NLog.Web.AspNetCore"/>
  </extensions>

  <variable name="logFilePath" value="${configsetting:name=Logging.LogFilePath}"/>

  <targets>
    <target xsi:type="File"
            name="PortailUsagersCore"
            fileName="${logFilePath}"
            layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|controller: ${aspnet-mvc-controller}|action: ${aspnet-mvc-action}"
            maxArchiveFiles="4"
            archiveNumbering="Rolling"
            archiveAboveSize="2097152" />
  </targets>

  <rules>
    <logger name="*" writeTo="PortailUsagersCore" />
  </rules>
</nlog>

LogFilePath 在日志记录部分的 appsettings.json 和 appsettings.development.json 中定义:

"Logging": {
    "LogFilePath": "C:\Logs\Portail\PortailUsagersCore.log",
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Trace",
      "Microsoft": "Information"
    }
  }

多亏了 RolfKristensen 的建议,我设法让它工作了。 Appsettings 现在在 NLog 初始化之前读取,因此 NLog 现在能够读取其中的文件路径。我使用 NLog.GlobalDiagnosticsContext 在 NLog.config 中设置文件路径。

string env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

// Load config file to read LogFilePath
var config = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddJsonFile($"appsettings.{env}.json", optional: true, reloadOnChange: true)
    .Build();

// LogFilePath is read in nlog.config
NLog.GlobalDiagnosticsContext.Set("LogFilePath", config["Logging:LogFilePath"]);

// NLog: setup the logger first to catch all errors
var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();

而在我的 NLog.config 中,我是这样使用它的:

<variable name="logFilePath" value="${gdc:item=LogFilePath}"/>
<targets>
    <target xsi:type="File"
            name="PortailUsagersCore"
            fileName="${logFilePath}"