如何使用缩进 xml 消息创建 NLog XmlLayout?

How to create NLog XmlLayout with indented xml message?

在4.6版本的NLog中增加了一些新特性。其中之一 - XMLLayout。有什么方法可以通过正确的缩进在 XMLLayout 目标中保存 xml 格式的消息吗?另一个问题是如何对分层 属性 值输出做同样的事情?

在我的配置和消息代码下方

<target name="xmlFile" xsi:type="File" fileName="my_log.xml" maxArchiveFiles="3" archiveNumbering="Sequence" archiveDateFormat="dd-mm-yyyy" archiveOldFileOnStartup="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <layout xsi:type="XmlLayout" indentXml="true" includeAllProperties="true" includeMdc="true">
    <attribute name="logger" layout="${logger}" />
    <attribute name="callsite" layout="${callsite}" />
    <attribute name="line" layout="${callsite-linenumber}" />
    <element name="message" value="${message}" />
    <element name="exception" value="${exception:format=toString}" />
  </layout>
</target>
  1. 正在测试 xml-文本。测试留言:
"<hello person=\"x\"><child>child value</child></hello>"

结果未缩进:

<logevent logger="Logs" callsite="WriteLogMessages.LogMessages" line="36">
  <message><hello person="x"><child>child value</child></hello></message>
</logevent>
  1. 测试属性。用于测试的 LogEventInfo:
var root = new Dictionary<string, object>();
var branches = new Dictionary<string, object>();
var leaf = new Dictionary<string, object>();
leaf["leaf"] = "This is the leaf";
branches["branches"] = leaf;
root["root"] = branches;

var logEvent = new LogEventInfo();
logEvent.Level = logLevel;
logEvent.Message = message;
logEvent.Properties["properties test"] = root;

结果:

<logevent logger="Logs" callsite="WriteLogMessages.LogMessages" line="26">
  <message>Test message.</message>
  <property key="properties test">
  <property key="root">
</property>

我知道可能需要在 Dictionary 上创建一个包装器并覆盖 ToString(),但结果转到问题编号 1。

预期结果:

<logevent logger="Logs" callsite="WriteLogMessages.LogMessages" line="36">
  <message>
    <hello person="x">
      <child>child value</child>
    </hello>
  </message>
</logevent>

对评论进行总结和阐述,

有一个错误,已在 NLog 4.6.1 中修复

默认情况下不序列化嵌套属性。你需要MaxRecursionLimit(例如10,默认为1),

所以在这种情况下:

 <layout xsi:type="XmlLayout" indentXml="true" 
         maxRecursionLimit="10"
 ... />

XML Layout docs