簡體   English   中英

油門Python smtphandler電子郵件

[英]Throttle Python smtphandler emails

我想使用Python的記錄器smtphandler發送電子郵件以獲取錯誤信息等等。 我也不想讓我的收件箱里充斥着成千上萬個關於同一錯誤的電子郵件。

有沒有辦法限制發送的電子郵件數量? 理想情況下,如果它繼續捕獲相同的異常,請減少發送的電子郵件數量。

我結束了自己對SMTPHandler的包裝。 初稿不那么完美。 處理程序的多個實例將分別限制重復。 可以將self.logged存儲在redis中以使其成為共享資源。

唯一需要設置的額外參數是時間間隔,它是分鍾(整數)列表。 假設將[0 10 30]傳遞給間隔。 它會說現在發送電子郵件。 隨后的重復將被忽略,直到10分鍾過去為止。 然后,直到30分鍾之后,后續的重復都會被忽略。 之后,它不會再發送任何電子郵件。

如果要更改計數為重復日志,請根據需要修改_record_type。

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)

您可以查看mailinglogger程序包,它看起來像您所需要的。 文檔的此部分說明了設置限制以防止洪泛。 即使不進行任何設置,它每小時仍具有合理的默認10封電子郵件:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM