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

问题描述 投票:1回答:1

我已经将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自己的日志显示以下内容:

错误错误已引发。异常:System.ArgumentException:路径不是合法形式。在NLog.Targets.FileTarget.Write(LogEventInfo logEvent)位于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"
    }
  }
c# asp.net-core nlog
1个回答
0
投票

感谢RolfKristensen的建议,我设法使它起作用。现在可以在NLog初始化之前读取Appsettings,因此NLog现在可以读取其中的文件路径。我使用ConfigSetting Layout Renderer来检索NLog.config中的filePath。

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}"

© www.soinside.com 2019 - 2024. All rights reserved.