Python sentry_sdk.init() Examples
The following are 30
code examples of sentry_sdk.init().
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 also want to check out all available functions/classes of the module
sentry_sdk
, or try the search function
.
Example #1
Source File: logging.py From parsec-cloud with GNU Affero General Public License v3.0 | 10 votes |
def disable_sentry_logging(): sentry_sdk.init(dsn=None)
Example #2
Source File: sentry.py From openSUSE-release-tools with GNU General Public License v2.0 | 6 votes |
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
Source File: platform_android.py From ZeroNet-kivy with GNU General Public License v2.0 | 6 votes |
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 #4
Source File: __init__.py From yet-another-image-bed with GNU General Public License v3.0 | 6 votes |
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 #5
Source File: bootstrap.py From amivapi with GNU Affero General Public License v3.0 | 6 votes |
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 #6
Source File: sentry.py From polyaxon with Apache License 2.0 | 6 votes |
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 #7
Source File: sentry.py From gitmostwanted.com with MIT License | 6 votes |
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 #8
Source File: settings.py From richie with MIT License | 6 votes |
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
Source File: sentry.py From ansibullbot with GNU General Public License v3.0 | 6 votes |
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 #10
Source File: sentry.py From review with Mozilla Public License 2.0 | 6 votes |
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 #11
Source File: outliers.py From ee-outliers with GNU General Public License v3.0 | 6 votes |
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 #12
Source File: sentry.py From openSUSE-release-tools with GNU General Public License v2.0 | 6 votes |
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 #13
Source File: settings.py From marsha with MIT License | 6 votes |
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 #14
Source File: test_client.py From sentry-python with BSD 2-Clause "Simplified" License | 5 votes |
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 #15
Source File: __init__.py From cyberdisc-bot with MIT License | 5 votes |
def main(): """Entry point for poetry script.""" sentry_sdk.init( SENTRY_URL, release=Repo().head.object.hexsha, integrations=[AioHttpIntegration()], ) bot.run(BOT_TOKEN)
Example #16
Source File: sentry.py From donate-wagtail with Mozilla Public License 2.0 | 5 votes |
def pre_setup(cls): super().pre_setup() import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration sentry_sdk.init( dsn=cls.SENTRY_DSN, integrations=[DjangoIntegration()], release=cls.HEROKU_RELEASE_VERSION, environment=cls.SENTRY_ENVIRONMENT )
Example #17
Source File: sentry.py From pyrobud with MIT License | 5 votes |
def init() -> None: """Initializes automatic Sentry error reporting.""" # Use Git commit if possible, otherwise fall back to the version number release = version.get_commit() if release is None: release = __version__ # Skip Sentry initialization if official status has been lost if not git.is_official(): log.warning("Skipping Sentry initialization due to unofficial status") return # Initialize the Sentry SDK using the public client key sentry_sdk.init(PUBLIC_CLIENT_KEY, release=release, before_send=_send_filter)
Example #18
Source File: sentry.py From micromasters with BSD 3-Clause "New" or "Revised" License | 5 votes |
def init_sentry(*, dsn, environment, version, log_level): """ Initializes sentry Args: dsn (str): the sentry DSN key environment (str): the application environment version (str): the version of the application log_level (str): the sentry log level """ def before_send(event, hint): """ Filter or transform events before they're sent to Sentry Args: event (dict): event object hint (dict): event hint, see https://docs.sentry.io/platforms/python/#hints Returns: dict or None: returns the modified event or None to filter out the event """ if 'exc_info' in hint: _, exc_value, _ = hint['exc_info'] if isinstance(exc_value, SHUTDOWN_ERRORS): # we don't want to report shutdown errors to sentry return None return event sentry_sdk.init( dsn=dsn, environment=environment, release=version, before_send=before_send, integrations=[ DjangoIntegration(), CeleryIntegration(), LoggingIntegration(level=log_level), ], )
Example #19
Source File: dbot.py From avrae with GNU General Public License v3.0 | 5 votes |
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 #20
Source File: __init__.py From SempoBlockchain with GNU General Public License v3.0 | 5 votes |
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 #21
Source File: cli.py From raiden-services with MIT License | 5 votes |
def setup_sentry(enable_flask_integration: bool = False) -> None: sentry_dsn = os.environ.get("SENTRY_DSN") environment = os.environ.get("DEPLOY_ENV") if sentry_dsn is not None: log.info("Initializing sentry", dsn=sentry_dsn) integrations: List[Any] = [LoggingIntegration(level=logging.INFO, event_level=None)] if enable_flask_integration: integrations.append(FlaskIntegration()) sentry_sdk.init( dsn=sentry_dsn, integrations=integrations, release=pkg_resources.get_distribution("raiden-services").version, environment=environment, )
Example #22
Source File: __init__.py From shavar with Mozilla Public License 2.0 | 5 votes |
def configure_sentry(config): dsn = config.registry.settings.get('shavar.sentry_dsn') if dsn: sentry_sdk.init( dsn=dsn, integrations=[PyramidIntegration()] )
Example #23
Source File: app.py From solarpi with BSD 3-Clause "New" or "Revised" License | 5 votes |
def register_extensions(app): assets.init_app(app) cache.init_app(app, config={'CACHE_TYPE': 'simple'}) db.init_app(app) debug_toolbar.init_app(app) migrate.init_app(app, db) if ProdConfig.SENTRY_DNS is not None: sentry_sdk.init( dsn=ProdConfig.SENTRY_DNS, integrations=[FlaskIntegration()] ) return None
Example #24
Source File: utils.py From File-Maker with GNU Affero General Public License v3.0 | 5 votes |
def setup_log(sentry_url, print_errors): global logger, production sentry_logging = LoggingIntegration( level=logging.INFO, event_level=logging.INFO ) sentry_sdk.init(dsn=sentry_url, integrations=[sentry_logging]) logger = logging.getLogger(__name__) p_errors = print_errors production = True
Example #25
Source File: test_client.py From sentry-python with BSD 2-Clause "Simplified" License | 5 votes |
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 #26
Source File: main.py From BotListBot with MIT License | 5 votes |
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 #27
Source File: errors.py From website with MIT License | 5 votes |
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 #28
Source File: logging.py From parsec-cloud with GNU Affero General Public License v3.0 | 5 votes |
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__)
Example #29
Source File: app.py From aioshadowsocks with GNU General Public License v3.0 | 5 votes |
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
Source File: sentry_proxy.py From isitfit with Apache License 2.0 | 5 votes |
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)