NLog:在文件中将\r\n替换为实际换行符

huangapple go评论65阅读模式
英文:

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

如何使NLog在目标文件中插入实际的换行符而不是${message}中的\r\n

英文:

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);
        }
   }
}

答案1

得分: 1

使用NLog的JsonLayout时,它会将换行符编码为字符\r\n,这是JSON格式所需的。

如果不需要正确的JSON输出,那么可以使用选项encode="false"

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

或者,可以考虑停止使用JsonLayout。

英文:

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=&quot;false&quot;:

&lt;layout xsi:type=&quot;JsonLayout&quot; IndentJson=&quot;true&quot;&gt;
   &lt;attribute name=&quot;message&quot; layout=&quot;${message:raw=true}&quot; encode=&quot;false&quot; /&gt;
&lt;/layout&gt;

Alternative stop using JsonLayout.

huangapple
  • 本文由 发表于 2023年6月8日 18:24:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76430894.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定