Created
October 20, 2022 08:11
-
-
Save puittenbroek/f9de6ddc1fbc1ac838fd46b31c827371 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import logging | |
| from weakref import WeakKeyDictionary | |
| import nameko | |
| from nameko.extensions import DependencyProvider | |
| import sentry_sdk | |
| from sentry_sdk import Hub | |
| from sentry_sdk.utils import event_from_exception | |
| logger = logging.getLogger("workers") | |
| class ErrorSentryHandler(DependencyProvider): | |
| def __init__(self): | |
| self.hubs = WeakKeyDictionary() | |
| self.main_hub = None | |
| def setup(self): | |
| """ | |
| Init sentry for all our workers. | |
| """ | |
| dsn = nameko.config.get("SENTRY_DSN") | |
| if dsn: | |
| sentry_sdk.init(dsn) | |
| self.main_hub = Hub.current | |
| logger.info("Sentry init completed") | |
| else: | |
| logger.info("Skipped sentry init; no DSN configured") | |
| def worker_setup(self, worker_ctx): | |
| """ | |
| For this worker, save a Hub pointing to the main hub. | |
| """ | |
| if self.main_hub: | |
| self.hubs[worker_ctx] = Hub(self.main_hub) | |
| def worker_result(self, worker_ctx, result=None, exc_info=None): | |
| """ | |
| If the worker resulted in an error, capture it in sentry. | |
| """ | |
| if exc_info is None: | |
| return # nothing to do | |
| # Fetch the earlier saved Hub. | |
| worker_hub = self.hubs.get(worker_ctx) | |
| if not worker_hub: | |
| return # sentry not setup | |
| # Capture the error in sentry. | |
| with worker_hub: | |
| client = worker_hub.client | |
| event, hint = event_from_exception( | |
| exc_info, | |
| client_options=client.options, | |
| mechanism={"type": "threading", "handled": False}, | |
| ) | |
| res = worker_hub.capture_event(event, hint=hint) | |
| logger.debug(f"capture_event result: {res}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment