有损记录,错误后也会收到一些消息?

时间:2011-06-08 08:01:29

标签: log4net log4net-configuration

log4net中的有损记录非常适合获取事件的详细信息,从而导致错误,并且性能损失最小。但是,在>错误之后记录一些消息以验证系统是否按计划处理它通常会很有趣。怎么办呢?

2 个答案:

答案 0 :(得分:5)

我会编写BufferingForwardAppender的自定义版本,它会在出错后记录可配置数量的邮件。基本上你会在错误一段时间后关闭“有损”并直接转发所有消息。

注意:确保在记录错误时appender立即刷新消息,因为您无法确定错误后是否会有其他消息。

答案 1 :(得分:4)

接受的答案就像一个魅力。为简化起见,我没有对错误后的消息数进行单独设置。而是在触发消息之后无损地发送一个完整缓冲区+ 1。代码:

public class BufferingForwardingAppenderEx : BufferingForwardingAppender
{
    /// <summary>
    /// If in lossy-mode, set the appender to non-lossy after a send has been done to get what happended after.
    /// </summary>
    public bool NonLossyAfterTriggered { get; set; }

    // Flag that tells if the appender is currently in non-lossy-override-mode
    private bool _nonLossyOverride = false;

    protected override void SendBuffer(global::log4net.Core.LoggingEvent[] events)
    {
        if (NonLossyAfterTriggered)
        {
            SetLossyAccordingToReasonForSending(events);
        }

        base.SendBuffer(events);
    }

    private void SetLossyAccordingToReasonForSending(LoggingEvent[] events)
    {
        if (_nonLossyOverride)
        {
            var newestEvent = events[events.Length - 1];
            var bufferIsSentBecauseItIsFull = !Evaluator.IsTriggeringEvent(newestEvent);

            if (bufferIsSentBecauseItIsFull)
            {
                _nonLossyOverride = false;
                Lossy = true;
            }
        }
        else
        {
            _nonLossyOverride = true;
            Lossy = false;
        }
    }
}

这是一个如何配置的例子:

<appender name="BufferingForwardingAppender"
          type="Foo.log4net.BufferingForwardingAppenderEx">
  <bufferSize value="3"/>
  <lossy value="true"/>
  <nonLossyAfterTriggered value="true" />
  <evaluator type="log4net.Core.LevelEvaluator">
    <threshold value="WARN"/>
  </evaluator>
  <appender-ref ref="ConsoleAppender"/>
</appender>

<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern
      value="%date{yyyy-MM-dd HH:mm:ss} %-5level %-13logger{1} %message%newline"/>
  </layout>
</appender>

<root>
  <level value="DEBUG"/>
  <appender-ref ref="BufferingForwardingAppender"/>
</root>

使用此配置时,单独的警告(或更糟)会以2开头,然后是4条消息。