Python sentry_sdk.init() Examples

The following are 30 code examples for showing how to use sentry_sdk.init(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module sentry_sdk , or try the search function .

Example 1
Project: parsec-cloud   Author: Scille   File: logging.py    License: GNU Affero General Public License v3.0 10 votes vote down vote up
def disable_sentry_logging():
    sentry_sdk.init(dsn=None) 
Example 2
Project: openSUSE-release-tools   Author: openSUSE   File: sentry.py    License: GNU General Public License v2.0 6 votes vote down vote up
def sentry_init(obs_apiurl=None, tags=None):
    try:
        import sentry_sdk
    except ImportError:
        sentry_init.client = sentry_client_dummy()
        return sentry_sdk_dummy()

    sentry_init.client = sentry_sdk.init(
        conf.config.get('sentry_sdk.dsn'),
        environment=conf.config.get('sentry_sdk.environment'),
        release=VERSION)

    with sentry_sdk.configure_scope() as scope:
        scope.set_tag('osc', core.__version__)

        if obs_apiurl:
            scope.set_tag('obs_apiurl', obs_apiurl)
            scope.user = {'username': conf.get_apiurl_usr(obs_apiurl)}

        if tags:
            for key, value in tags.items():
                scope.set_tag(key, value)

    return sentry_sdk 
Example 3
Project: openSUSE-release-tools   Author: openSUSE   File: sentry.py    License: GNU General Public License v2.0 6 votes vote down vote up
def sentry_init(obs_apiurl=None, tags=None):
    try:
        import sentry_sdk
    except ImportError:
        sentry_init.client = sentry_client_dummy()
        return sentry_sdk_dummy()

    sentry_init.client = sentry_sdk.init(
        conf.config.get('sentry_sdk.dsn'),
        environment=conf.config.get('sentry_sdk.environment'),
        release=VERSION)

    with sentry_sdk.configure_scope() as scope:
        scope.set_tag('osc', core.__version__)

        if obs_apiurl:
            scope.set_tag('obs_apiurl', obs_apiurl)
            scope.user = {'username': conf.get_apiurl_usr(obs_apiurl)}

        if tags:
            for key, value in tags.items():
                scope.set_tag(key, value)

    return sentry_sdk 
Example 4
Project: marsha   Author: openfun   File: settings.py    License: MIT License 6 votes vote down vote up
def post_setup(cls):
        """Post setup configuration.

        This is the place where you can configure settings that require other
        settings to be loaded.
        """
        super().post_setup()

        # The DJANGO_SENTRY_DSN environment variable should be set to activate
        # sentry for an environment
        if cls.SENTRY_DSN is not None:
            sentry_sdk.init(
                dsn=cls.SENTRY_DSN,
                environment=cls.ENVIRONMENT,
                release=cls.RELEASE,
                integrations=[DjangoIntegration()],
            )
            with sentry_sdk.configure_scope() as scope:
                scope.set_extra("application", "backend") 
Example 5
Project: ee-outliers   Author: NVISO-BE   File: outliers.py    License: GNU General Public License v3.0 6 votes vote down vote up
def setup_logging():
    """
    Setup the correct logging verbosity and file handlers.
    We also add a logger for Sentry in case it has been set in the environment.
    Sentry allows us to centrally collect error logging during development.
    """
    if os.environ.get("SENTRY_SDK_URL"):
        import sentry_sdk
        sentry_sdk.init(os.environ.get("SENTRY_SDK_URL"))

    # Configuration for which we need access to both settings and logging singletons should happen here
    logging.verbosity = settings.config.getint("general", "log_verbosity")
    logging.logger.setLevel(settings.config.get("general", "log_level"))

    # Log Handlers
    log_file = settings.config.get("general", "log_file")

    if os.path.exists(os.path.dirname(log_file)):
        logging.add_file_handler(log_file)
    else:
        logging.logger.warning(
            'log directory for log file %s does not exist, check your settings! Only logging to stdout', log_file) 
Example 6
Project: review   Author: mozilla-conduit   File: sentry.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def init_sentry():
    distribution = get_distribution("MozPhab")

    sentry_logging = LoggingIntegration(
        level=logging.INFO,
        event_level=None,
        # The default event_level is logging.ERROR, which will report any
        # "logging.error(...)" call to Sentry.  However, we respond to
        # incorrect usage with "logging.error(...)" messages, which we don't
        # want to report to Sentry.
    )
    sentry_sdk.init(
        dsn="https://e8a2a97b86c7472f9308186547aebfa2@sentry.prod.mozaws.net/502",
        integrations=[sentry_logging],
        release=distribution.version,
    ) 
Example 7
Project: ansibullbot   Author: ansible   File: sentry.py    License: GNU General Public License v3.0 6 votes vote down vote up
def initialize_sentry():
    sentry_sdk.init(
        dsn=constants.DEFAULT_SENTRY_DSN,
        environment=constants.DEFAULT_SENTRY_ENV,
        server_name=constants.DEFAULT_SENTRY_SERVER_NAME,
        attach_stacktrace=constants.DEFAULT_SENTRY_TRACE,
        release=constants.ANSIBULLBOT_VERSION,
    ) 
Example 8
Project: richie   Author: openfun   File: settings.py    License: MIT License 6 votes vote down vote up
def post_setup(cls):
        """Post setup configuration.
        This is the place where you can configure settings that require other
        settings to be loaded.
        """
        super().post_setup()

        # The SENTRY_DSN setting should be available to activate sentry for an environment
        if cls.SENTRY_DSN is not None:
            sentry_sdk.init(
                dsn=cls.SENTRY_DSN,
                environment=cls.ENVIRONMENT,
                release=cls.RELEASE,
                integrations=[DjangoIntegration()],
            )
            with sentry_sdk.configure_scope() as scope:
                scope.set_extra("application", "backend") 
Example 9
Project: gitmostwanted.com   Author: kkamkou   File: sentry.py    License: MIT License 6 votes vote down vote up
def register(app: Flask):
    if 'SENTRY_IO' not in app.config:
        return

    def merged_configuration(conf: dict) -> dict:
        defaults = {
            'environment': app.config['ENVIRONMENT'],
            'debug': app.config['DEBUG']
        }
        return {**defaults, **conf}

    for (k, grp) in groupby(app.config['SENTRY_IO']):
        mdl = 'sentry_sdk.integrations.' + k.lower()
        integrations = map(
            lambda key: getattr(import_module(mdl), key.title() + 'Integration')(), grp
        )
        sentry_sdk.init(
            dsn=app.config['SENTRY_IO'][k]['dsn'],
            integrations=list(integrations),
            **merged_configuration(
                app.config['SENTRY_IO'][k]['configuration']
                if 'configuration' in app.config['SENTRY_IO'][k] else {}
            )
        ) 
Example 10
Project: polyaxon   Author: polyaxon   File: sentry.py    License: Apache License 2.0 6 votes vote down vote up
def set_raven_client() -> bool:
    from polyaxon import pkg
    from polyaxon.env_vars.keys import POLYAXON_KEYS_SERVICE
    from polyaxon.managers.cli import CliConfigManager

    cli_config = CliConfigManager.get_config()
    if cli_config and cli_config.log_handler and cli_config.log_handler.decoded_dsn:
        import sentry_sdk

        sentry_sdk.init(
            dsn=cli_config.log_handler.decoded_dsn,
            release=pkg.VERSION,
            environment=cli_config.log_handler.environment,
            server_name=os.environ.get(POLYAXON_KEYS_SERVICE, None),
        )
        return True

    return False 
Example 11
Project: amivapi   Author: amiv-eth   File: bootstrap.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def init_sentry(app):
    """Init sentry if DSN *and* environment are provided."""
    dsn = app.config['SENTRY_DSN']
    env = app.config['SENTRY_ENVIRONMENT']

    if dsn is None and env is None:
        return

    if None in (dsn, env):
        raise ValueError("You need to specify both DSN and environment "
                         "to use Sentry.")

    sentry_sdk.init(
        dsn=dsn,
        integrations=[FlaskIntegration()],
        environment=env,
    ) 
Example 12
Project: yet-another-image-bed   Author: leollon   File: __init__.py    License: GNU General Public License v3.0 6 votes vote down vote up
def create_app(config_name):
    """Factory of Creating app
    @param:
        config_name - all configurations of app
    """
    sentry_sdk.init(
        dsn="",
        integrations=[FlaskIntegration()])
    application = Flask(__name__)
    application.config.from_object(config[config_name])
    config[config_name].init_app(application)

    csrf = CSRFProtect()

    from .image.model import image_db
    from .image.views import image as image_blueprint
    from .image.apis import blueprint as image_api_blueprint

    csrf.init_app(application)
    image_db.init_app(application)
    application.register_blueprint(image_blueprint)
    application.register_blueprint(image_api_blueprint, url_prefix='/api/v1')

    return application 
Example 13
Project: ZeroNet-kivy   Author: HelloZeroNet   File: platform_android.py    License: GNU General Public License v2.0 6 votes vote down vote up
def wrapSentry(mainFunc):
    if not getDebug():
        import traceback
        try:
            import sentry_sdk
            from sentry_sdk import capture_exception
            sentry_sdk.init("https://1cc0c8280fa54361920e75f014add9fe@sentry.io/1406946")
            try:
                mainFunc()
            except Exception as e:
                traceback.print_exc()
                capture_exception(e)
        except Exception as e:
            traceback.print_exc()
            mainFunc()
    else:
        mainFunc()

# Generate a SSL certificate using module M2Crypto,  an existing one will
# be overwritten . 
Example 14
Project: cyberdisc-bot   Author: CyberDiscovery   File: __init__.py    License: MIT License 5 votes vote down vote up
def main():
    """Entry point for poetry script."""
    sentry_sdk.init(
        SENTRY_URL,
        release=Repo().head.object.hexsha,
        integrations=[AioHttpIntegration()],
    )
    bot.run(BOT_TOKEN) 
Example 15
Project: avrae   Author: avrae   File: dbot.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, prefix, description=None, testing=False, **options):
        super(Avrae, self).__init__(prefix, help_command=help_command, description=description, **options)
        self.testing = testing
        self.state = "init"
        self.credentials = Credentials()
        if config.TESTING:
            self.mclient = motor.motor_asyncio.AsyncIOMotorClient(self.credentials.test_mongo_url)
        else:
            self.mclient = motor.motor_asyncio.AsyncIOMotorClient(config.MONGO_URL)
        self.mdb = self.mclient[config.MONGODB_DB_NAME]
        self.rdb = self.loop.run_until_complete(self.setup_rdb())
        self.prefixes = dict()
        self.muted = set()
        self.cluster_id = 0

        # sentry
        if config.SENTRY_DSN is not None:
            release = None
            if config.GIT_COMMIT_SHA:
                release = f"avrae-bot@{config.GIT_COMMIT_SHA}"
            sentry_sdk.init(dsn=config.SENTRY_DSN, environment=config.ENVIRONMENT.title(), release=release)

        # ddb entitlements
        if config.TESTING and config.DDB_AUTH_SERVICE_URL is None:
            self.ddb = BeyondClientBase()
        else:
            self.ddb = BeyondClient(self.loop)

        # launchdarkly
        self.ldclient = AsyncLaunchDarklyClient(self.loop, sdk_key=config.LAUNCHDARKLY_SDK_KEY) 
