.netlogging-application-block

How to configure EmailTraceListener to avoid over-flooded mailbox (on mass problem)?


How to configure EmailTraceListener to avoid over-flooded mailbox (on mass problem)?

Is it possible to setup a maximum for messages sent (per hour/per day) using logging applicaiton block configuration?

P.S. I have done it already with some conditions before calling WriteLog, but would like to move all this stuff to the configuration...


Solution

  • OK. I wrote this solution, and for me it is enough (max 200 per day):

    public class MyEmailTraceListener : EmailTraceListener
    {
        public const int MAXPER24HOURS = 200;
        public static int counter =0;
        public static DateTime counterReStarted = DateTime.Today;
    
    
        private static bool CanLog()
        {
            bool returnValue = false;
            DateTime today = DateTime.Today;
            if (counter < MAXPER24HOURS)
            {
                counter++;
                returnValue=true;
            }
            else if (today>counterReStarted)
            {
                counter = 0;
                counterReStarted = today;
                returnValue = true;
            }
            return returnValue;
        }
    
    
        public MyEmailTraceListener(string toAddress, string fromAddress, string subjectLineStarter, string subjectLineEnder, string smtpServer,  int id, ILogFormatter formatter)
            :base(toAddress,        fromAddress,         subjectLineStarter,       subjectLineEnder, smtpServer, id, formatter)
        {
        }
    
        public MyEmailTraceListener()
        {
        }
    
        public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data)
        {
            if (CanLog())
                base.TraceData(eventCache, source, eventType, id, data);
        } 
    }
    
    public class MyTraceListenerAssembler : EmailTraceListenerAssembler 
    {
        public override TraceListener Assemble(IBuilderContext context, TraceListenerData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache)
        {
            MyEmailTraceListenerData data = (MyEmailTraceListenerData)objectConfiguration;
            return new MyEmailTraceListener(data.ToAddress, data.FromAddress, data.SubjectLineStarter, data.SubjectLineEnder, data.SmtpServer, data.SmtpPort, base.GetFormatter(context, data.Formatter, configurationSource, reflectionCache));
        }
    }
    
    [Assembler(typeof(MyTraceListenerAssembler))]
    public class MyEmailTraceListenerData : EmailTraceListenerData
    {
    }