Python
Installing Airbrake in a Python application
We’re sick of bad software. Airbrake’s goal is to help developers produce better software faster so that we can get back to enjoying technology. Any python error or panic can be sent to the Airbrake dashboard using Pybrake SDK. The library is very small and has very little overhead.
Key Features
- Simple to install and configure
- Python Error Detection with Full Stack Traces
- Monitoring Python’s performance such as HTTP route statistics, SQL queries, and Job execution statistics.
- Filtering Python Errors, severity and control notification thresholds.
- Add extra context to errors before they are sent
- Integrates with your existing logger
- Asynchronous reporting
- Resends the Error notice or Performance data if the Airbrake Server malfunctions. Several configurations must be made as shown below. (Have a question? Look here at FAQ)
- Support for environments
Supported Frameworks
Pybrake provides a ready-to-use solution with minimal configuration for python frameworks.
AIOHTTP
BottlePy
Celery
CherryPy
Django
Falcon
FastAPI
Flask
Hug
Masonite
Morepath
Pycnic
Pyramid
Sanic
Starlette
Tornado
Turbogears
Installation & Configuration
What version of Python are you using?
The version of Python your app is using determines which installation instructions to follow.
The pybrake notifier supports Python 3.6 and above.
pip install -U pybrake
Configuration
To add Pybrake to your application project_id
& project_key
are
required, to find it browse to your project’s Settings and
copy the data from the right sidebar of the Airbrake portal.
import pybrake
notifier = pybrake.Notifier(project_id=123,
project_key='FIXME',
environment='production')
Additional Settings
List of Parameter Notifier will expect
Configuration parameter which can configure different functionality by Notifier
Parameter Name | Type | Description | Required | Default Value |
---|---|---|---|---|
project_id | Int | Integer Airbrake project id from Airbrake.io | Yes | |
project_key | String | Secret key of Airbrake project in string format from Airbrake.io | Yes | |
performance_stats | Boolean | Enable/disable performance monitoring if False, pybrake will not send any monitoring stats to Airbrake.io. Which include (route, query, & queue). | No | True |
query_stats | Boolean | Enable/disable query stats monitoring if False, pybrake will not send query monitoring stats to Airbrake.io. | No | True |
queue_stats | Boolean | Enable/disable queue stats monitoring if False, pybrake will not send queue monitoring stats to Airbrake.io. | No | True |
max_queue_size | Int | Maximum number for thread pool queue size | No | 1000 |
max_workers | Int | Maximum number of thread pool can make by Notifier | No | number CPU count * 5 |
root_directory | String | Root directory path of project to finf git directory | No | PROJECT_DIR |
environment | String | Project running environment, Like: development, testing, production. Can make own environment. | No | production |
keys_blocklist | List | To transmit an airbrake on an error notification, a list of sensitive parameter’s information must be blocked or filterout. | No | [re.compile(“password”), re.compile(“secret”)] |
remote_config | Boolean | Configure pybrake using Airbrake.io, a remote server. If True, pybrake will ignore any configutation done during the initialization of the notifier. | No | False |
backlog_enabled | Boolean | If backlog_enabled is set as true then pybrake will manage failed performance stats and errors and periodically sends them asynchronously in the background (every 1 minute). Default value: False | No | False |
max_backlog_size | Int | Set up the length of failed stats backlog queue. Default value: 100. Up to 100 backlog items for errors and 100 backlog items for performance stats (Shared with Routes, Route breakdown, query, queue stats). In the event that the backlog queue becomes full, the item will be replaced and an error will be recorded. | No | 100 |
Error Monitoring
Sending errors to Airbrake
try:
raise ValueError('hello')
except Exception as err:
notifier.notify(err)
Sending errors synchronously
The notify
function communicates errors asynchronously via
ThreadPoolExecutor
and produces a concurrent.futures.Future
by default;
however, the notify_sync
function provides a synchronous API
notice = notifier.notify_sync(err)
if 'id' in notice:
print(notice['id'])
else:
print(notice['error'])
Adding custom params
You can design and send an error notification in two phases to set custom parameters
notice = notifier.build_notice(err)
notice['params']['myparam'] = 'myvalue'
# Asynchronously
notifier.send_notice(notice)
# Synchronously
notifier.send_notice_sync(notice)
You can also use the add_filter
function to add custom params to every
error notice before it’s sent to Airbrake instead of sending it manually
def my_filter(notice):
notice['params']['myparam'] = 'myvalue'
return notice
notifier.add_filter(my_filter)
Linking errors to routes
You can link error notices with the routes by setting the route e.g. /hello and httpMethod e.g. GET, POST in the custom parameters for error notices. For example:
notice = notifier.build_notice(err)
notice['context']["route"] = "route-name"
notice['context']["httpMethod"] = "http-method-name"
Set severity
Severity allows
categorizing how severe an error is. By default, it’s set to error
. To
redefine severity, simply overwrite context/severity
of a notice object. For
example:
notice = notifier.build_notice(err)
notice['params']['myparam'] = 'myvalue'
notice['context']["severity"] = "critical"
# Asynchronously
notifier.send_notice(notice)
# Synchronously
notifier.send_notice_sync(notice)
Ignoring notices
You can use the add_filter
function to disregard any notifications or
faults that are issued in your application that you don’t want to submit to Airbrake
def my_filter(notice):
if notice['context']['environment'] == 'development':
# Ignore notices in development environment.
return None
return notice
notifier.add_filter(my_filter)
Filtering/Blocking keys data
You can specify a list of keys containing sensitive information that must
be filtered out using the keys_blocklist
option
notifier = pybrake.Notifier(
...
keys_blocklist=[
'password', # exact match
re.compile('secret'), # regexp match
],
)
Logging integration
Pybrake has a logging handler that transmits all of your logs to Airbrake
import logging
import pybrake
airbrake_handler = pybrake.LoggingHandler(notifier=notifier,
level=logging.ERROR)
logger = logging.getLogger('test')
logger.addHandler(airbrake_handler)
logger.error('something bad happened')
Disabling pybrake logs
Setting the logging level to logging.CRITICAL
will mute the pybrake logger.
import logging
logging.getLogger("pybrake").setLevel(logging.CRITICAL)
Performance Monitoring
You can read more about our Performance Monitoring offering in our docs.
Sending route stats
The function notifier.routes.notify
allows you to transmit route statistics
to Airbrake. Below listed frameworks are supported by the library for now.
(Your routes are automatically monitored.) This API can also be used manually.:
from pybrake import RouteMetric
metric = RouteMetric(method=request.method, route=route)
metric.status_code = response.status_code
metric.content_type = response.headers.get("Content-Type")
metric.end_time = time.time()
notifier.routes.notify(metric)
Sending route breakdowns
Airbrake can get performance breakdown stats through the
notifier.routes.breakdowns.notify
command. This API can be used manually:
from pybrake import RouteMetric
metric = 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
The function notifier.queries.notify
allows you to transmit SQL query
statistics to Airbrake. The library integrates with below listed frameworks
(your requests are automatically recorded).
Using SQLAlchemy
Using Django ORM
Using Masonite ORM
This API can also be used manually:
notifier.queries.notify(
query="SELECT * FROM foos",
method=request.method,
route=route,
start_time=time.time(),
end_time=time.time(),
)
Sending queue stats
The function notifier.queues.notify
allows you to submit queue (task)
statistics to Airbrake. Celery & Masonite are both integrated with the library,
so your queues are automatically tracked. This API can also be used manually:
from pybrake import QueueMetric
metric = QueueMetric(queue="foo_queue")
metric._groups = {'redis': 24.0, 'sql': 0.4}
notifier.queues.notify(metric)
Notes
Exception limit
The maximum size of an exception is 64KB. Exceptions that exceed this limit will be truncated to fit the size.
Taking Pybrake further
Now that you have configured Airbrake to report exceptions from your Python 3 and above app, we recommend you add extra context to your errors and add Airbrake to your existing logger. Please visit the Pybrake GitHub repo for the full list of notifier features.