log4net.ext.json - 自定义图章

时间:2015-09-17 00:22:38

标签: json log4net

我试图用带标记的事件编写JSON日志(目前只是一个ValueStamp,每个日志条目需要一个唯一的guid)。我按照指南here进行操作,我的log4net.config看起来像是

<log4net>
  <root>
    <loggerFactory type='log4net.Util.Stamps.StampingLoggerFactory, log4net.Ext.Json'>
      <stamp type='log4net.Util.Stamps.ValueStamp, log4net.Ext.Json'>
        <name>stamp</name>
        <value>MyValueHere</value>
      </stamp>
    </loggerFactory>

    <level value="ALL" />
    <appender-ref ref="LogFileAppender" />
    <appender-ref ref="JsonFileAppender" />
  </root>
  <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender" >
    ...      
  </appender>
  <appender name="JsonFileAppender" type="log4net.Appender.RollingFileAppender" >
    <param name="File" value="log-file.json" />
    <param name="AppendToFile" value="true" />
    <rollingStyle value="Size" />
    <maxSizeRollBackups value="10" />
    <maximumFileSize value="10MB" />
    <staticLogFileName value="true" />
    <layout type="log4net.Layout.SerializedLayout, log4net.Ext.Json">
      <decorator type="log4net.Layout.Decorators.StandardTypesFlatDecorator, log4net.Ext.Json" />
      <default /> 
      <!--explicit default members-->
      <member value="Stamp:stamp" />
    </layout>
  </appender>
</log4net>

不幸的是,我在日志消息中看到的只有

{"date":"2015-09-16T17:19:13.7833747-07:00","level":"INFO","appname":"MyApp.exe","logger":"MyApp.Program","thread":"6","ndc":"(null)","message":"Processed request successfully","Stamp":"stamp"}

所以我的问题是: 如何让Json布局向我展示&#34; MyValueHere&#34;邮票?

1 个答案:

答案 0 :(得分:3)

我终于明白了 - 我需要将loggerFactory放在根元素之前(和之外)。工作的log4net.config如下所示:

<log4net>
  <loggerFactory type="log4net.Util.Stamps.StampingLoggerFactory, log4net.Ext.Json">
    <stamp type="log4net.Util.Stamps.ValueStamp, log4net.Ext.Json">
        <name>stamp</name>
        <value>MyValueHere</value>        
    </stamp>
  </loggerFactory>

  <root>
    <level value="INFO" />
    <appender-ref ref="JsonFileAppender" />
  </root>

  <appender name="JsonFileAppender" type="log4net.Appender.RollingFileAppender" >
    <param name="File" value="log-file.json" />
    <param name="AppendToFile" value="true" />
    <rollingStyle value="Size" />
    <maxSizeRollBackups value="10" />
    <maximumFileSize value="10MB" />
    <staticLogFileName value="true" />
    <layout type="log4net.Layout.SerializedLayout, log4net.Ext.Json">
      <decorator type="log4net.Layout.Decorators.StandardTypesFlatDecorator, log4net.Ext.Json" />
      <member value="Stamp:stamp"/>
      <default />
    </layout>
  </appender>
</log4net>

使用此配置,每个日志条目都带有“MyValueHere”标记。