Console / FileAppender中的Log4net自定义json消息

时间:2017-06-12 14:30:16

标签: log4net log4net-appender loggly

我需要使用log4net登录到多个目标(loggly,console,file)。对于loggly,我需要登录JSON以获取一些元数据以查找日志。我正在通过将元数据添加到动态消息对象(例如主题)来改变消息对象。

public void Info(string message)
    {
        log.Info(GetLogObject(message));
    }

private object GetLogObject(string message, Exception ex = null)
    {
        dynamic obj = new ExpandoObject();

        obj.message = message;
        obj.exception = ex;
        obj.subject = _configuration.SubjectId;

        return obj;
    }

的app.config

<log4net>
<root>
  <level value="ALL" />
  <appender-ref ref="ConsoleAppender" />
  <appender-ref ref="RollingFileAppender" />
  <appender-ref ref="LogglyAppender" />
</root>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date - %message%newline" />
  </layout>
</appender>
<appender name="LogglyAppender" type="log4net.loggly.LogglyAppender, log4net-loggly">
  <rootUrl value="https://logs-01.loggly.com/" />
  <inputKey value="*" />
  <tag value="AppTag" />
  <filter type="log4net.Filter.LevelRangeFilter">
    <levelMin value="ERROR" />
    <levelMax value="FATAL" />
  </filter>
</appender>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
  <file value="Logs/rolling.log" />
  <appendToFile value="true" />
  <rollingStyle value="Size" />
  <maxSizeRollBackups value="5" />
  <maximumFileSize value="10MB" />
  <staticLogFileName value="true" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date %level - %message%newline" />
  </layout>
</appender>

现在,Console和FileAppenders正在将JSON记录为:

2017-06-12 15:28:10,236 INFO - {[message, Will collect every 1 Hours, 0 Minutes and 0 Seconds], [exception, ], [subject, 11111111-1111-1111-1111-111111111111]}
2017-06-12 15:28:10,271 INFO - {[message, Collection Round started at 12.06.2017 13:28:10], [exception, ], [subject, 11111111-1111-1111-1111-111111111111]}

我希望这些appender只是将消息本身(obj.message)记录下来:

2017-06-12 15:28:10,236 INFO - Will collect every 1 Hours, 0 Minutes and 0 Seconds
2017-06-12 15:28:10,271 INFO - Collection Round started at 12.06.2017 11:17:29

我该怎么做? 非常感谢你:))

1 个答案:

答案 0 :(得分:0)

如果您为消息对象创建了自己的类型(而不是使用动态对象)会发生什么情况,并覆盖ToString()方法?我怀疑,LogglyAppender会渲染图表,而常规PatternLayout会求助ToString()。我没试过这个,只是一个暗示。你可以将ExpandoObject子类化,而不是放松那种动态性。