Log4net, eliminate duplicate messages

后端 未结 1 1083
情话喂你
情话喂你 2020-12-22 01:38

is there any option to setup log4net to eliminate duplicate messages? I have an application which works in cycles...there is an infinate while cycle. If any error occure (fo

相关标签:
1条回答
  • 2020-12-22 02:27

    I have implemented log4net filter to eliminate same messages during specified time interval.

    The class:

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

    And the XML definition:

      <filter type="your.namespace.here.DuplicityFilter">
        <timeWindow value="900" /> <!-- 15min -->
        <lastOnly value="false" />
      </filter>
    
    0 讨论(0)
提交回复
热议问题