将NLog属性布局为JSON?

时间:2017-05-18 12:46:25

标签: logging serialization nlog

我试图找出如何将LogEventInfo对象中的所有属性记录到JSON格式的字符串。根据{{​​3}},我尝试做类似的事情:

<target xsi:type="ColoredConsole" name="coloredConsole">
  <layout xsi:type="JsonLayout">
    <attribute name="timestamp" layout="${longdate}"/>
    <attribute name="level" layout="${level:uppercase=true}"/>
    <attribute name="exception" layout="${onexception:${exception:format=tostring}}" />
    <attribute name="properties" encode="false">
      <layout type="JsonLayout">
        <attribute name="properties" layout="${all-event-properties}" />
      </layout>
    </attribute>
  </layout>
</target>

...但遗憾的是,我的属性包含复杂对象(我有两个属性,其名称为“properties”和“tags”,其中“properties”为IDictionary<string, object>,“tags”为{{ 1 {}在IList<string>属性中),根本不进行序列化。我最终得到了类似的东西:

LogEventInfo.Properties

我期待(并希望)一个序列化的JSON字典,它会给我一个日志消息的上下文,但显然这不是我得到的。

如何正确序列化{ "timestamp": "2017-05-18 08:41:28.7730", "level": "INFO", "properties": { "properties": "properties=System.Collections.Generic.Dictionary`2[System.String,System.Object], tags=System.Collections.Generic.List`1[System.String]" } } 对象中的属性?

2 个答案:

答案 0 :(得分:4)

好吧,看起来NLog中有一个bug,所以我有点制作了自己的渲染器。这就是我做的。首先,我使用JSON.NET制作了一个扩展方法:

public static string ToJson(this object obj, bool format = false, string dateFormat = null)
{
    var settings = new JsonSerializerSettings
    {
        NullValueHandling = NullValueHandling.Ignore
    };

    if (!String.IsNullOrWhiteSpace(dateFormat))
    {
        settings.Converters = new List<JsonConverter>
        {
            new IsoDateTimeConverter {DateTimeFormat = dateFormat}
        };

        return JsonConvert.SerializeObject(obj, format ? Formatting.Indented : Formatting.None, settings);
    }

    return JsonConvert.SerializeObject(obj, format ? Formatting.Indented : Formatting.None, settings);
}

...接下来,我创建了一个这样的LayoutRenderer:

[LayoutRenderer("json-event-properties")]
public class JsonEventPropertiesLayoutRenderer : LayoutRenderer
{
    /// <summary>
    /// Renders the specified environmental information and appends it to the specified <see cref="T:System.Text.StringBuilder" />.
    /// </summary>
    /// <param name="builder">The <see cref="T:System.Text.StringBuilder" /> to append the rendered data to.</param>
    /// <param name="logEvent">Logging event.</param>
    protected override void Append(StringBuilder builder, LogEventInfo logEvent) {
        if (logEvent.Properties == null || logEvent.Properties.Count == 0)
            return;
        var serialized = logEvent.Properties.ToJson();
        builder.Append(serialized);
    }
}

在我的应用程序中,启动时,我注册了我的LayoutRenderer

LayoutRenderer.Register<JsonEventPropertiesLayoutRenderer>("json-event-properties");

...最后,我像这样配置了NLog目标:

    <layout xsi:type="JsonLayout">
    <attribute name="timestamp" layout="${longdate}"/>
    <attribute name="level" layout="${level:uppercase=true}"/>
    <attribute name="exception" layout="${onexception:${exception:format=tostring}}" />
    <attribute name="message" layout="${message}" />
    <attribute name="properties" layout="${json-event-properties}" encode="false"/>
  </layout>

像这样运行,JSON格式正确,我可以访问LogEventInfo对象中的属性。

答案 1 :(得分:4)

在这里使用NLog 4.5.1。

使用此配置:

 <target xsi:type="File" name="jsonFile2" fileName="c:\temp\nlog-json-nested-${shortdate}.log">
     <layout type="JsonLayout">
         <attribute name="time" layout="${longdate}" />
         <attribute name="level" layout="${level}" />
         <attribute name="message" layout="${message}" />
         <attribute name="eventProperties" encode="false" >
             <layout type='JsonLayout' includeAllProperties="true"  maxRecursionLimit="20"/>
         </attribute>
     </layout>
 </target>

此代码:

var nestedData = new
{
    A = "a value",
    B = "b value",
    Nested = new
    {
        A = "nested a value",
        B = "nested b value",
    },
    Ints = new Collection<int> { 1, 2, 3},
    Dictionary = new Dictionary<string, object>
    {
        {"nested", new { X= 'x', y = 'y' }},
        { "awesome", "nlog"}
    }
};
LogEventInfo eventInfo = new LogEventInfo
{
    Level = LogLevel.Info,
    Properties = { {"nestedData", nestedData } }
};
logger.Log(eventInfo);

输出:

{  
   "time":"2018-04-05 18:08:01.0813",
   "level":"INFO",
   "eventProperties":{  
      "nestedData":{  
         "A":"a value",
         "B":"b value",
         "Nested":{  
            "A":"nested a value",
            "B":"nested b value"
         },
         "Ints":[  
            1,
            2,
            3
         ],
         "Dictionary":{  
            "nested":{  
               "X":"x",
               "y":"y"
            },
            "awesome":"nlog"
         }
      }
   }
}

实际上,它打印出丑陋的单行版本。

请参阅具有结构化日志on the NLog wiki

的嵌套JSON

注意maxRecursionLimit设置。默认情况下它是0,意思是&#34;没有对象反射&#34;,这意味着你将获得事件属性的ToString()表示。