Example 16
Project: SempoBlockchain   Author: teamsempo   File: __init__.py    License: GNU General Public License v3.0 5 votes vote down vote up
def register_extensions(app):
    db.init_app(app)
    executor.init_app(app)
    basic_auth.init_app(app)

    @app.before_request
    def enable_form_raw_cache():
        # Workaround to allow unparsed request body to be be read from cache
        # This is required to validate a signature on webhooks
        # This MUST go before Sentry integration as sentry triggers form parsing
        if not config.IS_TEST and (
                request.path.startswith('/api/v1/slack/') or request.path.startswith('/api/v1/poli_payments_webhook/')):
            if request.content_length > 1024 * 1024:  # 1mb
                # Payload too large
                return make_response(jsonify({'message': 'Payload too large'})), 413
            request.get_data(parse_form_data=False, cache=True)

    # limiter.init_app(app)

    CORS(app, resources={r"/api/*": {"origins": "*"}})

    celery_app.conf.update(app.config)
    if not config.IS_TEST:
        sentry_sdk.init(app.config['SENTRY_SERVER_DSN'], integrations=[FlaskIntegration()], release=config.VERSION)

    print('celery joined on {} at {}'.format(
        app.config['REDIS_URL'], datetime.utcnow())) 
Example 17
Project: sentry-python   Author: getsentry   File: test_client.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_atexit(tmpdir, monkeypatch, num_messages):
    app = tmpdir.join("app.py")
    app.write(
        dedent(
            """
    import time
    from sentry_sdk import init, transport, capture_message

    def send_event(self, event):
        time.sleep(0.1)
        print(event["message"])

    transport.HttpTransport._send_event = send_event
    init("http://foobar@localhost/123", shutdown_timeout={num_messages})

    for _ in range({num_messages}):
        capture_message("HI")
    """.format(
                num_messages=num_messages
            )
        )
    )

    start = time.time()
    output = subprocess.check_output([sys.executable, str(app)])
    end = time.time()

    # Each message takes at least 0.1 seconds to process
    assert int(end - start) >= num_messages / 10

    assert output.count(b"HI") == num_messages 
