Skip to content

Instantly share code, notes, and snippets.

@hyzyla
Created December 30, 2022 10:03
Show Gist options
  • Save hyzyla/41ed99cb0a8affcc29e5460f8ee4bb55 to your computer and use it in GitHub Desktop.
Save hyzyla/41ed99cb0a8affcc29e5460f8ee4bb55 to your computer and use it in GitHub Desktop.
Thin wrapper around Sentry SDK
"""
Thin wrapper around Sentry SDK, to hide details and do not depend on one product
"""
import logging
from contextlib import contextmanager
from typing import Any, Iterator
import sentry_sdk
from sentry_sdk.integrations.celery import CeleryIntegration
from sentry_sdk.integrations.logging import LoggingIntegration, ignore_logger
Scope = sentry_sdk.Scope
def init(dsn: str | None, environment: str) -> None:
sentry_sdk.init(
dsn=dsn,
environment=environment,
shutdown_timeout=10,
integrations=[
LoggingIntegration(
level=logging.INFO, # Capture info and above as breadcrumbs
event_level=logging.ERROR, # Send errors as events
),
CeleryIntegration(),
],
)
def capture_exception(error: BaseException) -> None:
"""
Manually capture exception
"""
sentry_sdk.capture_exception(error=error)
def set_attachment(key: str, value: bytes) -> None:
"""
Add large value to sentry context
"""
return sentry_sdk.Hub.current.scope.add_attachment(
bytes=value,
filename=key,
)
def set_context(key: str, value: Any) -> None:
"""
Add value to sentry context
"""
return sentry_sdk.set_context(
key=key,
value=value,
)
@contextmanager
def configure_scope() -> Iterator[Scope]:
""" Start new Sentry scope """
with sentry_sdk.configure_scope() as scope:
yield scope
scope.clear()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment