英文:
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="false"
:
<layout xsi:type="JsonLayout" IndentJson="true">
<attribute name="message" layout="${message:raw=true}" encode="false" />
</layout>
Alternative stop using JsonLayout.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论