Log4net,消除重复的消息

时间:2017-01-16 10:55:58

标签: log4net-configuration

有没有选项来设置log4net以消除重复的消息?我有一个循环工作的应用程序...有一个infinate while循环。如果发生任何错误(例如数据库不可访问),则会在每个循环中一次又一次地记录相同的消息。我只需要记录一次消息。

1 个答案:

答案 0 :(得分:1)

我已经实现了log4net过滤器,以在指定的时间间隔内消除相同的消息。

班级:

public class DuplicityFilter : FilterSkeleton
{
    private String lastMessage = null;
    private List<Tuple<DateTime, String>> lastMessages = new List<Tuple<DateTime,string>>();

    private Int32 _timeWindow = 0;
    public Int32 timeWindow
    {
        get { return _timeWindow; }
        set { _timeWindow = value; }
    }

    public Boolean _lastOnly = false;
    public Boolean lastOnly
    {
        get { return _lastOnly; }
        set { _lastOnly = value; }
    }

    public override FilterDecision Decide(log4net.Core.LoggingEvent loggingEvent)
    {
        if (_lastOnly)
        {
            if (lastMessage == loggingEvent.RenderedMessage)
            {
                return FilterDecision.Deny;
            }
            else
            {
                lastMessage = loggingEvent.RenderedMessage;
                return FilterDecision.Accept;
            }
        }
        else
        {
            if (_timeWindow <= 0)
                return FilterDecision.Accept;

            // Removes old messages
            lastMessages.RemoveAll(m => m.Item1 < DateTime.Now.AddSeconds(0 - _timeWindow));

            if (!lastMessages.Any(m => m.Item2 == loggingEvent.RenderedMessage))
            {
                lastMessages.Add(new Tuple<DateTime, string>(loggingEvent.TimeStamp, loggingEvent.RenderedMessage));
                return FilterDecision.Accept;
            }
            else
            {
                return FilterDecision.Deny;
            }
        }
    }

XML定义:

  <filter type="your.namespace.here.DuplicityFilter">
    <timeWindow value="900" /> <!-- 15min -->
    <lastOnly value="false" />
  </filter>