2

I'm trying to log4net.Ext.Json to serialize some JSON. I want the output to look like this:

{
  "data": {
    "objectField1": "foo",
    "objectField2": "bar",
    "time": "2015-05-11T12:35:00.05215Z"
  }
}

where objectField1 and objectField2 come from the message object on the LoggingEvent and time comes from some log4net pattern like this:

%utcdate{yyyy-HH-MM-dd}T%utcdate{HH:mm:ss.fffff}Z

Is there a way to add properties to the message object via configuration? I tried the following to no avail:

  <layout type="log4net.Layout.SerializedLayout, log4net.Ext.Json">
    <member value="data:messageobject" />
    <arrangement value="data:messageobject=time|%utcdate{yyyy-HH-MM-dd}T%utcdate{HH:mm:ss.fffff}Z" />
    <renderer type="log4net.ObjectRenderer.JsonObjectRenderer, log4net.Ext.Json">
      <!-- Please ignore the custom serializer factory setting below -->
      <factory type="log4net.Util.Serializer.JsonDotNetSerializer, log4net.Ext.Json.Serializers" />
    </renderer>
  </layout>
smarts
  • 48
  • 9

1 Answers1

1

You can achieve that by either logging such a structured object:

        log.Info(new { data = new { objectField1 = "foo", objectField2 = "bar" } });

And using the messageobject member only.

Or, see if the MultipleArrangement will get you somewhere:

<member value="data=objectField1\;objectField2\;time" />

It can most likely be used explicitly:

<layout type="log4net.Layout.SerializedLayout, log4net.Ext.Json">
 <arrangement value="data" type="log4net.Layout.Arrangements.MultipleArrangement, log4net.Ext.Json">
    <arrangement value="objectField1" type="..." />
    <arrangement value="objectField2" type="..." />
 </arrangement>
</layout>
Robert Cutajar
  • 3,181
  • 1
  • 30
  • 42
  • Solves the specific scenario, but doesn't quite answer the question. I don't want to configure every field from my message object. That is, I want all the fields from the message object & I don't want to have to update the logging configuration if I add new fields to it. However, I want those _plus_ some field (or fields) that are auto-generated by the logging framework. Is there a way to log all the message object fields (w/o configuring anything) **and** some extra auto-generated & formatted fields that come from the logging framework (which, of course, must be configured)? – smarts Nov 20 '16 at 19:28
  • Hi @smarts, the intention was not to create a transformer to allow you to declaratively shape and decorate objects. I think this is not a scope for this extention. Rather it is meant to capture any relevant information in a structured way so it can *later* be processed efficiently. I'd suggest if you need a very specific object structure to satisfy some further API down the line, you'd want a pre-processor to do that for you. – Robert Cutajar Nov 21 '16 at 10:36
  • `` is nice. Thanks, mate – Xin Jul 20 '17 at 06:15