This repository provides a Python helper for running a fully isolated Sentry client, designed to avoid interference with global sentry_sdk usage elsewhere in your application.
The standard sentry_sdk does not support multiple independent clients. Calling sentry_sdk.init will erase any previous Sentry client and scope initialization. While the Sentry developers have suggested a workaround (discussion here), these are outdated and have several limitations. In practice, encapsulating every entry point in a GUI application (with many buttons and actions) is laborious and error-prone.
Additionally, if your software allows external code and that code calls back into your API, you may enter a new scope but still inherit data from the parent scope. Meaning you could see confidential context or breadcrumbs from the external code. More, the external code will not receive crashes since it is in your API scope. Another issue is that breadcrumbs and other enrichments set within a scope are cleared when the scope ends, making it difficult to persist session-wide data (such as global breadcrumbs or tags) that should last for the entire application session, not just a single scope.
This helper ensures your Sentry events and context remain truly isolated, with all the power of Sentry (global context, no scope if not needed), even if other parts of your application use sentry_sdk globally.obally.
from sentry_sdk_wrapper import SentrySDKWrapper, IsInOurPathsChecker
import os
dsn = "YOUR_SENTRY_DSN"
checker = IsInOurPathsChecker([os.path.dirname(__file__)])
sdk = SentrySDKWrapper(dsn, checker, environment="production") # replace sentry_sdk.init
# Use all standard Sentry functions (add_breadcrumb, set_context, set_tag, set_user, capture_exception, etc.)
# with the same arguments and behavior as the official sentry_sdk API:
sdk.add_breadcrumb(message="Started isolated Sentry")
sdk.set_tag("env", "production")
sdk.set_context("my_context", {"foo": "bar"})
try:
raise ValueError("Example error")
except Exception as e:
sdk.capture_exception(e)
See example/main.py for an illustration of how sentry_sdk_wrapper can coexist with another sentry_sdk client.
This helper is currently NOT thread-safe.
If you use Python multithreading, enriching event in different thread it will mess up data.
Thread safety will be supported in a future version.