Opbeat is joining forces with Elastic – Learn more about Elastic APM

Get started with Django

Getting Opbeat set up for your Django project is easy, and there are various ways you can tweak it to fit to your needs.



  • pip
  • simplejson (Only if you’re using Python 2.6)

Install the Opbeat module using pip:

$ pip install opbeat

or add it to your project’s requirements.txt file.

Note: If you’re using Django with uwsgi, make sure to enable threads.


Set up the Opbeat module in Django with these two steps:

  1. Add opbeat.contrib.django to INSTALLED_APPS in your settings:

        # ...
  2. Find your IDs and token on the app’s settings page on Opbeat.com. Add them to your settings file:

    OPBEAT = {
        'APP_ID': '<APP-ID>',

    or as environment variables:


You now have basic error logging set up, and everything resulting in a 500 HTTP status code will be reported to Opbeat.

Performance Metrics

To send metrics to Opbeat, simply add our application metrics middleware to your MIDDLEWARE_CLASSES:

    # ...

Make sure that it is the first middleware in the list.

Instrumenting custom Python code

To gain further insights into the performance of your code, please see instrumenting custom code.

Ignoring specific views

You can use the TRANSACTIONS_IGNORE_PATTERNS configuration option to ignore specific views. The list given should be a list of regular expressions which are matched against the transaction name used in the Opbeat user interface:


This would ignore any requests using the OPTIONS method and any requests containing views.api.v2.

Note: make sure you use version 3.3.4 or newer of the Opbeat module for this to work.

Enabling and disabling logging

The simplest way to disable Opbeat is to set Django’s DEBUG option to True in your development configuration. No errors or metrics will be logged to Opbeat.

However, if during debugging you would like to force logging of errors to Opbeat, then you can set DEBUG to True inside of the Opbeat configuration dictionary, like this:

   'APP_ID': '<APP-ID>',
   'DEBUG': True,


For fine-grained control over logging use Python’s built-in logging module. If you are new to how the logging module works together with Django, read more in the Django documentation.

An example of how your LOGGING setting could look:

    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
    'handlers': {
        'opbeat': {
            'level': 'WARNING',
            'class': 'opbeat.contrib.django.handlers.OpbeatHandler',
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'verbose'
    'loggers': {
        'django.db.backends': {
            'level': 'ERROR',
            'handlers': ['console'],
            'propagate': False,
        'mysite': {
            'level': 'WARNING',
            'handlers': ['opbeat'],
            'propagate': False,
        # Log errors from the Opbeat module to the console (recommended)
        'opbeat.errors': {
            'level': 'ERROR',
            'handlers': ['console'],
            'propagate': False,

With this configuration, logging can be done like this in any module in the myapp django app:

You can now use the logger in any module in the myapp django app, for instance myapp/views.py:

import logging
logger = logging.getLogger('mysite')

    instance = MyModel.objects.get(pk=42)
except MyModel.DoesNotExist:
        'Could not find instance, doing something else',

Note that exc_info=True adds the exception info to the data that gets sent to Opbeat. Without it, only the message gets sent.

Extra data

If you want to send more data to Opbeat than what you get with the Opbeat module by default, logging can be done like so:

import logging
logger = logging.getLogger('mysite')

    instance = MyModel.objects.get(pk=42)
except MyModel.DoesNotExist:
        'There was some crazy error',
            'datetime': str(datetime.now()),

the Extra tab on detail page for the error group will now have the extra field datetime.

Sanitizing data (removing sensitive information)

Sometimes it is also necessary to sanitize the data, e.g. remove sensitive data.

To do this with the Opbeat module, you create Processor.

This is an example of a Processor where we remove the function that caused the error:

from opbeat.processors import Processor

class MyProcessor(Processor):
    def process(self, data, **kwargs):
        # 'data' is a dictionary
        if 'extra' in data:
            if 'funcName' in data['extra']:
                data['extra'].pop('funcName', None)
        return data

In this case, update your OPBEAT settings like this:

    'APP_ID': '<APP-ID>',

Note that we recommend you use 'opbeat.processors.SanitizePasswordsProcessor' (on by default) as this ensures that passwords and secrets get masked.

Logging Celery tasks

For a general guide on how to set up Django with Celery, head over to Celery’s Django documentation.

If you followed Celery’s docs, you should now have a celery.py in your project folder. Add the following code to the bottom of celery.py to integrate Opbeat with Celery:

from opbeat.contrib.django.models import client, logger, register_handlers
from opbeat.contrib.celery import register_signal

except Exception as e:
    logger.exception('Failed installing celery hook: %s' % e)

if 'opbeat.contrib.django' in settings.INSTALLED_APPS:

What kind of errors are reported to Opbeat?

In the default setup, only unhandled exceptions are reported to Opbeat. Generally speaking, this includes all exceptions that result in a HTTP 500 error.

HTTP errors with status codes in the 400 range are not reported by default. This includes “404 Not Found” errors as well as “403 Forbidden” errors, which are, amongst other reasons, returned when CSRF verification fails.

If you want to log HTTP 404 errors, the next section will help you. For more advanced requirements, you can hook into Django’s extensive logging framework as described above and in the Django docs.

Logging “HTTP 404 Not Found” Errors

By default, Opbeat does not log HTTP 404 errors. If you wish to log these errors, add 'opbeat.contrib.django.middleware.Opbeat404CatchMiddleware' to MIDDLEWARE_CLASSES in your settings:

    # ...
    # ...

Note that this middleware respects Django’s IGNORABLE_404_URLS setting.

Available settings

Below are all the available settings for the OPBEAT dictionary and their default values.

    # ID for the organization

    # ID of the app
    'APP_ID': '<APP-ID>',

    # Secret for the organization

    # Enable the Opbeat module when the Django configuration DEBUG=True
    'DEBUG': False,

    # By default Opbeat only looks at modules in INSTALLED_APPS for drilling
    # down where an exception is located
    'INCLUDE_PATHS': [],

    # Extending this allow you to ignore module prefixes when we attempt to
    # discover which function an error comes from (typically a view)
    'EXCLUDE_PATHS': [],

    # List of exceptions types to be filtered out. Those won't be sent to the server.
    # It accepts both qualified and non qualified names (e.g.: 'KeyError' and 'exceptions.KeyError')

    # How many seconds to wait for a response from the Opbeat servers before
    # timing out.
    'TIMEOUT': 5,

    # The hostname of the server emitting the logs
    'HOSTNAME': socket.gethostname(),

    # Automatically log frame stacks from all ``logging`` messages.
    'AUTO_LOG_STACKS': False,

    # The maximum length to store of a string-like structure.

    # The maximum number of elements to store for a list-like structure.
    'MAX_LENGTH_LIST': 50,

    # Client-side data processors to apply

    # How often to send app performance data to Opbeat (in seconds)

    # If data should be sent to Opbeat asynchronously in a separate thread
    'ASYNC': True,

    # Ignore views that match the specified regexp patterns

Disable Opbeat during tests

To prevent Opbeat from sending any data to Opbeat during tests, set the OPBEAT_DISABLE_SEND environment variable to true, e.g.:

OPBEAT_DISABLE_SEND=true python manage.py test

Note: make sure you use version 3.1.2 or newer of the Opbeat module for this to work.


Opbeat comes with a Django command that helps troubleshooting your setup. To check your configuration, run

python manage.py opbeat check

To send a test exception using the current settings, run

python manage.py opbeat test

If the command succeeds in sending a test exception, it will print a URL to the error on Opbeat:

python manage.py opbeat test

Trying to send a test error to Opbeat using these settings:

APP_ID:             <APP_ID>
SERVERS:            https://intake.opbeat.com

INFO Logged error at https://opbeat.com/<your-organization>/<your-app>/errors/shortcut/<error-id>
Success! We tracked the error successfully! You should be able to see it in a few seconds at the above URL

Supported Django and Python versions

Opbeat supports the following Django versions:

  • 1.4
  • 1.5
  • 1.6
  • 1.7
  • 1.8
  • 1.9
  • 1.10

and the following Python versions:

  • 2.7
  • 3.3
  • 3.4
  • 3.5