Search code examples
c#loggingnlog.net-4.8

NLog ignores the config file


For some reason, the NLog ignores the config file. I have an NLog.config file with Build Action: Content and Copy to Output Directory: Copy always.

Here is the config file content:

<?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="default" xsi:type="Console" />
    <target name="dump" xsi:type="File" filename="./dump.log">
      <layout xsi:type="JsonLayout" includeAllProperties="true">
      </layout>
    </target>
  </targets>

  <!-- rules to map from logger name to target -->
  <rules>
    <logger name="DumpLogger" minlevel="Trace" writeTo="dump" />
    <logger name="*" minlevel="Trace" writeTo="dump" />
  </rules>
</nlog>

I have this code:

var logger = LogManager.GetLogger("DumpLogger");
logger.Trace("Try Trace"); // ignored
logger.Info("Try Info"); // writes to console

I also tried to add an explicit NLog config before the GetLogger call:

LogManager.LoadConfiguration(@"C:\Projects\ConsoleApplication1\bin\x64\Debug\NLog.config");

But I get the same result.

Why NLog ignore my config file?


Solution

  • With some correction, the code you provided work pretty well:

    <?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="default" xsi:type="Console" />
        <target name="dump" xsi:type="File" filename="./dump.log">
          <layout xsi:type="JsonLayout" includeAllProperties="true">
            <!-- Add something in the json entries -->
            <attribute name="timestamp" layout="${date:universalTime=true:format=yyyy-MM-dd HH\:mm\:ss,fff}" />
            <attribute name="level" layout="${level}"/>
            <attribute name="message" layout="${message}" />
          </layout>
        </target>
      </targets>
    
      <!-- rules to map from logger name to target -->
      <rules>
        <logger name="DumpLogger" minlevel="Trace" writeTo="dump" />
        <!-- Use default here instead of dump -->
        <logger name="*" minlevel="Trace" writeTo="default" />
      </rules>
    </nlog>
    

    And:

    using NLog;
    
    namespace NLogTest
    {
        class Program
        {
            static void Main(string[] args)
            {
                var logger = LogManager.GetLogger("DumpLogger");
                logger.Trace("Try Trace");
                logger.Info("Try Info");
    
            }
        }
    }
    

    Content of dump.log:

    { "timestamp": "2021-10-21 11:26:34,672", "level": "Trace", "message": "Try Trace" }
    { "timestamp": "2021-10-21 11:26:34,697", "level": "Info", "message": "Try Info" }
    

    Console output:

    2021-10-21 13:13:27.8513|TRACE|DumpLogger|Try Trace
    2021-10-21 13:13:27.8815|INFO|DumpLogger|Try Info