NLog:记录序列化为JSON的对象 [英] NLog: logging an object serialized to JSON

查看:853
本文介绍了NLog:记录序列化为JSON的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有NLog配置的.Net项目,该项目使我可以生成JSON格式的日志文件.它适用于简单的文本消息.现在,我需要记录一些已经序列化为JSON的任意对象.当我将这些JSON字符串记录为日志消息时,NLog会将文本放在引号中,然后转义内部JSON语法.这使得这样的输出不可用.到目前为止,我还没有找到一个NLog功能或布局设置,该功能或布局设置只是将我的JSON字符串作为文字转储,而没有引号和转义字符.我想念什么吗?

I have .Net project with NLog configuration which allows me to produce JSON-formatted log file. It works fine with simple text messages. Now, I need to log a number of arbitrary objects already serialized to JSON. When I log those JSON strings as log messages, NLog puts the text in quotes and subsequently escapes inner JSON syntax. This renders such output unusable. So far I have failed to find an NLog feature or layout setting that would simply dump my JSON string as a literal, without quotation marks and escape characters. Am I missing something?

示例.目前,我的日志条目如下所示:]

Example. Currently my log entries look like:]

{ "dateTime": "2017-06-07 11:50:55.7324", "level": "DEBUG", "message": "\"description\": \"blah-blah\", \"Request\": { \"Request URL\":\/somepagepage\/}, \"Content\": { \"Form\": { ... } , \"Body\": \"Blah\" } ", "utcDateTime": "2017-06-05 06:10:34.1411" }

相反,我需要使它们看起来像:

Instead, I need to make them to look like:

{ "dateTime": "2017-06-07 11:50:55.7324", "level": "DEBUG", "message":
 { "description": "blah-blah", "Request": { "Request URL":/somepagepage/, "Content": { "Form": {...}, "Body": "Blah" }  }, "utcDateTime": "2017-06-05 06:10:34.1411" }

NLog.config中的相关部分:

Relevant section from NLog.config:

 <layout xsi:type="JsonLayout">
   <attribute name="dateTime" layout="${longdate}" />
   <attribute name="level" layout="${level:upperCase=true}"/>
   <attribute name="message" layout="${message}" /> 
   <attribute name="utcDateTime" layout="${longdate:universalTime=true}" />
 </layout>

最终,我希望看到一个嵌套在消息"中而不是引用版本的带有JSON的日志条目.

Ultimately, I would like to see a log entry with JSON nested inside "message", and not a quoted version of it.

推荐答案

按照上面@Rolf Kristensen的评论.本质上,参数encode ="false"允许记录未加引号的JSON:

As per @Rolf Kristensen's commentary above. Essentially, parameter encode="false" allows to log unquoted JSON:

  <attribute name="message" layout="${message}" encode="false" /> 

纯文本现在也没有报价,但是可以通过自定义布局渲染器来处理,该渲染器可以从JSON识别纯文本.

Plain text also comes out unquoted now, but this can be dealt with by a custom layout renderer that can tell plain text from JSON.

这篇关于NLog:记录序列化为JSON的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