Search code examples
pythonexceptionsmtplogging

Is there a way how to configure SMTPHandler in Python to do more advanced stuff?


I am using standard SMTPHandler logger to catch my Python exceptions. Is there a way how to put exception name into the subject of the mail? It would be much better than with static subject, because Gmail (and not only Gmail) can group conversations according to subject and so it could group it according to the type of error.

E.g., if 50 completely the same errors occure + 1 different, I'd see two conversations in my inbox instead of 1 group consisting 51 emails, where I can very easily overlook the single different one.

Also, is there a way how to prevent sending still the same errors? E. g. somehow define my own function deciding if email is to be sent or not. The function would take some basic info in params so it could decide (e.g. cache & see if such an issue was already sent).

I browsed the docs, but I can't find anything like that. It seems to be very simple. If SMTPHandler can't do this, what would be the best and still simple alternative? Any neat libraries?

Thank you!


Solution

  • You simply need to create your own subclass of SMTPHandler.

    For your first request: You just need to override the getSubject(record) method. As to what you can put in the subject, look at help(Formatter) after importing Formatter from logging.

    For your second request: You must override the emit(record) method. Inspect the record and make your own decision about whether it should be send. If so then just call the super(SMTPHandler,self).emit(record) method.

    class MySMTPHandler(SMTPHandler):
    
        def getSubject(self, record):
            return "My Error Format from the record dict"
    
        def emit(self, record):
            #check for record in self.already_send or something
            if sendit:
               super(MySMTPHandler,self).emit(record)