gpt4 book ai didi

python - 限制 Python smtphandler 电子邮件

转载 作者:行者123 更新时间:2023-12-01 04:56:28 25 4
gpt4 key购买 nike

我想使用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)

关于python - 限制 Python smtphandler 电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27240208/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com