sys_exit.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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=False):
  20. # type: (bool) -> None
  21. self._capture_successful_exits = capture_successful_exits
  22. @staticmethod
  23. def setup_once():
  24. # type: () -> None
  25. SysExitIntegration._patch_sys_exit()
  26. @staticmethod
  27. def _patch_sys_exit():
  28. # type: () -> None
  29. old_exit = sys.exit # type: Callable[[Union[str, int, None]], NoReturn]
  30. @functools.wraps(old_exit)
  31. def sentry_patched_exit(__status=0):
  32. # type: (Union[str, int, None]) -> NoReturn
  33. # @ensure_integration_enabled ensures that this is non-None
  34. integration = sentry_sdk.get_client().get_integration(SysExitIntegration)
  35. if integration is None:
  36. old_exit(__status)
  37. try:
  38. old_exit(__status)
  39. except SystemExit as e:
  40. with capture_internal_exceptions():
  41. if integration._capture_successful_exits or __status not in (
  42. 0,
  43. None,
  44. ):
  45. _capture_exception(e)
  46. raise e
  47. sys.exit = sentry_patched_exit
  48. def _capture_exception(exc):
  49. # type: (SystemExit) -> None
  50. event, hint = event_from_exception(
  51. exc,
  52. client_options=sentry_sdk.get_client().options,
  53. mechanism={"type": SysExitIntegration.identifier, "handled": False},
  54. )
  55. sentry_sdk.capture_event(event, hint=hint)