2

我需要使用 log4net 登录到多个目标(loggly、控制台、文件)。对于 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;
    }

应用程序配置

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

现在控制台和 FileAppender 正在记录 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]}

我希望这些附加程序仅记录消息本身(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

我怎样才能做到这一点?非常感谢 :)

4

1 回答 1

0

如果您为消息对象创建自己的类型(而不是使用动态对象)并覆盖该ToString()方法会发生什么?我怀疑,LogglyAppender会呈现图表,而常规PatternLayout会诉诸ToString(). 这个我没试过,仅供参考。您也许可以将其子类化,ExpandoObject以免失去这种动态性。

于 2018-05-06T17:20:28.077 回答