NLog中如何将Exception.Data像事件属性一样渲染为原生JSON
NLog JsonLayout输出Exception.Data为原生JSON对象方案
NLog 4.7及以上版本原生支持该需求,无需自定义代码、无需手动枚举Exception.Data的字典键。
方式1:极简配置(自动输出标准异常结构)
直接在根JsonLayout开启异常包含开关,指定异常数据的序列化格式为JSON即可:
<layout type="JsonLayout" includeException="true" exceptionDataFormatting="Json" maxRecursionLimit="10"> <!-- 其余原有配置,比如properties字段 --> <attribute name="properties" encode="false" > <layout type='JsonLayout' includeAllProperties="true" maxRecursionLimit="10"/> </attribute> </layout>
该配置会自动输出异常的type、message、stacktrace、data等字段,其中data字段自动序列化为原生嵌套JSON对象,不会转义为字符串。
方式2:自定义异常字段配置
如果需要自定义异常输出的字段(比如只保留需要的字段,去掉HResult、TargetSite等冗余内容),可以通过嵌套JsonLayout实现:
<layout type="JsonLayout"> <!-- 自定义exception字段结构 --> <attribute name="exception" encode="false"> <layout type="JsonLayout"> <attribute name="type" layout="${exception:format=type}" /> <attribute name="message" layout="${exception:format=message}" /> <attribute name="stacktrace" layout="${exception:format=stacktrace}" /> <!-- 核心:自动遍历Exception.Data输出为嵌套对象 --> <attribute name="data" encode="false"> <layout type="JsonLayout" includeExceptionData="true" maxRecursionLimit="10" /> </attribute> </layout> </attribute> <!-- 原有properties配置保留 --> <attribute name="properties" encode="false" > <layout type='JsonLayout' includeAllProperties="true" maxRecursionLimit="10"/> </attribute> </layout>
配置注意事项
- 所有承载嵌套JsonLayout的attribute节点必须设置
encode="false",否则序列化后的JSON内容会被当做普通字符串转义,出现带反斜杠的字符串问题 maxRecursionLimit参数根据实际需求调整即可,支持Exception.Data中存储的嵌套对象、集合等复杂类型的序列化- 不要使用
${exception:format=data}作为data字段的布局,该配置默认调用ToString()方法,只会输出键值对拼接的平文本字符串;也不要直接用${exception:format=@}作为attribute的布局,该方法输出的是预序列化的JSON字符串,即使关闭编码也无法灵活自定义字段结构。
内容的提问来源于stack exchange,提问作者kwill
相关产品推荐
相关产品推荐