Example 18
Project: sentry-python   Author: getsentry   File: test_client.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_broken_mapping(sentry_init, capture_events):
    sentry_init()
    events = capture_events()

    class C(Mapping):
        def broken(self, *args, **kwargs):
            raise Exception("broken")

        __getitem__ = broken
        __setitem__ = broken
        __delitem__ = broken
        __iter__ = broken
        __len__ = broken

        def __repr__(self):
            return "broken"

    try:
        a = C()  # noqa
        1 / 0
    except Exception:
        capture_exception()

    (event,) = events
    assert (
        event["exception"]["values"][0]["stacktrace"]["frames"][0]["vars"]["a"]
        == "<failed to serialize, use init(debug=True) to see error logs>"
    ) 
Example 19
Project: website   Author: jazzband-roadies   File: errors.py    License: MIT License 5 votes vote down vote up
def init_app(app):
    @app.errorhandler(404)
    def page_not_found(e):
        return render_template("error.html"), 404

    @app.errorhandler(403)
    def forbidden(error):
        return render_template("forbidden.html"), 403

    @app.errorhandler(500)
    def error(error):
        return render_template("error.html"), 500

    sentry_sdk.init(
        integrations=[
            LoggingIntegration(
                level=logging.INFO,  # Capture info and above as breadcrumbs
                event_level=logging.ERROR,  # Send errors as events
            ),
            FlaskIntegration(),
            SpinachIntegration(),
            SqlalchemyIntegration(),
        ],
        request_bodies="always",
        with_locals=True,
    ) 
