Skip to content

Commit

Permalink
sentry
Browse files Browse the repository at this point in the history
  • Loading branch information
whyliam committed Dec 7, 2019
1 parent 956db15 commit c461cda
Show file tree
Hide file tree
Showing 50 changed files with 2,631 additions and 945 deletions.
Empty file modified sentry_sdk/__init__.py
100755 → 100644
Empty file.
13 changes: 9 additions & 4 deletions sentry_sdk/_compat.py
100755 → 100644
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@
from typing import Any
from typing import Type

from typing import TypeVar

T = TypeVar("T")


PY2 = sys.version_info[0] == 2

Expand All @@ -23,6 +27,7 @@
iteritems = lambda x: x.iteritems() # noqa: B301

def implements_str(cls):
# type: (T) -> T
cls.__unicode__ = cls.__str__
cls.__str__ = lambda x: unicode(x).encode("utf-8") # noqa
return cls
Expand All @@ -40,10 +45,8 @@ def implements_str(cls):
int_types = (int,) # noqa
iteritems = lambda x: x.items()

def _identity(x):
return x

def implements_str(x):
# type: (T) -> T
return x

def reraise(tp, value, tb=None):
Expand All @@ -55,8 +58,10 @@ def reraise(tp, value, tb=None):


def with_metaclass(meta, *bases):
# type: (Any, *Any) -> Any
class metaclass(type):
def __new__(cls, name, this_bases, d):
def __new__(metacls, name, this_bases, d):
# type: (Any, Any, Any, Any) -> Any
return meta(name, bases, d)

return type.__new__(metaclass, "temporary_class", (), {})
Expand Down
3 changes: 3 additions & 0 deletions sentry_sdk/_types.py
100755 → 100644
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,6 @@
EventProcessor = Callable[[Event, Hint], Optional[Event]]
ErrorProcessor = Callable[[Event, ExcInfo], Optional[Event]]
BreadcrumbProcessor = Callable[[Breadcrumb, BreadcrumbHint], Optional[Breadcrumb]]

# https://github.com/python/mypy/issues/5710
NotImplementedType = Any
69 changes: 69 additions & 0 deletions sentry_sdk/api.py
100755 → 100644
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@

if MYPY:
from typing import Any
from typing import Dict
from typing import Optional
from typing import overload
from typing import Callable
from typing import TypeVar
from typing import ContextManager

from sentry_sdk._types import Event, Hint, Breadcrumb, BreadcrumbHint
from sentry_sdk.tracing import Span

T = TypeVar("T")
F = TypeVar("F", bound=Callable[..., Any])
Expand All @@ -34,6 +36,12 @@ def overload(x):
"push_scope",
"flush",
"last_event_id",
"start_span",
"set_tag",
"set_context",
"set_extra",
"set_user",
"set_level",
]


Expand All @@ -46,6 +54,15 @@ def hubmethod(f):
return f


def scopemethod(f):
# type: (F) -> F
f.__doc__ = "%s\n\n%s" % (
"Alias for :py:meth:`sentry_sdk.Scope.%s`" % f.__name__,
inspect.getdoc(getattr(Scope, f.__name__)),
)
return f


