在log4net.Ext.Json中覆盖SerializedLayout的默认序列化程序

时间:2015-05-11 23:50:46

标签: json log4net

我正在尝试log4net.Ext.Json来序列化一些JSON。我希望输出看起来像这样:

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

其中objectField1objectField2来自LoggingEvent上的消息对象,而time来自某些log4net模式,如下所示:

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

有没有办法通过配置向邮件对象添加属性?我尝试了以下无济于事:

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

1 个答案:

答案 0 :(得分:1)

您可以通过记录这样的结构化对象来实现这一目标:

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

仅使用messageobject成员。

或者,看看MultipleArrangement是否会让你到达某个地方:

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

最有可能明确使用:

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