Python sentry_sdk.configure_scope() Examples
The following are 30
code examples of sentry_sdk.configure_scope().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
sentry_sdk
, or try the search function
.
Example #1
Source File: exception_handler.py From renku-python with Apache License 2.0 | 7 votes |
def _handle_sentry(self): """Handle exceptions using Sentry.""" from sentry_sdk import capture_exception, configure_scope from sentry_sdk.utils import capture_internal_exceptions with configure_scope() as scope: with capture_internal_exceptions(): from git import Repo from renku.core.commands import get_git_home from renku.core.models.provenance.agents import Person repo = Repo(get_git_home()) user = Person.from_git(repo) scope.user = {'name': user.name, 'email': user.email} event_id = capture_exception() click.echo( _BUG + 'Recorded in Sentry with ID: {0}\n'.format(event_id), err=True, ) raise
Example #2
Source File: sentry.py From openSUSE-release-tools with GNU General Public License v2.0 | 6 votes |
def sentry_init(obs_apiurl=None, tags=None): try: import sentry_sdk except ImportError: sentry_init.client = sentry_client_dummy() return sentry_sdk_dummy() sentry_init.client = sentry_sdk.init( conf.config.get('sentry_sdk.dsn'), environment=conf.config.get('sentry_sdk.environment'), release=VERSION) with sentry_sdk.configure_scope() as scope: scope.set_tag('osc', core.__version__) if obs_apiurl: scope.set_tag('obs_apiurl', obs_apiurl) scope.user = {'username': conf.get_apiurl_usr(obs_apiurl)} if tags: for key, value in tags.items(): scope.set_tag(key, value) return sentry_sdk
Example #3
Source File: settings.py From richie with MIT License | 6 votes |
def post_setup(cls): """Post setup configuration. This is the place where you can configure settings that require other settings to be loaded. """ super().post_setup() # The SENTRY_DSN setting should be available to activate sentry for an environment if cls.SENTRY_DSN is not None: sentry_sdk.init( dsn=cls.SENTRY_DSN, environment=cls.ENVIRONMENT, release=cls.RELEASE, integrations=[DjangoIntegration()], ) with sentry_sdk.configure_scope() as scope: scope.set_extra("application", "backend")
Example #4
Source File: deactivate_repo.py From zeus with Apache License 2.0 | 6 votes |
def deactivate_repo(repository_id: UUID, reason: DeactivationReason): with sentry_sdk.configure_scope() as scope: scope.set_tag("repository_id", str(repository_id)) repository = Repository.query.unrestricted_unsafe().get(repository_id) repository.status = RepositoryStatus.inactive with db.session.begin_nested(): ItemOption.query.filter( ItemOption.item_id == repository_id, ItemOption.name == "auth.private-key" ).delete() db.session.add(repository) current_app.logger.warn( "repository.deactivated repository_id=%s reason=%s", repository_id, reason ) db.session.commit() msg = build_message(repository, reason) if msg: mail.send(msg)
Example #5
Source File: test_client.py From sentry-python with BSD 2-Clause "Simplified" License | 6 votes |
def test_cyclic_data(sentry_init, capture_events): sentry_init() events = capture_events() with configure_scope() as scope: data = {} data["is_cyclic"] = data other_data = "" data["not_cyclic"] = other_data data["not_cyclic2"] = other_data scope.set_extra("foo", data) capture_message("hi") (event,) = events data = event["extra"]["foo"] assert data == {"not_cyclic2": "", "not_cyclic": "", "is_cyclic": "<cyclic>"}
Example #6
Source File: test_client.py From sentry-python with BSD 2-Clause "Simplified" License | 6 votes |
def test_scope_initialized_before_client(sentry_init, capture_events): """ This is a consequence of how configure_scope() works. We must make `configure_scope()` a noop if no client is configured. Even if the user later configures a client: We don't know that. """ with configure_scope() as scope: scope.set_tag("foo", 42) sentry_init() events = capture_events() capture_message("hi") (event,) = events assert "tags" not in event
Example #7
Source File: test_celery.py From sentry-python with BSD 2-Clause "Simplified" License | 6 votes |
def test_no_stackoverflows(celery): """We used to have a bug in the Celery integration where its monkeypatching was repeated for every task invocation, leading to stackoverflows. See https://github.com/getsentry/sentry-python/issues/265 """ results = [] @celery.task(name="dummy_task") def dummy_task(): with configure_scope() as scope: scope.set_tag("foo", "bar") results.append(42) for _ in range(10000): dummy_task.delay() assert results == [42] * 10000 with configure_scope() as scope: assert not scope._tags
Example #8
Source File: settings.py From marsha with MIT License | 6 votes |
def post_setup(cls): """Post setup configuration. This is the place where you can configure settings that require other settings to be loaded. """ super().post_setup() # The DJANGO_SENTRY_DSN environment variable should be set to activate # sentry for an environment if cls.SENTRY_DSN is not None: sentry_sdk.init( dsn=cls.SENTRY_DSN, environment=cls.ENVIRONMENT, release=cls.RELEASE, integrations=[DjangoIntegration()], ) with sentry_sdk.configure_scope() as scope: scope.set_extra("application", "backend")
Example #9
Source File: service.py From raiden-services with MIT License | 6 votes |
def handle_message(self, message: Message) -> None: with sentry_sdk.configure_scope() as scope: scope.set_extra("message", message) try: if isinstance(message, PFSCapacityUpdate): changed_channel: Optional[Channel] = self.on_capacity_update(message) elif isinstance(message, PFSFeeUpdate): changed_channel = self.on_fee_update(message) else: log.debug("Ignoring message", unknown_message=message) return if changed_channel: self.database.upsert_channel(changed_channel) except DeferMessage as ex: self.defer_message_until_channel_is_open(ex.deferred_message) except InvalidGlobalMessage as ex: log.info(str(ex), **asdict(message))
Example #10
Source File: sentry.py From openSUSE-release-tools with GNU General Public License v2.0 | 6 votes |
def sentry_init(obs_apiurl=None, tags=None): try: import sentry_sdk except ImportError: sentry_init.client = sentry_client_dummy() return sentry_sdk_dummy() sentry_init.client = sentry_sdk.init( conf.config.get('sentry_sdk.dsn'), environment=conf.config.get('sentry_sdk.environment'), release=VERSION) with sentry_sdk.configure_scope() as scope: scope.set_tag('osc', core.__version__) if obs_apiurl: scope.set_tag('obs_apiurl', obs_apiurl) scope.user = {'username': conf.get_apiurl_usr(obs_apiurl)} if tags: for key, value in tags.items(): scope.set_tag(key, value) return sentry_sdk
Example #11
Source File: worker.py From mergify-engine with Apache License 2.0 | 5 votes |
def push(redis, owner, repo, pull_number, event_type, data): with sentry_sdk.configure_scope() as scope: scope.user = { "username": owner, } stream_name = f"stream~{owner}" scheduled_at = utils.utcnow() + datetime.timedelta(seconds=WORKER_PROCESSING_DELAY) score = scheduled_at.timestamp() transaction = await redis.pipeline() # NOTE(sileht): Add this event to the pull request stream payload = { b"event": msgpack.packb( { "owner": owner, "repo": repo, "pull_number": pull_number, "source": {"event_type": event_type, "data": data}, }, use_bin_type=True, ), } await transaction.xadd(stream_name, payload) # NOTE(sileht): Add pull request stream to process to the list, only if it # does not exists, to not update the score(date) await transaction.zaddoption("streams", "NX", **{stream_name: score}) ret = await transaction.execute() LOG.debug( "pushed to worker", gh_owner=owner, gh_repo=repo, gh_pull=pull_number, event_type=event_type, ) return (ret[0], payload)
Example #12
Source File: test_sentry.py From airflow with Apache License 2.0 | 5 votes |
def test_add_breadcrumbs(self): """ Test adding breadcrumbs. """ self.sentry.add_tagging(task_instance=self.ti) self.sentry.add_breadcrumbs(task_instance=self.ti, session=self.session) with configure_scope() as scope: test_crumb = scope._breadcrumbs.pop() self.assertEqual(CRUMB, test_crumb)
Example #13
Source File: test_sentry_hook.py From sentry_airflow with Apache License 2.0 | 5 votes |
def test_add_tags(self): """ Test adding tags. """ add_tagging(self.ti, run_id=RUN_ID) with configure_scope() as scope: for key, value in scope._tags.items(): if key is "executor": self.assertEqual(value, "SequentialExecutor") elif key is "run_id": self.assertEqual(value, RUN_ID) else: self.assertEqual(TEST_SCOPE[key], value)
Example #14
Source File: test_sentry_hook.py From sentry_airflow with Apache License 2.0 | 5 votes |
def test_add_breadcrumbs(self): """ Test adding breadcrumbs. """ add_breadcrumbs(self.ti, self.session) with configure_scope() as scope: test_crumb = scope._breadcrumbs.pop() self.assertEqual(CRUMB, test_crumb)
Example #15
Source File: update.py From myaas with GNU Lesser General Public License v3.0 | 5 votes |
def main(): dumps = list_dump_files() for dump in dumps: db_name,_ = os.path.splitext(dump) sql_file = os.path.join(settings.DUMP_DIR, dump) if is_empty(sql_file): print(f"- Skipping: {sql_file} is empty") continue start_db_func = functools.partial(start_template_database, db_name) db = RetryPolicy(5, delay=2)(start_db_func) if not db: continue # skip to next database to import print(indent("* Importing data...")) try: db.import_data(sql_file) except (ImportDataError, Exception) as e: with configure_scope() as scope: scope.set_extra("engine_status", db.get_engine_status()) scope.set_tag('database', db_name) capture_message(e) print(indent("* An error happened, debug information:", level=2)) print(db.get_engine_status(), file=sys.stderr) print(indent("* Restoring previous database", level=2)) db.stop() db.restore_backup() finally: db.remove_backup() print(indent("* Stopping database...")) db.stop() print(indent("* Stopped"))
Example #16
Source File: testcase_rollups.py From zeus with Apache License 2.0 | 5 votes |
def rollup_testcase(testcase_id: UUID): testcase = TestCase.query.unrestricted_unsafe().get(testcase_id) assert testcase with sentry_sdk.configure_scope() as scope: scope.set_tag("repository_id", str(testcase.repository_id)) scope.set_tag("job_id", str(testcase.job_id)) _, created = create_or_update( model=TestCaseRollup, where={ "repository_id": testcase.repository_id, "hash": testcase.hash, "date": testcase.job.date_finished.date(), }, values={ "name": testcase.name, "runs_failed": TestCaseRollup.runs_failed + (1 if testcase.result == Result.failed else 0), "runs_passed": TestCaseRollup.runs_passed + (1 if testcase.result == Result.passed else 0), "total_runs": TestCaseRollup.total_runs + 1, "total_duration": TestCaseRollup.total_duration + testcase.duration, }, create_values={ "name": testcase.name, "runs_failed": 1 if testcase.result == Result.failed else 0, "runs_passed": 1 if testcase.result == Result.passed else 0, "total_runs": 1, "total_duration": testcase.duration, }, ) if created: try_create( TestCaseMeta, where={"repository_id": testcase.repository_id, "hash": testcase.hash}, defaults={"first_build_id": testcase.job.build_id, "name": testcase.name}, )
Example #17
Source File: delete_repo.py From zeus with Apache License 2.0 | 5 votes |
def delete_repo(repository_id: UUID): with sentry_sdk.configure_scope() as scope: scope.set_tag("repository_id", str(repository_id)) auth.set_current_tenant(auth.RepositoryTenant(repository_id, Permission.admin)) repo = Repository.query.unrestricted_unsafe().get(repository_id) if not repo: current_app.logger.error("Repository %s not found", repository_id) return if repo.status != RepositoryStatus.inactive: current_app.logger.error("Repository %s not marked as inactive", repository_id) return # delete repo abstract entities ItemOption.query.filter_by(item_id=repo.id).delete() ItemStat.query.filter_by(item_id=repo.id).delete() # delete related abstract entities (build/job) for model in ItemStat, ItemOption: model.query.filter( model.item_id.in_( db.session.query(Build.id) .filter(Build.repository_id == repo.id) .subquery() ) ).delete(synchronize_session=False) model.query.filter( model.item_id.in_( db.session.query(Job.id).filter(Job.repository_id == repo.id).subquery() ) ).delete(synchronize_session=False) db.session.delete(repo) db.session.commit()
Example #18
Source File: auth.py From zeus with Apache License 2.0 | 5 votes |
def from_user(cls, user: Optional[User]): if not user: return cls() g.current_user = user with sentry_sdk.configure_scope() as scope: scope.user = {"id": str(user.id), "email": user.email} return UserTenant(user_id=user.id)
Example #19
Source File: auth.py From zeus with Apache License 2.0 | 5 votes |
def logout(): session.clear() g.current_user = None g.current_tenant = None with sentry_sdk.configure_scope() as scope: scope.user = None
Example #20
Source File: service.py From raiden-services with MIT License | 5 votes |
def handle_event(self, event: Event) -> None: with sentry_sdk.configure_scope() as scope: scope.set_extra("event", event) if isinstance(event, ReceiveTokenNetworkCreatedEvent): self.handle_token_network_created(event) elif isinstance(event, ReceiveChannelOpenedEvent): self.handle_channel_opened(event) elif isinstance(event, ReceiveChannelClosedEvent): self.handle_channel_closed(event) elif isinstance(event, UpdatedHeadBlockEvent): # TODO: Store blockhash here as well self.blockchain_state.latest_committed_block = event.head_block_number self.database.update_lastest_committed_block(event.head_block_number) else: log.debug("Unhandled event", evt=event)
Example #21
Source File: auth.py From zeus with Apache License 2.0 | 5 votes |
def get_current_user(fetch=True) -> Optional[User]: rv = getattr(g, "current_user", None) if not rv and fetch: rv = get_user_from_request() g.current_user = rv with sentry_sdk.configure_scope() as scope: scope.user = {"id": str(rv.id), "email": rv.email} if rv else None return rv
Example #22
Source File: auth.py From zeus with Apache License 2.0 | 5 votes |
def set_current_tenant(tenant: Tenant): current_app.logger.info("Binding tenant as %r", tenant) g.current_tenant = tenant with sentry_sdk.configure_scope() as scope: scope.set_tag( "repository_id", str(tenant.repository_ids[0]) if len(tenant.repository_ids) == 1 else None, ) scope.set_context( "tenant", {"repository_ids": [str(i) for i in tenant.repository_ids]} )
Example #23
Source File: config.py From zeus with Apache License 2.0 | 5 votes |
def with_health_check(app): def middleware(environ, start_response): path_info = environ.get("PATH_INFO", "") if path_info: with sentry_sdk.configure_scope() as scope: scope.transaction = path_info if environ.get("PATH_INFO", "") == "/healthz": start_response("200 OK", [("Content-Type", "application/json")]) return [b'{"ok": true}'] return app(environ, start_response) return middleware
Example #24
Source File: server.py From raiden-services with MIT License | 5 votes |
def handle_message(self, message: Message) -> None: with configure_scope() as scope: scope.set_extra("message", message) try: if isinstance(message, RequestMonitoring): self.on_monitor_request(message) else: log.debug("Ignoring message", message=message) # add more advanced exception catching except AssertionError as ex: log.error("Error while handling message", message=message, _exc=ex)
Example #25
Source File: __init__.py From spidermon with BSD 3-Clause "New" or "Revised" License | 5 votes |
def send_message(self, message): sentry_client = Client(dsn=self.sentry_dsn, environment=self.environment) with configure_scope() as scope: scope.set_tag("project_name", self.project_name) scope.set_extra("job_link", message.get("job_link", "")) scope.set_extra("spider_name", message.get("spider_name", "")) scope.set_extra("items_count", message.get("items_count", 0)) scope.set_extra( "passed_monitors_count", message.get("passed_monitors_count", 0) ) scope.set_extra( "failed_monitors_count", message.get("failed_monitors_count", 0) ) scope.set_extra("failed_monitors", message.get("failed_monitors", [])) sentry_client.capture_event( { "message": "{title} \n {description}".format( title=message.get("title"), description=message.get("failure_reasons", ""), ), "level": self.sentry_log_level, }, scope=scope, ) logger.info("Notification sent to the sentry dashboard!!") sentry_client.close()
Example #26
Source File: test_tornado.py From sentry-python with BSD 2-Clause "Simplified" License | 5 votes |
def get(self): with configure_scope() as scope: scope.set_tag("foo", 42) 1 / 0
Example #27
Source File: test_tornado.py From sentry-python with BSD 2-Clause "Simplified" License | 5 votes |
def test_basic(tornado_testcase, sentry_init, capture_events): sentry_init(integrations=[TornadoIntegration()], send_default_pii=True) events = capture_events() client = tornado_testcase(Application([(r"/hi", CrashingHandler)])) response = client.fetch( "/hi?foo=bar", headers={"Cookie": "name=value; name2=value2; name3=value3"} ) assert response.code == 500 (event,) = events (exception,) = event["exception"]["values"] assert exception["type"] == "ZeroDivisionError" assert exception["mechanism"]["type"] == "tornado" request = event["request"] host = request["headers"]["Host"] assert event["request"] == { "env": {"REMOTE_ADDR": "127.0.0.1"}, "headers": { "Accept-Encoding": "gzip", "Connection": "close", "Host": host, "Cookie": "name=value; name2=value2; name3=value3", }, "cookies": {"name": "value", "name2": "value2", "name3": "value3"}, "method": "GET", "query_string": "foo=bar", "url": "http://{host}/hi".format(host=host), } assert event["tags"] == {"foo": 42} assert ( event["transaction"] == "tests.integrations.tornado.test_tornado.CrashingHandler.get" ) with configure_scope() as scope: assert not scope._tags
Example #28
Source File: test_threading.py From sentry-python with BSD 2-Clause "Simplified" License | 5 votes |
def test_propagates_hub(sentry_init, capture_events, propagate_hub): sentry_init( default_integrations=False, integrations=[ThreadingIntegration(propagate_hub=propagate_hub)], ) events = capture_events() def stage1(): with configure_scope() as scope: scope.set_tag("stage1", True) t = Thread(target=stage2) t.start() t.join() def stage2(): 1 / 0 t = Thread(target=stage1) t.start() t.join() (event,) = events (exception,) = event["exception"]["values"] assert exception["type"] == "ZeroDivisionError" assert exception["mechanism"] == {"type": "threading", "handled": False} if propagate_hub: assert event["tags"]["stage1"] is True else: assert "stage1" not in event.get("tags", {})
Example #29
Source File: spark_worker.py From sentry-python with BSD 2-Clause "Simplified" License | 5 votes |
def _tag_task_context(): # type: () -> None from pyspark.taskcontext import TaskContext with configure_scope() as scope: @scope.add_event_processor def process_event(event, hint): # type: (Event, Hint) -> Optional[Event] with capture_internal_exceptions(): integration = Hub.current.get_integration(SparkWorkerIntegration) task_context = TaskContext.get() if integration is None or task_context is None: return event event.setdefault("tags", {}).setdefault( "stageId", task_context.stageId() ) event["tags"].setdefault("partitionId", task_context.partitionId()) event["tags"].setdefault("attemptNumber", task_context.attemptNumber()) event["tags"].setdefault("taskAttemptId", task_context.taskAttemptId()) if task_context._localProperties: if "sentry_app_name" in task_context._localProperties: event["tags"].setdefault( "app_name", task_context._localProperties["sentry_app_name"] ) event["tags"].setdefault( "application_id", task_context._localProperties["sentry_application_id"], ) if "callSite.short" in task_context._localProperties: event.setdefault("extra", {}).setdefault( "callSite", task_context._localProperties["callSite.short"] ) return event
Example #30
Source File: blueprint.py From website with MIT License | 5 votes |
def github_error(blueprint, error, error_description=None, error_uri=None): """A GitHub API error handler that pushes the error to Sentry and shows a flash message to the user. """ if error: with configure_scope() as scope: scope.set_extra("error_description", error_description) scope.set_extra("error_uri", error_uri) capture_message(f"Error during OAUTH found: {error}") flash( f"OAuth error from Github ({error}): {error_description}", category="error" )