from datetime import datetime from contextlib import contextmanager
from sentry_sdk._compat import with_metaclass from sentry_sdk.scope import Scope from sentry_sdk.client import Client from sentry_sdk.tracing import Span from sentry_sdk.sessions import Session from sentry_sdk.utils import (
exc_info_from_error,
event_from_exception,
logger,
ContextVar,
)
from sentry_sdk._types import MYPY
if MYPY: from typing import Union from typing import Any from typing import Optional from typing import Tuple from typing import Dict from typing import List from typing import Callable from typing import Generator from typing import Type from typing import TypeVar from typing import overload from typing import ContextManager
from sentry_sdk.integrations import Integration from sentry_sdk._types import (
Event,
Hint,
Breadcrumb,
BreadcrumbHint,
ExcInfo,
) from sentry_sdk.consts import ClientConstructor
T = TypeVar("T")
else:
def overload(x): # type: (T) -> T return x
_local = ContextVar("sentry_current_hub")
def _update_scope(base, scope_change, scope_kwargs): # type: (Scope, Optional[Any], Dict[str, Any]) -> Scope if scope_change and scope_kwargs: raise TypeError("cannot provide scope and kwargs") if scope_change isnotNone:
final_scope = copy.copy(base) if callable(scope_change):
scope_change(final_scope) else:
final_scope.update_from_scope(scope_change) elif scope_kwargs:
final_scope = copy.copy(base)
final_scope.update_from_kwargs(scope_kwargs) else:
final_scope = base return final_scope
def __exit__(self, exc_type, exc_value, tb): # type: (Any, Any, Any) -> None
c = self._client if c isnotNone:
c.close()
def _init(*args, **kwargs): # type: (*Optional[str], **Any) -> ContextManager[Any] """Initializes the SDK and optionally integrations.
This takes the same arguments as the client constructor. """
client = Client(*args, **kwargs) # type: ignore
Hub.current.bind_client(client)
rv = _InitGuard(client) return rv
from sentry_sdk._types import MYPY
if MYPY: # Make mypy, PyCharm and other static analyzers think `init` is a type to # have nicer autocompletion for params. # # Use `ClientConstructor` to define the argument types of `init` and # `ContextManager[Any]` to tell static analyzers about the return type.
class init(ClientConstructor, ContextManager[Any]): # noqa: N801 pass
else: # Alias `init` for actual usage. Go through the lambda indirection to throw # PyCharm off of the weakly typed signature (it would otherwise discover # both the weakly typed signature of `_init` and our faked `init` type).
init = (lambda: _init)()
class HubMeta(type):
@property def current(cls): # type: () -> Hub """Returns the current instance of the hub."""
rv = _local.get(None) if rv isNone:
rv = Hub(GLOBAL_HUB)
_local.set(rv) return rv
@property def main(cls): # type: () -> Hub """Returns the main instance of the hub.""" return GLOBAL_HUB
layer = self._hub._stack[self._original_len - 1] del self._hub._stack[self._original_len - 1 :]
if layer[1] != self._layer[1]:
logger.error( "Wrong scope found. Meant to pop %s, but popped %s.",
layer[1],
self._layer[1],
) elif layer[0] != self._layer[0]:
warning = ( "init() called inside of pushed scope. This might be entirely " "legitimate but usually occurs when initializing the SDK inside " "a request handler or task/job function. Try to initialize the " "SDK as early as possible instead."
)
logger.warning(warning)
class Hub(with_metaclass(HubMeta)): # type: ignore """The hub wraps the concurrency management of the SDK. Each thread has
its own hub but the hub might transfer with the flow of execution if
context vars are available.
If the hub is used with a with statement it's temporarily activated. """
def run(
self, callback # type: Callable[[], T]
): # type: (...) -> T """Runs a callback in the context of the hub. Alternatively the with statement can be used on the hub directly. """ with self: return callback()
def get_integration(
self, name_or_class # type: Union[str, Type[Integration]]
): # type: (...) -> Any """Returns the integration for this hub by name or class. If there is no client bound or the client does not have that integration
then `None` is returned.
If the return value isnot `None` the hub is guaranteed to have a
client attached. """ if isinstance(name_or_class, str):
integration_name = name_or_class elif name_or_class.identifier isnotNone:
integration_name = name_or_class.identifier else: raise ValueError("Integration has no name")
client = self._stack[-1][0] if client isnotNone:
rv = client.integrations.get(integration_name) if rv isnotNone: return rv
@property def client(self): # type: () -> Optional[Client] """Returns the current client on the hub.""" return self._stack[-1][0]
@property def scope(self): # type: () -> Scope """Returns the current scope on the hub.""" return self._stack[-1][1]
def last_event_id(self): # type: () -> Optional[str] """Returns the last event ID.""" return self._last_event_id
def bind_client(
self, new # type: Optional[Client]
): # type: (...) -> None """Binds a new client to the hub."""
top = self._stack[-1]
self._stack[-1] = (new, top[1])
def capture_message(
self,
message, # type: str
level=None, # type: Optional[str]
scope=None, # type: Optional[Any]
**scope_args # type: Dict[str, Any]
): # type: (...) -> Optional[str] """Captures a message. The message is just a string. If no level is provided the default level is `info`.
:returns: An `event_id` if the SDK decided to send the event (see :py:meth:`sentry_sdk.Client.capture_event`). """ if self.client isNone: returnNone if level isNone:
level = "info" return self.capture_event(
{"message": message, "level": level}, scope=scope, **scope_args
)
:param error: An exception to catch. If `None`, `sys.exc_info()` will be used.
:returns: An `event_id` if the SDK decided to send the event (see :py:meth:`sentry_sdk.Client.capture_event`). """
client = self.client if client isNone: returnNone if error isnotNone:
exc_info = exc_info_from_error(error) else:
exc_info = sys.exc_info()
def _capture_internal_exception(
self, exc_info # type: Any
): # type: (...) -> Any """
Capture an exception that is likely caused by a bug in the SDK
itself.
These exceptions do not end up in Sentry and are just logged instead. """
logger.error("Internal error in sentry_sdk", exc_info=exc_info)
:param crumb: Dictionary with the data as the sentry v7/v8 protocol expects.
:param hint: An optional value that can be used by `before_breadcrumb`
to customize the breadcrumbs that are emitted. """
client, scope = self._stack[-1] if client isNone:
logger.info("Dropped breadcrumb because no client bound") return
max_breadcrumbs = client.options["max_breadcrumbs"] # type: int while len(scope._breadcrumbs) > max_breadcrumbs:
scope._breadcrumbs.popleft()
def start_span(
self,
span=None, # type: Optional[Span]
**kwargs # type: Any
): # type: (...) -> Span """
Create a new span whose parent span is the currently active
span, if any. The return value is the span object that can
be used as a context manager to start and stop timing.
Note that you will not see any span that isnot contained
within a transaction. Create a transaction with
``start_span(transaction="my transaction")`` if an
integration doesn't already do this for you. """
client, scope = self._stack[-1]
kwargs.setdefault("hub", self)
if span isNone:
span = scope.span if span isnotNone:
span = span.new_span(**kwargs) else:
span = Span(**kwargs)
if span.sampled isNoneand span.transaction isnotNone:
sample_rate = client and client.options["traces_sample_rate"] or 0
span.sampled = random.random() < sample_rate
if span.sampled:
max_spans = (
client and client.options["_experiments"].get("max_spans") or 1000
)
span.init_finished_spans(maxlen=max_spans)
def push_scope( # noqa
self, callback=None# type: Optional[Callable[[Scope], None]]
): # type: (...) -> Optional[ContextManager[Scope]] """
Pushes a new layer on the scope stack.
:param callback: If provided, this method pushes a scope, calls
`callback`, and pops the scope again.
:returns: If no `callback` is provided, a context manager that should
be used to pop the scope again. """ if callback isnotNone: with self.push_scope() as scope:
callback(scope) returnNone
def pop_scope_unsafe(self): # type: () -> Tuple[Optional[Client], Scope] """
Pops a scope layer from the stack.
Try to use the context manager :py:meth:`push_scope` instead. """
rv = self._stack.pop() assert self._stack, "stack must have at least one layer" return rv
def start_session(self): # type: (...) -> None """Starts a new session."""
self.end_session()
client, scope = self._stack[-1]
scope._session = Session(
release=client.options["release"] if client elseNone,
environment=client.options["environment"] if client elseNone,
user=scope._user,
)
def end_session(self): # type: (...) -> None """Ends the current session if there is one."""
client, scope = self._stack[-1]
session = scope._session if session isnotNone:
session.close() if client isnotNone:
client.capture_session(session)
self._stack[-1][1]._session = None
This temporarily session tracking for the current scope when called.
To resume session tracking call `resume_auto_session_tracking`. """
self.end_session()
client, scope = self._stack[-1]
scope._force_auto_session_tracking = False
def resume_auto_session_tracking(self): # type: (...) -> None """Resumes automatic session tracking for the current scope if
disabled earlier. This requires that generally automatic session
tracking is enabled. """
client, scope = self._stack[-1]
scope._force_auto_session_tracking = None
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.