Prevent log4net to send duplicate issues via SMTP

独自空忆成欢 提交于 2019-11-30 17:40:55

Maybe this is sufficient for your requirements:

it basically limits the number of emails that are sent in a given time span. I think it should be quite easy to customize this to your needs. I did something similar that even discards messages within a certain time span:

public class SmtpThrottlingAppender : SmtpAppender
{
    private DateTime lastFlush = DateTime.MinValue;
    private TimeSpan flushInterval = new TimeSpan(0, 5, 0);

    public TimeSpan FlushInterval
    {
        get { return this.flushInterval; }
        set { this.flushInterval = value; }
    }

    protected override void SendBuffer(LoggingEvent[] events)
    {
        if (DateTime.Now - this.lastFlush > this.flushInterval)
        {
            base.SendBuffer(events);
            this.lastFlush = DateTime.Now;
        } 
    }
}

The flush interval can be configured like normal settings of other appenders:

<flushInterval value="01:00:00" />

You can also use a plain SmtpAppender with a log4net.Core.TimeEvaluator as the Evaluator.

Suppose we have an interval of 5 minutes, and events at 00:00, 00:01 and 01:00.

  • Stefan Egli's SmtpThrottlingAppender will send emails at 00:00 (event 1) and 01:00 (events 2 and 3).
  • An SmtpAppender with a TimeEvaluator will send emails at 00:05 (events 1 and 2) and 01:05 (event 3).

Which one you want depends on whether you're more bothered by the guaranteed delay or the potentially large delay.

I attempted the combine the SmptThrottlingAppender with a TimeEvaluator, but couldn't get the behaviour I wanted. I'm beginning to suspect that I should be writing a new ITriggeringEventEvaluator, not a new IAppender.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!