Search code examples
c#newlinenlog

NLog: replace \r\n with actual line break in file


How to make NLog insert actual line breaks to the target file instead of \r\n in ${message}?

I am using a config file to configure NLog as follows:

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

  <variable name="logDirectory" value="Logs" />
  
    <targets>
        <target name="txtFile" xsi:type="File" fileName="${logDirectory}/${shortdate}.txt" />
      
      <target name="jsonFile" xsi:type="File" fileName="${logDirectory}/${shortdate}.json" >
        <layout type="JsonLayout" IndentJson="true">
          <attribute name="time" layout="${date:format=yyyy-MM-dd HH\:mm\:ss}" />                          
          <attribute name="message" layout="${message:raw=true}" />
          <attribute name="exception" layout="${exception}" />
        </layout>
      </target>
    </targets>

    <rules>
      <logger name="*" minlevel="Error" writeTo="jsonFile"  />        
    </rules>
</nlog>

and I am using NLog in a C# application. The logged messages contain Environment.NewLine characters which are currently replaced by \r\n in the log file.

public class SomeClass
{
   static readonly Logger logger = LogManager.GetCurrentClassLogger();
   
   public void DoStuff()
   {
        try
        {
         // ... some code
        }
        catch(Exception n)
        {
          string msg = "Failed to do stuff" + Environment.NewLine + 
          "Try again later";
          logger.Error(n, msg);
        }
   }
}

Solution

  • When using the NLog JsonLayout, then it will encode newlines as the chars \r\n, as required by the JSON-format.

    If correct JSON output is not relevant, then you can use the option encode="false":

    <layout xsi:type="JsonLayout" IndentJson="true">
       <attribute name="message" layout="${message:raw=true}" encode="false" />
    </layout>
    

    Alternative stop using JsonLayout.