From a91d342d1963b47c07a5cc69edf5e230d79bf102 Mon Sep 17 00:00:00 2001 From: Daniel Szoke Date: Wed, 7 Aug 2024 11:38:25 +0200 Subject: [PATCH 1/2] feat(integrations): New `SysExitIntegration` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The `SysExitIntegration` reports `SystemExit` exceptions raised by calls made to `sys.exit` with a value indicating unsuccessful program termination – that is, any value other than `0` or `None`. Optionally, by setting `capture_successful_exits=True`, the `SysExitIntegration` can also report `SystemExit` exceptions resulting from `sys.exit` calls with successful values. You need to manually enable this integration if you wish to use it. Closes #2636 --- sentry_sdk/integrations/sys_exit.py | 73 ++++++++++++++++++++ tests/integrations/sys_exit/test_sys_exit.py | 71 +++++++++++++++++++ 2 files changed, 144 insertions(+) create mode 100644 sentry_sdk/integrations/sys_exit.py create mode 100644 tests/integrations/sys_exit/test_sys_exit.py diff --git a/sentry_sdk/integrations/sys_exit.py b/sentry_sdk/integrations/sys_exit.py new file mode 100644 index 0000000000..88a95c0781 --- /dev/null +++ b/sentry_sdk/integrations/sys_exit.py @@ -0,0 +1,73 @@ +import sys + +import sentry_sdk +from sentry_sdk.utils import ( + ensure_integration_enabled, + capture_internal_exceptions, + event_from_exception, +) +from sentry_sdk.integrations import Integration +from sentry_sdk._types import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Callable + from typing import NoReturn, Union + + +class SysExitIntegration(Integration): + """Captures sys.exit calls and sends them as an events to Sentry. + + By default, SystemExit exceptions are not captured by the SDK. Enabling this integration will capture SystemExit + exceptions generated by sys.exit calls and send them to Sentry. + + This integration, in its default configuration, only captures the sys.exit call if the exit code is a non-zero and + non-None value (unsuccessful exits). Pass `capture_successful_exits=True` to capture successful exits as well. + Note that the integration does not capture SystemExit exceptions raised outside a call to sys.exit. + """ + + identifier = "sys_exit" + + def __init__(self, *, capture_successful_exits=False): + # type: (bool) -> None + self._capture_successful_exits = capture_successful_exits + + @staticmethod + def setup_once(): + # type: () -> None + SysExitIntegration._patch_sys_exit() + + @staticmethod + def _patch_sys_exit(): + # type: () -> None + old_exit = sys.exit # type: Callable[[Union[str, int, None]], NoReturn] + + @ensure_integration_enabled(SysExitIntegration, old_exit) + def sentry_patched_exit(__status=0): + # type: (Union[str, int, None]) -> NoReturn + # @ensure_integration_enabled ensures that this is non-None + integration = sentry_sdk.get_client().get_integration( + SysExitIntegration + ) # type: SysExitIntegration + + try: + old_exit(__status) + except SystemExit as e: + with capture_internal_exceptions(): + if integration._capture_successful_exits or __status not in ( + 0, + None, + ): + _capture_exception(e) + raise e + + sys.exit = sentry_patched_exit # type: ignore + + +def _capture_exception(exc): + # type: (SystemExit) -> None + event, hint = event_from_exception( + exc, + client_options=sentry_sdk.get_client().options, + mechanism={"type": SysExitIntegration.identifier, "handled": False}, + ) + sentry_sdk.capture_event(event, hint=hint) diff --git a/tests/integrations/sys_exit/test_sys_exit.py b/tests/integrations/sys_exit/test_sys_exit.py new file mode 100644 index 0000000000..81a950c7c0 --- /dev/null +++ b/tests/integrations/sys_exit/test_sys_exit.py @@ -0,0 +1,71 @@ +import sys + +import pytest + +from sentry_sdk.integrations.sys_exit import SysExitIntegration + + +@pytest.mark.parametrize( + ("integration_params", "exit_status", "should_capture"), + ( + ({}, 0, False), + ({}, 1, True), + ({}, None, False), + ({}, "unsuccessful exit", True), + ({"capture_successful_exits": False}, 0, False), + ({"capture_successful_exits": False}, 1, True), + ({"capture_successful_exits": False}, None, False), + ({"capture_successful_exits": False}, "unsuccessful exit", True), + ({"capture_successful_exits": True}, 0, True), + ({"capture_successful_exits": True}, 1, True), + ({"capture_successful_exits": True}, None, True), + ({"capture_successful_exits": True}, "unsuccessful exit", True), + ), +) +def test_sys_exit( + sentry_init, capture_events, integration_params, exit_status, should_capture +): + sentry_init(integrations=[SysExitIntegration(**integration_params)]) + + events = capture_events() + + # Manually catch the sys.exit rather than using pytest.raises because IDE does not recognize that pytest.raises + # will catch SystemExit. + try: + sys.exit(exit_status) + except SystemExit: + ... + else: + pytest.fail("Patched sys.exit did not raise SystemExit") + + if should_capture: + (event,) = events + (exception_value,) = event["exception"]["values"] + + assert exception_value["type"] == "SystemExit" + assert exception_value["value"] == ( + str(exit_status) if exit_status is not None else "" + ) + else: + assert len(events) == 0 + + +def test_sys_exit_integration_not_auto_enabled(sentry_init, capture_events): + sentry_init() # No SysExitIntegration + + events = capture_events() + + # Manually catch the sys.exit rather than using pytest.raises because IDE does not recognize that pytest.raises + # will catch SystemExit. + try: + sys.exit(1) + except SystemExit: + ... + else: + pytest.fail( + "sys.exit should not be patched, but it must have been because it did not raise SystemExit" + ) + + assert ( + len(events) == 0 + ), "No events should have been captured because sys.exit should not have been patched" From b1c17e43ab7f301fb47d1bdc9218554c731b4251 Mon Sep 17 00:00:00 2001 From: Daniel Szoke <7881302+szokeasaurusrex@users.noreply.github.com> Date: Fri, 9 Aug 2024 13:07:28 +0200 Subject: [PATCH 2/2] Update sentry_sdk/integrations/sys_exit.py Co-authored-by: Anton Pirker --- sentry_sdk/integrations/sys_exit.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sentry_sdk/integrations/sys_exit.py b/sentry_sdk/integrations/sys_exit.py index 88a95c0781..39539b4c15 100644 --- a/sentry_sdk/integrations/sys_exit.py +++ b/sentry_sdk/integrations/sys_exit.py @@ -15,7 +15,7 @@ class SysExitIntegration(Integration): - """Captures sys.exit calls and sends them as an events to Sentry. + """Captures sys.exit calls and sends them as events to Sentry. By default, SystemExit exceptions are not captured by the SDK. Enabling this integration will capture SystemExit exceptions generated by sys.exit calls and send them to Sentry.