为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
阿波罗的战车 2022-11-13 13:38:22
在 NLog 的 4.6 版本中添加了一些新特性。其中之一 - 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>测试 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>测试性能。用于测试的 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>
查看完整描述

1 回答

?
白猪掌柜的

TA贡献1893条经验 获得超10个赞

总结和阐述评论,


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


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


所以在这种情况下:


 <layout xsi:type="XmlLayout" indentXml="true" 

         maxRecursionLimit="10"

 ... />

请参阅XML 布局文档


查看完整回答
反对 回复 2022-11-13
  • 1 回答
  • 0 关注
  • 87 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号