Example 20
Project: isitfit   Author: autofitcloud   File: sentry_proxy.py    License: Apache License 2.0 5 votes vote down vote up
def init(dsn):
    # use default_integrations=False to avoid the AtexitIntegration from displaying a message
    # "Senty is attempting to send ..."
    # https://docs.sentry.io/platforms/python/default-integrations/
    parsed_dsn = MyDsn(dsn)
    sentry_sdk.init(dsn=parsed_dsn, transport=MyTransport, default_integrations=False) 
Example 21
Project: httprunner   Author: httprunner   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
def init_sentry_sdk():
    sentry_sdk.init(
        dsn="https://460e31339bcb428c879aafa6a2e78098@sentry.io/5263855",
        release="httprunner@{}".format(__version__),
    )
    with sentry_sdk.configure_scope() as scope:
        scope.set_user({"id": uuid.getnode()}) 
Example 22
Project: BotListBot   Author: JosXa   File: main.py    License: MIT License 5 votes vote down vote up
def setup_logging():
    sentry_logging = LoggingIntegration(
        level=logging.INFO,  # Capture info and above as breadcrumbs
        event_level=logging.WARNING,  # Send errors as events
    )
    sentry_sdk.init(
        settings.SENTRY_URL,
        integrations=[sentry_logging],
        environment=settings.SENTRY_ENVIRONMENT,
    ) 
