dedupe.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import weakref
  2. import sentry_sdk
  3. from sentry_sdk.utils import ContextVar, logger
  4. from sentry_sdk.integrations import Integration
  5. from sentry_sdk.scope import add_global_event_processor
  6. from typing import TYPE_CHECKING
  7. if TYPE_CHECKING:
  8. from typing import Optional
  9. from sentry_sdk._types import Event, Hint
  10. class DedupeIntegration(Integration):
  11. identifier = "dedupe"
  12. def __init__(self):
  13. # type: () -> None
  14. self._last_seen = ContextVar("last-seen")
  15. @staticmethod
  16. def setup_once():
  17. # type: () -> None
  18. @add_global_event_processor
  19. def processor(event, hint):
  20. # type: (Event, Optional[Hint]) -> Optional[Event]
  21. if hint is None:
  22. return event
  23. integration = sentry_sdk.get_client().get_integration(DedupeIntegration)
  24. if integration is None:
  25. return event
  26. exc_info = hint.get("exc_info", None)
  27. if exc_info is None:
  28. return event
  29. last_seen = integration._last_seen.get(None)
  30. if last_seen is not None:
  31. # last_seen is either a weakref or the original instance
  32. last_seen = (
  33. last_seen() if isinstance(last_seen, weakref.ref) else last_seen
  34. )
  35. exc = exc_info[1]
  36. if last_seen is exc:
  37. logger.info("DedupeIntegration dropped duplicated error event %s", exc)
  38. return None
  39. # we can only weakref non builtin types
  40. try:
  41. integration._last_seen.set(weakref.ref(exc))
  42. except TypeError:
  43. integration._last_seen.set(exc)
  44. return event
  45. @staticmethod
  46. def reset_last_seen():
  47. # type: () -> None
  48. integration = sentry_sdk.get_client().get_integration(DedupeIntegration)
  49. if integration is None:
  50. return
  51. integration._last_seen.set(None)