Skip to content

Instantly share code, notes, and snippets.

@zsiciarz
Created October 26, 2021 17:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zsiciarz/84a358e9bfabc7f4857590e407d77b3b to your computer and use it in GitHub Desktop.
Save zsiciarz/84a358e9bfabc7f4857590e407d77b3b to your computer and use it in GitHub Desktop.
Nameko with sentry_sdk
AMQP_URI: ${AMQP_URI:pyamqp://guest:guest@localhost}
SENTRY:
DSN: https://your.sentry.dsn
from weakref import WeakKeyDictionary
import sentry_sdk
from sentry_sdk import Hub
from nameko.rpc import rpc
from nameko.web.handlers import http
from nameko.extensions import DependencyProvider
class SentryReporterV2(DependencyProvider):
"""Send exceptions generated by entrypoints to a sentry server."""
def __init__(self):
self.hubs = WeakKeyDictionary()
def setup(self):
sentry_config = self.container.config.get("SENTRY")
sentry_config = sentry_config or {}
dsn = sentry_config.get("DSN", None)
print(f"{dsn=}")
sentry_sdk.init(dsn, debug=True)
print(f"Setup complete, {Hub.current=}")
try:
raise Exception("Dependency setup")
except Exception:
sentry_sdk.capture_exception()
def get_dependency(self, worker_ctx):
"""Expose the SDK directly to the worker"""
return sentry_sdk
def worker_setup(self, worker_ctx):
print(f"Worker setup before: {Hub.current=}")
self.hubs[worker_ctx] = Hub.current
print(f"Worker setup after: {Hub.current=}, {worker_ctx=}")
try:
raise Exception("Worker setup")
except Exception:
print("Handling exception in worker setup")
sentry_sdk.capture_exception()
def worker_result(self, worker_ctx, result, exc_info):
if exc_info is None:
return
worker_hub = self.hubs[worker_ctx]
print(f"Worker result: {Hub.current=}, {worker_ctx=}, {result=}, {exc_info=}")
with worker_hub:
try:
raise Exception("Worker result")
except Exception:
print("Handling exception in worker result")
sentry_sdk.capture_exception()
sentry_sdk.set_context("nameko", {"foo": "bar42"})
_, exc, _ = exc_info
print(f"Capturing: {Hub.current=}, {worker_ctx=} {exc=}")
result = sentry_sdk.capture_exception(exc)
print(f"Captured: {result=}")
def worker_teardown(self, worker_ctx):
print(f"Worker teardown: {Hub.current=}, {worker_ctx=}")
del self.hubs[worker_ctx]
class Service:
name = "crasher_service"
sentry = SentryReporterV2()
@rpc
def crash(self):
raise Exception("oops, I crashed")
@http("GET", "/")
def crash_http(self, request):
raise Exception("http crashed")
@http("GET", "/new")
def crash_http_by_hand(self, request):
sentry_sdk.init(
"https://your.sentry.dsn",
debug=True,
)
try:
raise ValueError("New SDK should catch me")
except Exception as e:
sentry_sdk.capture_exception(e)
return "ok"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment