示例#1
0
文件: sdk.py 项目: webZW/sentry
def _create_noop_hub():
    def transport(event):
        with capture_internal_exceptions():
            metrics.incr('internal.uncaptured.events', skip_internal=False)
            sdk_logger.warn('internal-error.noop-hub')

    return sentry_sdk.Hub(sentry_sdk.Client(transport=transport))
示例#2
0
def init_sentry_client_from_config(raw_config: config.RawConfig,
                                   **kwargs: Any) -> None:
    """Configure the Sentry client.

    This expects one configuration option and can take many optional ones:

    ``sentry.dsn``
        The DSN provided by Sentry. If blank, the reporter will discard events.
    ``sentry.environment`` (optional)
        The environment your application is running in.
    ``sentry.sample_rate`` (optional)
        Percentage of errors to report. (e.g. "37%")
    ``sentry.ignore_errors`` (optional)
        A comma-delimited list of exception names, unqualified (e.g.
        ServerTimeout) or fully qualified (e.g.
        baseplate.observers.timeout.ServerTimeout) to not notify sentry about.
        Note: a minimal list of common exceptions is hard-coded in Baseplate,
        this option only extends that list.

    Example usage::

        init_sentry_client_from_config(app_config)

    :param raw_config: The application configuration which should have
        settings for the error reporter.

    """
    cfg = config.parse_config(
        raw_config,
        {
            "sentry": {
                "dsn":
                config.Optional(config.String, default=None),
                "environment":
                config.Optional(config.String, default=None),
                "sample_rate":
                config.Optional(config.Percent, default=1),
                "ignore_errors":
                config.Optional(config.TupleOf(config.String), default=()),
            }
        },
    )

    if cfg.sentry.dsn:
        kwargs.setdefault("dsn", cfg.sentry.dsn)

    if cfg.sentry.environment:
        kwargs.setdefault("environment", cfg.sentry.environment)

    kwargs.setdefault("sample_rate", cfg.sentry.sample_rate)

    ignore_errors: List[Union[type, str]] = []
    ignore_errors.extend(ALWAYS_IGNORE_ERRORS)
    ignore_errors.extend(cfg.sentry.ignore_errors)
    kwargs.setdefault("ignore_errors", ignore_errors)

    kwargs.setdefault("with_locals", False)

    client = sentry_sdk.Client(**kwargs)
    sentry_sdk.Hub.current.bind_client(client)
示例#3
0
def register(cfg: Optional['CliConfig'] = None):
    global cli_config, client

    if cfg is None:
        from pros.config.cli_config import cli_config as get_cli_config
        cli_config = get_cli_config()
    else:
        cli_config = cfg

    assert cli_config is not None

    if cli_config.offer_sentry is False:
        return

    import sentry_sdk as sentry
    from pros.upgrade import get_platformv2

    client = sentry.Client(
        'https://[email protected]/1226033',
        before_send=prompt_to_send,
        release=ui.get_version()
    )
    sentry.Hub.current.bind_client(client)

    with sentry.configure_scope() as scope:
        scope.set_tag('platformv2', get_platformv2().name)
示例#4
0
 def _get_client(self, dsn):
     client = self._clients_by_dsn.get(dsn)
     if client is None:
         if sentry_sdk is None:
             logger.warning('sentry_sdk is not installed')
             return None
         client = sentry_sdk.Client(dsn)
         self._clients_by_dsn[dsn] = client
     return client
示例#5
0
def get_exception_event():
    event = {}

    def transport(e):
        nonlocal event
        event = e

    client = sentry_sdk.Client(transport=transport)
    hub = sentry_sdk.Hub(client)
    hub.capture_exception()

    assert event
    return event
