简体   繁体   中英

Nlog log file is not created

I am trying to log exceptions in console application. I have done everything as always (and then it worked for me...):

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"
 xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
 autoReload="true"
 throwExceptions="false"
 internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
  <targets>
    <target name="LogFile" xsi:type="File"
               fileName="${basedir}/Log/${date:format=yyyyMMdd} myLog.txt"
               layout="${longdate}|${level:uppercase=true}|${message}|${exception}" />
  </targets>

  <rules>
    <logger name="*" minlevel="Debug" writeTo="LogFile" />
  </rules>
</nlog>
class Program
{
    private static Logger _log = LogManager.GetCurrentClassLogger();

    static void Main(string[] args)
    {
      _log.Error("test");
    }
}

For some mysterious reason file is never created nowhere on my computer. Any ideas why

In Visual Studio, check if your NLog.config file has this properties: Build Action: Content. Copy to Output Directory = Copy if newer

I am attaching a screen shot where you can see how it should appear. Sorry, it is in Spanish.

在此处输入图片说明

Your config looks valid, so that shouldn't be the issue.

Some things to check:

  1. Is you nlog.config in the correct directory? The best way to test is to copy the nlog.config to the directory with your .dll or .exe.

  2. Enable exceptions to be sure that errors are not captured by Nlog: throwExceptions="true"

  3. Check the internal log by setting internalLogLevel="Info" and check "c:\\temp\\nlog-internal.log"

A full tutorial to troubleshoot could be found on the NLog documentation .

Edit your NLog config, change your log file path like this,use ${shortdate} instead {date:format=yyyyMMdd} . Set name in rules and call it like in this sample.

 <?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 async="true">
    <targets>
      <target name="LogFile" xsi:type="File"
              fileName="${basedir}/Log/${shortdate}myLog.txt"
              layout="${longdate}|${level:uppercase=true}|${message}|${exception}" />
    </targets>

    <rules>
      <logger name="ErrorLog" minlevel="Trace" writeTo="LogFile" />
    </rules>
</nlog>

And your .cs

    class Program
{

    private Logger ErrorLogger = NLog.LogManager.GetLogger("ErrorLog");

    static void Main(string[] args)
    {
        ErrorLogger.Error("test");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM