Django | Sentry for Python (original) (raw)

Learn about using Sentry with Django.

Sentry's Django integration adds support for the Django framework. It enables automatic reporting of errors and exceptions as well as tracing. In order to get started using the integration, you should have a Sentry account and a project set up.

Install sentry-sdk from PyPI with the django extra:

Copied

pip install "sentry-sdk[django]"

To configure the Sentry SDK, initialize it in your settings.py file:

In addition to capturing errors, you can monitor interactions between multiple services or applications by enabling tracing. You can also collect and analyze performance profiles from real users with profiling.

Select which Sentry features you'd like to install in addition to Error Monitoring to get the corresponding installation and configuration instructions below.

Error MonitoringTracingProfiling

settings.py

Copied

import sentry_sdk

sentry_sdk.init(
    dsn="https://examplePublicKey@o0.ingest.sentry.io/0",
    # Add data like request headers and IP for users;
    # see https://docs.sentry.io/platforms/python/data-management/data-collected/ for more info
    send_default_pii=True,
    #  performance
    # Set traces_sample_rate to 1.0 to capture 100%
    # of transactions for tracing.
    traces_sample_rate=1.0,
    #  performance
    #  profiling
    # To collect profiles for all profile sessions,
    # set `profile_session_sample_rate` to 1.0.
    profile_session_sample_rate=1.0,
    # Profiles will be automatically collected while
    # there is an active span.
    profile_lifecycle="trace",
    #  profiling
)

The snippet below includes an intentional error that will be captured by Sentry when triggered. This will allow you to make sure that everything is working as soon as you set it up:

Copied

from django.urls import path

def trigger_error(request):
    division_by_zero = 1 / 0

urlpatterns = [
    path('sentry-debug/', trigger_error),
    # ...
]

The following parts of your Django project are monitored:

By adding DjangoIntegration explicitly to your sentry_sdk.init() call you can set options for DjangoIntegration to change its behavior:

Copied

import django.db.models.signals

import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration

sentry_sdk.init(
    # ...
    integrations=[
        DjangoIntegration(
            transaction_style='url',
            middleware_spans=True,
            signals_spans=True,
            signals_denylist=[
                django.db.models.signals.pre_init,
                django.db.models.signals.post_init,
            ],
            cache_spans=False,
            http_methods_to_capture=("GET",),
        ),
    ],
)

You can pass the following keyword arguments to DjangoIntegration():

Help improve this content
Our documentation is open source and available on GitHub. Your contributions are welcome, whether fixing a typo (drat!) or suggesting an update ("yeah, this would be better").