首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Throttle smtphandler电子邮件

Throttle smtphandler电子邮件
EN

Stack Overflow用户
提问于 2014-12-02 09:06:26
回答 2查看 853关注 0票数 2

我想使用Python的记录器smtphandler来发送有关错误之类的电子邮件。我也不想让我的收件箱因为同一个bug被成千上万的电子邮件淹没。

有没有办法限制电子邮件的发送量?理想情况下,如果它一直捕捉到相同的异常,就减少发送的电子邮件数量。

EN

回答 2

Stack Overflow用户

发布于 2014-12-10 11:37:29

我最终为SMTPHandler制作了自己的包装器。初稿并不完美。处理程序的多个实例将分别限制复制。可以将self.logged存储在redis中,使其成为共享资源。

唯一需要设置的额外参数是intervals,它是分钟列表(Int)。假设将0 10 30传递给intervals。它会说现在就发送电子邮件。后续的复制将被忽略,直到经过10分钟之后。则随后的复制将被忽略,直到30分钟之后。在那之后,它就不会发送任何电子邮件了。

如果您想要更改被视为复制日志的内容,请根据您的要求修改_record_type。

代码语言:javascript
复制
import logging.handlers
import datetime


class SMTPHandler(logging.handlers.SMTPHandler):
    """
    Custom SMTPHandler for the logger.

    You specify the intervals to which emails will be sent.  At most the number
    of emails that will be sent will be equal to the number of intervals set.
    """

    def __init__(self, mailhost, fromaddr, toaddrs, subject, intervals,
                 credentials=None, secure=None, timeout=5.0):
        super(SMTPHandler, self).__init__(mailhost, fromaddr, toaddrs, subject,
                                          credentials, secure, timeout)
        self.logged = {}
        self.init_date = datetime.datetime.now()
        self.intervals = self._make_intervals(intervals)

    def _make_intervals(self, intervals):
        return [datetime.timedelta(minutes=i) for i in intervals]

    def _record_type(self, record):
        """Make key from LogRecord"""
        type = record.levelname + record.pathname
        if record.exc_info:
            type = type + str(record.exc_info[0])
        return type

    def update(self, record):
        """Check if a similar log has been emitted, if so how many times and has specified interval passed"""
        record_type = self._record_type(record)
        last = self.logged.get(record_type)
        # log if hasn't been logged at all
        if last is None:
            self.logged[record_type] = (1, datetime.datetime.now())
            return True
        # log if last log was more than a specified interval before
        else:
            count, last_date = last
            if count <= len(self.intervals):
                if (last_date - self.init_date) > self.intervals[count]:
                    self.logged[record_type] = (count+1, datetime.datetime.now())
                    return True
                else:
                    return False
            else:
                return False

    def emit(self, record):
        emittable = self.update(record)
        if emittable is True:
            super(SMTPHandler, self).emit(record)
票数 1
EN

Stack Overflow用户

发布于 2015-03-16 17:19:05

你可以看看mailinglogger包,它看起来就是你所需要的。This part of documentation解释了如何设置限制以防止洪水泛滥。即使没有设置任何东西,它也有合理的默认每小时10封电子邮件:)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27240208

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档