Coverage for src/ptf/log_utils.py: 42%

22 statements  

« prev     ^ index     » next       coverage.py v7.6.4, created at 2024-11-05 09:56 +0000

1""" 

2See : 

3 https://stackoverflow.com/questions/2052284/how-to-throttle-django-error-emails 

4 https://github.com/jedie/django-tools/blob/main/django_tools/log_utils/throttle_admin_email_handler.py 

5""" 

6# -*- coding: utf-8 -*- 

7 

8from django.core.cache import cache 

9from django.utils.log import AdminEmailHandler 

10 

11 

12class ThrottledAdminEmailHandler(AdminEmailHandler): 

13 PERIOD_LENGTH_IN_SECONDS = 60 

14 MAX_EMAILS_IN_PERIOD = 25 

15 COUNTER_CACHE_KEY = "email_admins_counter" 

16 

17 def __init__(self, include_html=False, email_backend=None, reporter_class=None): 

18 super().__init__() 

19 

20 def increment_counter(self): 

21 try: 

22 cache.incr(self.COUNTER_CACHE_KEY) 

23 except ValueError: 

24 cache.set(self.COUNTER_CACHE_KEY, 1, self.PERIOD_LENGTH_IN_SECONDS) 

25 return cache.get(self.COUNTER_CACHE_KEY) 

26 

27 def emit(self, record): 

28 try: 

29 counter = self.increment_counter() 

30 except Exception: 

31 pass 

32 else: 

33 if counter > self.MAX_EMAILS_IN_PERIOD: 

34 return 

35 super().emit(record)