Python exception notifier for Airbrake

airbrake airbrake Last update: Jul 08, 2022

Python exception notifier for Airbrake

Build Status

Installation

pybrake requires Python 3.6+.

pip install -U pybrake

Configuration

You must set both project_id & project_key.

To find your project_id and project_key navigate to your project'sSettings and copy the values from the right sidebar.

project-idkey

import pybrakenotifier = pybrake.Notifier(project_id=123,                            project_key='FIXME',                            environment='production')

Sending errors to Airbrake

try:    raise ValueError('hello')except Exception as err:    notifier.notify(err)

Sending errors synchronously

By default, the notify function sends errors asynchronously usingThreadPoolExecutor and returns a concurrent.futures.Future, a synchronousAPI is also made available with the notify_sync function:

notice = notifier.notify_sync(err)if 'id' in notice:    print(notice['id'])else:    print(notice['error'])

Adding custom params

To 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 Airbrakewith the add_filter function.

def my_filter(notice):    notice['params']['myparam'] = 'myvalue'    return noticenotifier.add_filter(my_filter)

Ignoring notices

There may be some notices/errors thrown in your application that you're notinterested in sending to Airbrake, you can ignore these using the add_filterfunction.

def my_filter(notice):    if notice['context']['environment'] == 'development':        # Ignore notices in development environment.        return None    return noticenotifier.add_filter(my_filter)

Filtering keys

With keys_blocklist option you can specify list of keys containing sensitive information that must be filtered out, e.g.:

notifier = pybrake.Notifier(    ...    keys_blocklist=[        'password',           # exact match        re.compile('secret'), # regexp match    ],)

Logging integration

pybrake provides a logging handler that sends your logs to Airbrake.

import loggingimport pybrakeairbrake_handler = pybrake.LoggingHandler(notifier=notifier,                                          level=logging.ERROR)logger = logging.getLogger('test')logger.addHandler(airbrake_handler)logger.error('something bad happened')

Disabling pybrake logs

The pybrake logger can be silenced by setting the logging level tologging.CRITICAL.

import logginglogging.getLogger("pybrake").setLevel(logging.CRITICAL)

Sending route stats

notifier.routes.notify allows sending route stats to Airbrake. The libraryprovides integrations with Django and Flask. (your routes are trackedautomatically). You can also use this API manually:

from pybrake import RouteMetricmetric = 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 breakdowns

notifier.routes.breakdowns.notify allows sending performance breakdown statsto Airbrake. You can use this API manually:

from pybrake import RouteMetricmetric = 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 stats

notifier.queries.notify allows sending SQL query stats to Airbrake. Thelibrary provides integration with Django (your queries are trackedautomatically). 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 stats

notifier.queues.notify allows sending queue (job) stats to Airbrake. Thelibrary provides integration with Celery (your queues are trackedautomatically). You can also use this API manually:

from pybrake import QueueMetricmetric = QueueMetric(queue="foo_queue")metric._groups = {'redis': 24.0, 'sql': 0.4}notifier.queues.notify(metric)

Framework Integration

Pybrake provides a ready-to-use solution with minimal configuration for pythonframeworks.

Development

Running the tests

pip install -r requirements.txtpip install -r test-requirements.txtpytest

Uploading to PyPI

python setup.py sdist upload

Remote configuration

Every 10 minutes the notifier issues an HTTP GET request to fetch remoteconfiguration. This might be undesirable while running tests. To suppress thisHTTP call, you need to pass remote_config=False to the notifier.

PRAGMA foreign_keys = off; BEGIN TRANSACTION; COMMIT TRANSACTION; PRAGMA foreign_keys = on;

Subscribe to our newsletter