Package: pybrake1
Python exception notifier for AirbrakeInstallationpybrake requires Python 3.6+.pipinstall-UpybrakeConfigurationYoumustset bothproject_id&project_key.To find yourproject_idandproject_keynavigate to your project'sSettingsand copy the values from the right sidebar.importpybrakenotifier=pybrake.Notifier(project_id=123,project_key='FIXME',environment='production')Sending errors to Airbraketry:raiseValueError('hello')exceptExceptionaserr:notifier.notify(err)Sending errors synchronouslyBy default, thenotifyfunction sends errors asynchronously usingThreadPoolExecutorand returns aconcurrent.futures.Future, a synchronous
API is also made available with thenotify_syncfunction:notice=notifier.notify_sync(err)if'id'innotice:print(notice['id'])else:print(notice['error'])Adding custom paramsTo set custom params you can build and send notice in separate steps:notice=notifier.build_notice(err)notice['params']['myparam']='myvalue'notifier.send_notice(notice)You can also add custom params to every error notice before it's sent to Airbrake
with theadd_filterfunction.defmy_filter(notice):notice['params']['myparam']='myvalue'returnnoticenotifier.add_filter(my_filter)Ignoring noticesThere may be some notices/errors thrown in your application that you're not
interested in sending to Airbrake, you can ignore these using theadd_filterfunction.defmy_filter(notice):ifnotice['context']['environment']=='development':# Ignore notices in development environment.returnNonereturnnoticenotifier.add_filter(my_filter)Filtering keysWithkeys_blocklistoption you can specify list of keys containing sensitive information that must be filtered out, e.g.:notifier=pybrake.Notifier(...keys_blocklist=['password',# exact matchre.compile('secret'),# regexp match],)Logging integrationpybrake provides a logging handler that sends your logs to Airbrake.importloggingimportpybrakeairbrake_handler=pybrake.LoggingHandler(notifier=notifier,level=logging.ERROR)logger=logging.getLogger('test')logger.addHandler(airbrake_handler)logger.error('something bad happened')Django integrationFirst, configureproject_idandproject_keyinsettings.py:AIRBRAKE=dict(project_id=123,project_key='FIXME',)Next, activate the Airbrake middleware:MIDDLEWARE=[...'pybrake.middleware.django.AirbrakeMiddleware',]Finally, configure the airbrake logging handler:LOGGING={'version':1,'disable_existing_loggers':False,'handlers':{'airbrake':{'level':'ERROR','class':'pybrake.LoggingHandler',},},'loggers':{'app':{'handlers':['airbrake'],'level':'ERROR','propagate':True,},},}Now you are ready to start reporting errors to Airbrake from your Django app.Flask integrationThe Flask integration leverages Flask signals and therefore requires theblinkerlibrary.fromflaskimportFlaskfrompybrake.middleware.flaskimportinit_appapp=Flask(__name__)app.config['PYBRAKE']=dict(project_id=123,project_key='FIXME',)app=init_app(app)aiohttp integration (python 3.5+)Setup airbrake's middleware and config for your web application:# app.pyfromaiohttpimportwebfrompybrake.middleware.aiohttpimportcreate_airbrake_middlewareairbrake_middleware=create_airbrake_middleware()app=web.Application(middlewares=[airbrake_middleware])app['airbrake_config']=dict(project_id=123,project_key='FIXME',environment='production'# optional)Also, you can pass custom handlers tocreate_airbrake_middleware:# middlewares.pyimportaiohttp_jinja2frompybrake.middleware.aiohttpimportcreate_airbrake_middlewareasyncdefhandle_404(request):returnaiohttp_jinja2.render_template('404.html',request,{})asyncdefhandle_500(request):returnaiohttp_jinja2.render_template('500.html',request,{})defsetup_middlewares(app):airbrake_middleware=create_airbrake_middleware({404:handle_404,500:handle_500})app.middlewares.append(airbrake_middleware)Disabling pybrake logsThe pybrake logger can be silenced by setting the logging level tologging.CRITICAL.importlogginglogging.getLogger("pybrake").setLevel(logging.CRITICAL)Sending route statsnotifier.routes.notifyallows sending route stats to Airbrake. The library
provides integrations with Django and Flask. (your routes are tracked
automatically). You can also use this API manually:frompybrakeimportRouteMetricmetric=RouteMetric(method=request.method,route=route)metric.status_code=response.status_codemetric.content_type=response.headers.get("Content-Type")metric.end_time=time.time()notifier.routes.notify(metric)Sending route breakdownsnotifier.routes.breakdowns.notifyallows sending performance breakdown stats
to Airbrake. You can use this API manually:frompybrakeimportRouteMetricmetric=RouteMetric(method=request.method,route='/things/1',status_code=200,content_type=response.headers.get('Content-Type'))metric._groups={'db':12.34,'view':56.78}metric.end_time=time.time()notifier.routes.breakdowns.notify(metric)Sending query statsnotifier.queries.notifyallows sending SQL query stats to Airbrake. The
library provides integration with Django (your queries are tracked
automatically). You can also use this API manually:notifier.queries.notify(query="SELECT * FROM foos",method=request.method,route=route,start_time=time.time(),end_time=time.time(),)Sending queue statsnotifier.queues.notifyallows sending queue (job) stats to Airbrake. The
library provides integration with Celery (your queues are tracked
automatically). You can also use this API manually:frompybrakeimportQueueMetricmetric=QueueMetric(queue="foo_queue")metric._groups={'redis':24.0,'sql':0.4}notifier.queues.notify(metric)DevelopmentRunning the testspipinstall-rrequirements.txt
pipinstall-rtest-requirements.txt
pytestUploading to PyPIpythonsetup.pysdistuploadRemote configurationEvery 10 minutes the notifier issues an HTTP GET request to fetch remote
configuration. This might be undesirable while running tests. To suppress this
HTTP call, you need to passremote_config=Falseto the notifier.