November 11, 2023

Limiting the number of emails you get from Django Logger

As someone who still uses email to get 500 errors on their Django project sometimes you’ll wake up to 1000 emails when things go haywire. Seems to happen more often when your sever goes down, late night commits that you didn’t properly vet, etc. This has happened a bit more than I would like over the past couple months and today my sendgrid bill came out to 400$ so I had to make a small change. Below is the code I used to essentially limit how often I could get a traceback email from my django project in a specified interval.

LOGGING = { version’: 1, disable_existing_loggers’: False, handlers’: { console’: { level’: INFO, class’: logging.StreamHandler’, stream’: stdout, }, mail_admins’: { level’: ERROR, class’: main.adminemailhandler.RateLimitedAdminEmailHandler’, },

}, loggers’: { django’: { level’: WARNING, handlers’: [‘console’, mail_admins’], propagate’: False, }, main’: { level’: INFO, handlers’: [‘console’], }, } }

Admin Email Handler

import time

from django.core.cache import cache

from django.utils.log import AdminEmailHandler

import settings

class RateLimitedAdminEmailHandler(AdminEmailHandler): def emit(self, record): if cache.get(‘error_email_rate_limit’) is None: cache.set(‘error_email_rate_limit’, 0, timeout=360) rate_info = 0 else: rate_info = cache.get(‘error_email_rate_limit’)

if int(rate_info) < int(settings.EMAIL_LIMIT_PER_HOUR):

super().emit(record)

cache.set(‘error_email_rate_limit’, rate_info + 1, timeout=360) else: pass


Previous post
Reason To NOT Sell Your Business One Reason to Not Sell Your Business It always irks me when people use the phrase, “as long as their money is green.” This is probably some of the
Next post
The Right Time To Hire Trying to figure out the right time to bring on additional help is like trying to time the stock market. If you are trying
Share this post if you enjoyed it :)
Subscribe to my newsletter to get notified of new posts
Follow Me On Twitter