无法使用 NLog 创建日志

Unable to Create Logs with NLog

我有一个 .NET 应用程序。我正在尝试使用 NLog 编写一些日志。我的应用程序非常基础,可以成功运行而不会抛出异常。但是,我在任何地方都看不到实际的日志文件。我怎样才能让我的日志真正写入?

MyLogger.cs

using NLog;
public class MyLogger
{
  private static Logger logger = LogManager.GetCurrentClassLogger();

  public void Log(string message)
  {
    logger.Info(message);
  }
}

Program.cs

static class Program
{
  static void Main()
  {
    var logger = new MyLogger();
    logger.Log("hello");
  }
}

我在 App.config 文件中添加了 NLog 配置详细信息,如下所示:

App.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />
  </configSections>

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
  </startup>

  <appSettings>
  </appSettings>

  <nlog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <targets>
      <target name="logFile" xsi:type="File" fileName="C:\Logs\MyApp.log" keepFileOpen="true" encoding="Utf8" layout="${longdate} ${logger} ${message}${exception:format=ToString}"></target>
    </targets>

    <rules>
      <logger name="*" minlevel="Info" writeTo="logFile" />
      <logger name="*" minlevel="Warn" writeTo="logFile" />
    </rules>
  </nlog>  
</configuration>

我没有使用 NLog.config 文件。我的印象是我可以将我的整个配置设置放在 App.config 文件中。我错过了什么?如何使用 NLog 将日志写入文本文件?

谢谢!

确保文件夹 "C:/logs" logs 已创建并且应用程序有权在其中读取和写入。您可能只对 C 驱动器根目录中的 Users 组具有只读访问权限。如果将日志路径设置为 C:/Users/<your_username/test.log

,则可以对其进行测试

要自动创建文件夹,请使用以下配置。

<target xsi:type="File"
    ...
    createDirs="true" />

这不会直接解决问题,但会帮助您找出它不起作用的原因。

通过将此添加到您的配置文件来打开 Internal Logging

<nlog internalLogFile="c:\log.txt" internalLogLevel="Trace">

将该文件记录到驱动器的根目录以减少它成为权限问题的可能性。如果仍然失败,请确保在调试选项中中断所有内容,并删除 just my code(如果已启用)。也许这会有所帮助。

注意:一旦日志记录正常工作,请不要忘记将其关闭,因为它会对性能造成 重大™ 影响。

这是编码。它想要 "utf-8" 而不是 "Utf8"