sys_exit.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import functools
  2. import sys
  3. import sentry_sdk
  4. from sentry_sdk.utils import capture_internal_exceptions, event_from_exception
  5. from sentry_sdk.integrations import Integration
  6. from sentry_sdk._types import TYPE_CHECKING
  7. if TYPE_CHECKING:
  8. from collections.abc import Callable
  9. from typing import NoReturn, Union
  10. class SysExitIntegration(Integration):
  11. """Captures sys.exit calls and sends them as events to Sentry.
  12. By default, SystemExit exceptions are not captured by the SDK. Enabling this integration will capture SystemExit
  13. exceptions generated by sys.exit calls and send them to Sentry.
  14. This integration, in its default configuration, only captures the sys.exit call if the exit code is a non-zero and
  15. non-None value (unsuccessful exits). Pass `capture_successful_exits=True` to capture successful exits as well.
  16. Note that the integration does not capture SystemExit exceptions raised outside a call to sys.exit.
  17. """
  18. identifier = "sys_exit"
  19. def __init__(self, *, capture_successful_exits: bool = False) -> None:
  20. self._capture_successful_exits = capture_successful_exits
  21. @staticmethod
  22. def setup_once() -> None:
  23. SysExitIntegration._patch_sys_exit()
  24. @staticmethod
  25. def _patch_sys_exit() -> None:
  26. old_exit: "Callable[[Union[str, int, None]], NoReturn]" = sys.exit
  27. @functools.wraps(old_exit)
  28. def sentry_patched_exit(__status: "Union[str, int, None]" = 0) -> "NoReturn":
  29. # @ensure_integration_enabled ensures that this is non-None
  30. integration = sentry_sdk.get_client().get_integration(SysExitIntegration)
  31. if integration is None:
  32. old_exit(__status)
  33. try:
  34. old_exit(__status)
  35. except SystemExit as e:
  36. with capture_internal_exceptions():
  37. if integration._capture_successful_exits or __status not in (
  38. 0,
  39. None,
  40. ):
  41. _capture_exception(e)
  42. raise e
  43. sys.exit = sentry_patched_exit
  44. def _capture_exception(exc: "SystemExit") -> None:
  45. event, hint = event_from_exception(
  46. exc,
  47. client_options=sentry_sdk.get_client().options,
  48. mechanism={"type": SysExitIntegration.identifier, "handled": False},
  49. )
  50. sentry_sdk.capture_event(event, hint=hint)