示例#6
0
def _sentry_client(
    disabled: bool = False,
) -> sentry_sdk.Client:
    """
    Initialize sentry. You can override the default values with the following env vars:
    1. CORTEX_TELEMETRY_SENTRY_DSN
    2. CORTEX_TELEMETRY_SENTRY_ENVIRONMENT
    3. CORTEX_TELEMETRY_DISABLE
    """

    dsn = CORTEX_TELEMETRY_SENTRY_DSN
    environment = CORTEX_TELEMETRY_SENTRY_ENVIRONMENT

    if disabled or os.getenv("CORTEX_TELEMETRY_DISABLE", "").lower() == "true":
        return

    if os.getenv("CORTEX_TELEMETRY_SENTRY_DSN", "") != "":
        dsn = os.environ["CORTEX_TELEMETRY_SENTRY_DSN"]

    if os.getenv("CORTEX_TELEMETRY_SENTRY_ENVIRONMENT", "") != "":
        environment = os.environ["CORTEX_TELEMETRY_SENTRY_ENVIRONMENT"]

    client = sentry_sdk.Client(
        dsn=dsn,
        environment=environment,
        release=CORTEX_VERSION,
        ignore_errors=[CortexBinaryException],  # exclude CortexBinaryException exceptions
        in_app_include=["cortex"],  # for better grouping of events in sentry
        attach_stacktrace=True,
        default_integrations=False,  # disable all default integrations
        auto_enabling_integrations=False,
        integrations=[
            DedupeIntegration(),  # prevent duplication of events
            StdlibIntegration(),  # adds breadcrumbs (aka more info)
            ModulesIntegration(),  # adds info about installed modules
        ],
        # debug=True,
    )

    return client
示例#7
0
    def send_event(self, project_id, payload=None):
        if payload is None:
            payload = {"message": "Hello, World!"}

        if isinstance(payload, dict):
            client = sentry_sdk.Client(self.dsn, default_integrations=False)
            client.capture_event(payload)
            client.close()
        elif isinstance(payload, bytes):
            response = self.post(
                "/api/%s/store/" % project_id,
                data=payload,
                headers={
                    "Content-Type":
                    "application/octet-stream",
                    "X-Sentry-Auth":
                    ("Sentry sentry_version=5, sentry_timestamp=1535376240291, "
                     "sentry_client=raven-node/2.6.3, "
                     "sentry_key={}".format(self.dsn_public_key)),
                },
            )
            response.raise_for_status()
        else:
            raise ValueError(f"Invalid type {type(payload)} for payload.")
示例#8
0
 def inner(*a, **kw):
     hub = sentry_sdk.Hub.current
     client = sentry_sdk.Client(*a, **kw)
     client.options["_experiments"]["fast_serialize"] = fast_serialize
     hub.bind_client(client)
     monkeypatch_test_transport(sentry_sdk.Hub.current.client)
示例#9
0
 def inner(*a, **kw):
     hub = sentry_sdk.Hub.current
     client = sentry_sdk.Client(*a, **kw)
     hub.bind_client(client)
     monkeypatch_test_transport(sentry_sdk.Hub.current.client)
示例#10
0
        passed=passed,
        messages=messages,
        awaiting_input=awaiting_input,
        output=output,
        output_parts=output_parts,
        birdseye_objects=birdseye_objects,
        error=error,
    )
    # Check that JSON encoding works here
    # because failures in the queue pickling are silent
    json_pickler.dumps(result)
    return result


# Import eagerly
sentry_sdk.Hub(sentry_sdk.Client(transport=lambda e: None))


def get_exception_event():
    event = {}

    def transport(e):
        nonlocal event
        event = e

    client = sentry_sdk.Client(transport=transport)
    hub = sentry_sdk.Hub(client)
    hub.capture_exception()

    assert event
    return event
示例#11
0
from types import ModuleType
from typing import Any, Callable, Dict, List, Optional

import sentry_sdk
import wrapt
from sentry_sdk.integrations import aws_lambda

from . import config

# https://docs.sentry.io/error-reporting/configuration/?platform=python#common-options
sentry_client = sentry_sdk.Hub(
    sentry_sdk.Client(
        dsn=
        "https://[email protected]/5469393",
        release=f"sentiment_flanders@{config.__version__}",
        environment=config.get_workspace(),
        traces_sample_rate=1.0,
        # https://github.com/getsentry/sentry-python/issues/227
        integrations=[aws_lambda.AwsLambdaIntegration()],
    ))


@wrapt.decorator
def log_function_with_sentry(wrapped: Callable[..., Any], instance: Any,
                             args: List[Any], kwargs: Dict[str, Any]) -> Any:
    """Attaches Sentry integrations to a function."""
    with sentry_client:
        try:
            return wrapped(*args, **kwargs)
        except Exception as e:
            sentry_sdk.capture_exception(e)
示例#12
0
def get_sentry_client(sentry_dsn):
    return sentry_sdk.Client(sentry_dsn, release=__version__)