Collate output in Python logging MemoryHandler with SMTPHandler

前端 未结 5 1928
傲寒
傲寒 2020-12-01 00:14

I have the logging module MemoryHandler set up to queue debug and error messages for the SMTPHandler target. What I want is for an email to be sent when the process errors t

5条回答
  •  广开言路
    2020-12-01 00:51

    If you are using django - here is simple buffering handler, which will use standard django email methods:

    import logging
    
    from django.conf import settings
    from django.core.mail import EmailMessage
    
    
    class DjangoBufferingSMTPHandler(logging.handlers.BufferingHandler):
        def __init__(self, capacity, toaddrs=None, subject=None):
            logging.handlers.BufferingHandler.__init__(self, capacity)
    
            if toaddrs:
                self.toaddrs = toaddrs
            else:
                # Send messages to site administrators by default
                self.toaddrs = zip(*settings.ADMINS)[-1]
    
            if subject:
                self.subject = subject
            else:
                self.subject = 'logging'
    
        def flush(self):
            if len(self.buffer) == 0:
                return
    
            try:
                msg = "\r\n".join(map(self.format, self.buffer))
                emsg = EmailMessage(self.subject, msg, to=self.toaddrs)
                emsg.send()
            except Exception:
                # handleError() will print exception info to stderr if logging.raiseExceptions is True
                self.handleError(record=None)
            self.buffer = []
    

    In django settings.py you will need to configure email and logging like this:

    EMAIL_USE_TLS = True
    EMAIL_PORT = 25  
    EMAIL_HOST = ''  # example: 'smtp.yandex.ru'
    EMAIL_HOST_USER = ''  # example: 'user@yandex.ru'
    EMAIL_HOST_PASSWORD = ''
    DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
    SERVER_EMAIL = EMAIL_HOST_USER
    
    LOGGING = {
        'handlers': {
            ...
            'mail_buffer': {
                'level': 'WARN',
                'capacity': 9999,
                'class': 'utils.logging.DjangoBufferingSMTPHandler',
                # optional: 
                # 'toaddrs': 'admin@host.com'
                # 'subject': 'log messages'
            }
        },
        ...
    }
    

提交回复
热议问题