Example 23
Project: fbs   Author: mherrmann   File: sentry.py    License: GNU General Public License v3.0 5 votes vote down vote up
def init(self):
        sentry_sdk.init(
            self._dsn, release=self._app_version, environment=self._environment,
            attach_stacktrace=True, default_integrations=False
        )
        # Sentry doesn't give us an easy way to set context information
        # globally, for all threads. We work around this by maintaining a
        # reference to "the" main scope:
        self.scope = sentry_sdk.configure_scope().__enter__()
        self._callback() 
Example 24
Project: pasportaservo   Author: tejoesperanto   File: sentry.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def sentry_init(env=None):
    sentry_sdk.init(
        dsn=get_env_setting('SENTRY_DSN'),
        integrations=[DjangoIntegration()],
        environment={'PROD': "production", 'UAT': "staging"}.get(env, "development"),

        # If you wish to associate users to errors (assuming you are using
        # django.contrib.auth) you may enable sending PII data.
        # send_default_pii=True,
    ) 
Example 25
Project: renku-python   Author: SwissDataScienceCenter   File: exception_handler.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        """Initialize a Sentry client."""
        super().__init__(*args, **kwargs)

        if HAS_SENTRY:
            import sentry_sdk
            sentry_sdk.init() 
Example 26
Project: rssant   Author: anyant   File: main.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_app():
    configure_logging(level=CONFIG.log_level)
    backdoor.setup()
    if CONFIG.sentry_enable:
        sentry_sdk.init(
            dsn=CONFIG.sentry_dsn,
            integrations=[AioHttpIntegration()]
        )
    api = web.Application()
    api.router.add_routes(routes)
    app = web.Application()
    app.add_subapp('/api/v1', api)
    setup_aiojobs(app, limit=5000, pending_limit=5000)
    return app 
Example 27
Project: rssant   Author: anyant   File: sentry.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def sentry_init(dsn=None):
    if dsn:
        sentry_sdk.init(
            dsn=dsn,
            integrations=[AioHttpIntegration()]
        ) 
Example 28
Project: sentry_airflow   Author: getsentry   File: sentry_hook.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, sentry_conn_id="sentry_dsn"):
        ignore_logger("airflow.task")
        ignore_logger("airflow.jobs.backfill_job.BackfillJob")
        executor_name = conf.get("core", "EXECUTOR")

        integrations = [FlaskIntegration(), SqlalchemyIntegration()]

        traces_sample_rate = (
            1
            if os.environ.get("SENTRY_ENABLE_AIRFLOW_APM") in ["true", "True"]
            else 0
        )

        try:
            dsn = None
            conn = self.get_connection(sentry_conn_id)
            dsn = get_dsn(conn)
            sentry_sdk.init(
                dsn=dsn,
                integrations=integrations,
                traces_sample_rate=traces_sample_rate,
            )

        except (AirflowException, exc.OperationalError, exc.ProgrammingError):
            self.log.debug("Sentry defaulting to environment variable.")
            sentry_sdk.init(integrations=integrations, traces_sample_rate=traces_sample_rate)

        if traces_sample_rate is 0:
            TaskInstance._run_raw_task = sentry_patched_run_raw_task
        else:
            self.log.debug("Sentry sending APM spans.")
            TaskInstance._run_raw_task = sentry_patched_run_raw_task_with_span

        TaskInstance._sentry_integration_ = True 
Example 29
Project: aioshadowsocks   Author: Ehco1996   File: app.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _init_sentry(self):
        if not self.use_sentry:
            return
        sentry_sdk.init(dsn=self.sentry_dsn, integrations=[AioHttpIntegration()])
        logging.info("Init Sentry Client...") 
Example 30
Project: parsec-cloud   Author: Scille   File: logging.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def configure_sentry_logging(sentry_url):
    sentry_logging = LoggingIntegration(
        level=logging.WARNING,  # Capture warning and above as breadcrumbs
        event_level=logging.ERROR,  # Send errors as events
    )
    sentry_sdk.init(dsn=sentry_url, integrations=[sentry_logging], release=__version__)