Log4Net smtp appender only send email when error with full log(debug & info & error). Only when the application ends

前端 未结 3 1212
耶瑟儿~
耶瑟儿~ 2021-02-08 18:59

I am trying to configure a smtp appender in the log4net.config file that I have. The problem is that I have looked all over the internet and cannot find how to send an email whe

3条回答
  •  死守一世寂寞
    2021-02-08 19:01

    SmtpAppender cannot accomplish this on its own. So what I did was create another appender that to an appender of type MemoryAppender. I set a threshold on this logger to only include messages that should trigger the SmtpAppender, e.g. Error. We use this to later determine if we want to send the email which has more levels logged.

    We don't actually care about the messages in the MemoryAppender--we just care that it contains messages at the end. The messages we get via email actually come from the SmtpAppender.

    At the end of my program I check the memory appender to see if its GetEvents() contains any events. If so, I do not stop the SmtpAppender from running normally.

    Log4Net configs for both appenders:

    
        
        
        
    
    
        
        
         
        
            
        
        
        
            
        
          
            
    
    
    
      
      
      
    
    

    At the end of the app run this to disable the SmtpAppender if the ErrorHolder appender is empty:

    // trigger loggers if errors occurred:
    var memoryAppender = ((Hierarchy)LogManager.GetRepository())
        .Root.Appenders.OfType().FirstOrDefault();
    
    if (memoryAppender != null && memoryAppender.GetEvents().Length == 0)
    {
        // there was no error so don't email anything
        var smtpAppender = ((Hierarchy)LogManager.GetRepository())
            .Root.Appenders.OfType().FirstOrDefault();
    
        if (smtpAppender != null)
        {
            smtpAppender.Threshold = Level.Off;
            smtpAppender.ActivateOptions();
        }
    }
    

提交回复
热议问题