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