Layout NLog properties as JSON?

Viewed 9626

I am trying to figure out how to log all the properties in a LogEventInfo object to a JSON-formatted string. Per the issue on github, I tried to do something like this:

<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>

... but unfortunately, my properties contain complex objects (I have two properties with the names of "properties" and "tags", where "properties" is a IDictionary<string, object> and "tags" is an IList<string> in the LogEventInfo.Properties property) that simply do not serialize. I end up with something resembling this:

{ "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]" } }

I was expecting (and hoping for) a serialized JSON dictionary that would give me the context of the log message, but clearly that is not what I am getting.

How can I properly serialize the properties in my LogEventInfo object?

2 Answers
Related