NLog没有显示任何内容?

5

由于某些奇怪的原因,当我在Program.cs的Main()方法中分配nlog.config时,nlog不会在控制台中显示任何内容:

LogManager.Configuration = new XmlLoggingConfiguration("assets/packages/nlog/nlog.config");

这里是配置:

<nlog throwExceptions="true">
  <targets>
    <target name="file" type="File" fileName="${basedir}/assets/logging/log.txt" />
  </targets>
  <rules>
    <logger name="*" minLevel="Info" writeTo="File" />
  </rules>
</nlog>

这里是一个示例类:

private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();

public MyClass()
{
    Console.Write("lol");
    Logger.Debug("Debug test...");
    Logger.Error("Debug test...");
    Logger.Fatal("Debug test...");
    Logger.Info("Debug test...");
    Logger.Trace("Debug test...");
    Logger.Warn("Debug test...");
}

我知道这个方法被调用了,因为我得到了“lol”,但控制台上实际的日志没有打印出来,但它确实写入了 /assets/logging/log.txt 文件。


你确认文件名路径正确吗? - Dave S
如果不是的话,它会抛出一个异常。 - Ashkru
请查看 https://github.com/NLog/NLog/wiki/Internal-logging。 - Julian
4个回答

7
为了在控制台上查看日志输出,您需要:
<?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">

    <targets>
        <target name="console" xsi:type="Console" />
    </targets>

    <rules>
        <logger name="*" minlevel="Info" writeTo="console" />
    </rules>
</nlog>

通过创建一个简单的Logger类,您的示例对我起作用了(使用上面的配置文件)

class MyLoggerClass
{
    public static Logger Logger = LogManager.GetCurrentClassLogger();
}

class MyClass
{
    static void Main(string[] args)
    {

        Console.Write("lol");
        MyLoggerClass.Logger.Debug("Debug test...");
        MyLoggerClass.Logger.Error("Debug test...");
        MyLoggerClass.Logger.Fatal("Debug test...");
        MyLoggerClass.Logger.Info("Debug test...");
        MyLoggerClass.Logger.Trace("Debug test...");
        MyLoggerClass.Logger.Warn("Debug test...");
    }
}

或者您可以直接在您的类中使用 Logger,如下所示:

class MyClass
{
    private static Logger Logger = LogManager.GetCurrentClassLogger();
    static void Main(string[] args)
    {
        Console.Write("lol");
        Logger.Debug("Debug test...");
        Logger.Error("Debug test...");
        Logger.Fatal("Debug test...");
        Logger.Info("Debug test...");
        Logger.Trace("Debug test...");
        Logger.Warn("Debug test...");
    }
}

log.txt的输出内容:

2017-02-26 16:13:44.8388|ERROR|NLogTest.Program|Debug test...
2017-02-26 16:13:44.8856|FATAL|NLogTest.Program|Debug test...
2017-02-26 16:13:44.8856|INFO|NLogTest.Program|Debug test...
2017-02-26 16:13:44.8971|WARN|NLogTest.Program|Debug test...

3
我仍然一无所获。 - ed22
4
请确保将 NLog.config 复制到生成的输出目录中。 - ed22
@ed22,你是救星。我不知道为什么这个日志没有显示,因为我没有复制到输出目录。哈哈,谢谢啊。 - lwin

2

basedir是相对于.exe的路径

在这种情况下,它很可能位于bin\debug\assets\logging\log.txt中。


2
您需要将数据发送到控制台。按照Nlog控制台目标git hub示例中所写的,添加另一个将数据发送到控制台的目标。我认为您还应该将该目标放在ruleslogger(在writeTo中与File一起)中。

1
如果您仍然遇到问题,请查看此内容。我复制并粘贴了所有必要的代码和配置,但直到我做了这个操作才起作用。 NLog在IIS上无法工作 将"Copy to Output Directory"设置为"始终复制"。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接