logging - Throttle Python smtphandler emails -
i want use python's logger smtphandler send emails errors , whatnot. don't want inbox flooded thousands of emails same bug.
is there way throttle amounts of emails sent? ideally, if keeps catching same exception, taper off amount of emails sent.
i wound making own wrapper smtphandler. first draft not perfect. multiple instances of handler limit dupes separately. store self.logged in redis make shared resource.
the parameter needs set intervals list of minutes (ints). suppose [0 10 30] passed in intervals. send email now. subsequent dupes ignored until after 10 minutes has passed. subsequent dupes ignored until after 30 minutes,. won't send emails after that.
if want change counts dupe logs, modify _record_type requirements.
import logging.handlers import datetime class smtphandler(logging.handlers.smtphandler): """ custom smtphandler logger. specify intervals emails sent. @ number of emails sent equal 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) in intervals] def _record_type(self, record): """make key 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 similar log has been emitted, if how many times , has specified interval passed""" record_type = self._record_type(record) last = self.logged.get(record_type) # log if hasn't been logged @ if last none: self.logged[record_type] = (1, datetime.datetime.now()) return true # log if last log more 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 true: super(smtphandler, self).emit(record)
Comments
Post a Comment