Coverage for conf/settings/sentry.py: 54%

20 statements  

« prev     ^ index     » next       coverage.py v7.15.2, created at 2026-10-07 06:14 +0000

1import sentry_sdk 

2from decouple import config 

3from sentry_sdk.integrations.django import DjangoIntegration 

4from sentry_sdk.integrations.logging import LoggingIntegration, ignore_logger 

5 

6from conf.settings.base import ENVIRONMENT 

7from conf.settings.security import DEBUG 

8 

9 

10SENTRY_DSN = config("SENTRY_DSN", default="") 

11 

12SENTRY_TRACES_SAMPLE_RATE: float = config( 

13 "SENTRY_TRACES_SAMPLE_RATE", default=0, cast=float 

14) 

15SENTRY_PROFILES_SAMPLE_RATE: float = config( 

16 "SENTRY_PROFILES_SAMPLE_RATE", default=0, cast=float 

17) 

18 

19 

20def profiles_sampler(sampling_context) -> float: 

21 """ 

22 Control the performance profile sampling. 

23 See https://docs.sentry.io/platforms/python/profiling/ 

24 

25 Returns a float between 0.0 and 1.0. 

26 """ 

27 url_path = sampling_context.get("url.path", "") 

28 

29 if "healthcheck" in url_path: 

30 return 0.0 # Exclude the health check URL from profiling 

31 

32 # All the other instances 

33 return SENTRY_PROFILES_SAMPLE_RATE 

34 

35 

36INTEGRATIONS = [ 

37 # See https://docs.sentry.io/platforms/python/integrations/django/ 

38 DjangoIntegration(), 

39 # This prevents two errors from being sent to Sentry (one with the correct 

40 # information and the other with the logged JSON as the error name), since we 

41 # use JSON-logging as well which can conflict with the way Sentry expects alerts. 

42 # https://github.com/kiwicom/structlog-sentry?tab=readme-ov-file#logging-as-json 

43 LoggingIntegration(event_level=None, level=None), 

44] 

45 

46if not DEBUG and SENTRY_DSN: 46 ↛ 47line 46 didn't jump to line 47 because the condition on line 46 was never true

47 sentry_sdk.init( 

48 dsn=SENTRY_DSN, 

49 integrations=INTEGRATIONS, 

50 traces_sample_rate=SENTRY_TRACES_SAMPLE_RATE, 

51 profiles_sampler=profiles_sampler, 

52 send_default_pii=False, 

53 environment=ENVIRONMENT, 

54 ) 

55 

56 # ALLOW_HOSTS is correctly configured so ignore this to prevent 

57 # spammy bots like https://github.com/robertdavidgraham/masscan 

58 # from pushing un-actionable alerts to Sentry like 

59 # https://sentry.io/share/issue/9af3cdf8ef74420aa7bbb6697760a82c/ 

60 ignore_logger("django.security.DisallowedHost") 

61 # ``django-structlog`` writes ERROR logs when a response has a 5xx response 

62 # code, which can be registered by Sentry and obscure the underlying reason 

63 # why 5xx response was returned in the first place. 

64 ignore_logger("django_structlog.middlewares.request") 

65 # These errors can occur in large volumes and so we don't want them to fill 

66 # up in Sentry and overwhelm us with Slack notifications. 

67 ignore_logger("api.utils.check_dead_links._head")