@hubmethod
def capture_event(
event, # type: Event
Expand Down Expand Up @@ -161,6 +178,46 @@ def inner():
return None


@scopemethod # noqa
def set_tag(key, value):
# type: (str, Any) -> None
hub = Hub.current
if hub is not None:
hub.scope.set_tag(key, value)


@scopemethod # noqa
def set_context(key, value):
# type: (str, Any) -> None
hub = Hub.current
if hub is not None:
hub.scope.set_context(key, value)


@scopemethod # noqa
def set_extra(key, value):
# type: (str, Any) -> None
hub = Hub.current
if hub is not None:
hub.scope.set_extra(key, value)


@scopemethod # noqa
def set_user(value):
# type: (Dict[str, Any]) -> None
hub = Hub.current
if hub is not None:
hub.scope.set_user(value)


@scopemethod # noqa
def set_level(value):
# type: (str) -> None
hub = Hub.current
if hub is not None:
hub.scope.set_level(value)


@hubmethod
def flush(
timeout=None, # type: Optional[float]
Expand All @@ -179,3 +236,15 @@ def last_event_id():
if hub is not None:
return hub.last_event_id()
return None


@hubmethod
def start_span(
span=None, # type: Optional[Span]
**kwargs # type: Any
):
# type: (...) -> Span

# TODO: All other functions in this module check for
# `Hub.current is None`. That actually should never happen?
return Hub.current.start_span(span=span, **kwargs)
61 changes: 40 additions & 21 deletions sentry_sdk/client.py
100755 → 100644
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@
get_type_name,
capture_internal_exceptions,
current_stacktrace,
disable_capture_event,
logger,
)
from sentry_sdk.serializer import Serializer
from sentry_sdk.serializer import serialize
from sentry_sdk.transport import make_transport
from sentry_sdk.consts import DEFAULT_OPTIONS, SDK_INFO, ClientConstructor
from sentry_sdk.integrations import setup_integrations
Expand Down Expand Up @@ -42,9 +43,9 @@ def _get_options(*args, **kwargs):
dsn = None

rv = dict(DEFAULT_OPTIONS)
options = dict(*args, **kwargs) # type: ignore
options = dict(*args, **kwargs)
if dsn is not None and options.get("dsn") is None:
options["dsn"] = dsn # type: ignore
options["dsn"] = dsn

for key, value in iteritems(options):
if key not in rv:
Expand All @@ -63,7 +64,7 @@ def _get_options(*args, **kwargs):
if rv["server_name"] is None and hasattr(socket, "gethostname"):
rv["server_name"] = socket.gethostname()

return rv # type: ignore
return rv


class _Client(object):
Expand All @@ -74,23 +75,37 @@ class _Client(object):
"""

def __init__(self, *args, **kwargs):
# type: (*Optional[str], **Any) -> None
# type: (*Any, **Any) -> None
self.options = get_options(*args, **kwargs) # type: Dict[str, Any]
self._init_impl()

def __getstate__(self):
# type: () -> Any
return {"options": self.options}

def __setstate__(self, state):
# type: (Any) -> None
self.options = state["options"]
self._init_impl()

def _init_impl(self):
# type: () -> None
old_debug = _client_init_debug.get(False)
try:
self.options = options = get_options(*args, **kwargs) # type: ignore
_client_init_debug.set(options["debug"])
self.transport = make_transport(options)
_client_init_debug.set(self.options["debug"])
self.transport = make_transport(self.options)

request_bodies = ("always", "never", "small", "medium")
if options["request_bodies"] not in request_bodies:
if self.options["request_bodies"] not in request_bodies:
raise ValueError(
"Invalid value for request_bodies. Must be one of {}".format(
request_bodies
)
)

self.integrations = setup_integrations(
options["integrations"], with_defaults=options["default_integrations"]
self.options["integrations"],
with_defaults=self.options["default_integrations"],
)
finally:
_client_init_debug.set(old_debug)
Expand All @@ -108,6 +123,7 @@ def _prepare_event(
scope, # type: Optional[Scope]
):
# type: (...) -> Optional[Event]

if event.get("timestamp") is None:
event["timestamp"] = datetime.utcnow()

Expand Down Expand Up @@ -139,8 +155,8 @@ def _prepare_event(
}

for key in "release", "environment", "server_name", "dist":
if event.get(key) is None and self.options[key] is not None: # type: ignore
event[key] = text_type(self.options[key]).strip() # type: ignore
if event.get(key) is None and self.options[key] is not None:
event[key] = text_type(self.options[key]).strip()
if event.get("sdk") is None:
sdk_info = dict(SDK_INFO)
sdk_info["integrations"] = sorted(self.integrations.keys())
Expand All @@ -156,7 +172,7 @@ def _prepare_event(
# Postprocess the event here so that annotated types do
# generally not surface in before_send
if event is not None:
event = Serializer().serialize_event(event)
event = serialize(event)

before_send = self.options["before_send"]
if before_send is not None:
Expand Down Expand Up @@ -185,7 +201,7 @@ def _is_ignored_error(self, event, hint):
if errcls == full_name or errcls == type_name:
return True
else:
if issubclass(exc_info[0], errcls): # type: ignore
if issubclass(exc_info[0], errcls):
return True

return False
Expand Down Expand Up @@ -226,20 +242,23 @@ def capture_event(
:returns: An event ID. May be `None` if there is no DSN set or of if the SDK decided to discard the event for other reasons. In such situations setting `debug=True` on `init()` may help.
"""
if disable_capture_event.get(False):
return None

if self.transport is None:
return None
if hint is None:
hint = {}
rv = event.get("event_id")
if rv is None:
event["event_id"] = rv = uuid.uuid4().hex
event_id = event.get("event_id")
if event_id is None:
event["event_id"] = event_id = uuid.uuid4().hex
if not self._should_capture(event, hint, scope):
return None
event = self._prepare_event(event, hint, scope)
if event is None:
event_opt = self._prepare_event(event, hint, scope)
if event_opt is None:
return None
self.transport.capture_event(event)
return rv
self.transport.capture_event(event_opt)
return event_id

def close(
self,
Expand Down
14 changes: 8 additions & 6 deletions sentry_sdk/consts.py
100755 → 100644
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from typing import Type
from typing import Dict
from typing import Any
from typing import Sequence

from sentry_sdk.transport import Transport
from sentry_sdk.integrations import Integration
Expand All @@ -27,17 +28,17 @@ def __init__(
environment=None, # type: Optional[str]
server_name=None, # type: Optional[str]
shutdown_timeout=2, # type: int
integrations=[], # type: List[Integration]
in_app_include=[], # type: List[str]
in_app_exclude=[], # type: List[str]
integrations=[], # type: Sequence[Integration] # noqa: B006
in_app_include=[], # type: List[str] # noqa: B006
in_app_exclude=[], # type: List[str] # noqa: B006
default_integrations=True, # type: bool
dist=None, # type: Optional[str]
transport=None, # type: Optional[Union[Transport, Type[Transport], Callable[[Event], None]]]
sample_rate=1.0, # type: float
send_default_pii=False, # type: bool
http_proxy=None, # type: Optional[str]
https_proxy=None, # type: Optional[str]
ignore_errors=[], # type: List[Union[type, str]]
ignore_errors=[], # type: List[Union[type, str]] # noqa: B006
request_bodies="medium", # type: str
before_send=None, # type: Optional[EventProcessor]
before_breadcrumb=None, # type: Optional[BreadcrumbProcessor]
Expand All @@ -48,6 +49,7 @@ def __init__(
# DO NOT ENABLE THIS RIGHT NOW UNLESS YOU WANT TO EXCEED YOUR EVENT QUOTA IMMEDIATELY
traces_sample_rate=0.0, # type: float
traceparent_v2=False, # type: bool
_experiments={}, # type: Dict[str, Any] # noqa: B006
):
# type: (...) -> None
pass
Expand All @@ -58,7 +60,7 @@ def _get_default_options():
import inspect

if hasattr(inspect, "getfullargspec"):
getargspec = inspect.getfullargspec # type: ignore
getargspec = inspect.getfullargspec
else:
getargspec = inspect.getargspec # type: ignore

Expand All @@ -70,7 +72,7 @@ def _get_default_options():
del _get_default_options


VERSION = "0.10.0"
VERSION = "0.13.5"
SDK_INFO = {
"name": "sentry.python",
"version": VERSION,
Expand Down
Empty file modified sentry_sdk/debug.py
100755 → 100644
Empty file.
Loading

0 comments on commit c461cda

Please sign in to comment.