How to send Exceptions to sentry for a django project

10.2k Views Asked by At

Following the Sentry Django guide I've setup my project and deployed it.

So I configure RAVEN_CONFIG with the SENTRY_DSN value and release values, and include raven.contrib.django.raven_compat in my INSTALLED_APPS.

I've confirmed that with this configuration the following command will properly generate a message in sentry.

python manage.py raven test

However, I've created the following django view to raise an exception as an alternative way to confirm that sentry is working, and when I hit this view, I get a 500 response, but nothing shows up in sentry.

app1/views.py

def error(request):
    x = 1/0  # error for sentry testing

My expectation is that any exception (including 500 errors) that occurs in django will be sent to sentry without the need to use logging.

Is my understanding of the raven sentry configuration wrong? Or, do I need to configure something else?

I am using the LOGGING setting of django, but at the moment I don't care if these messages 'error' or otherwise are sent to sentry. My main goal at the moment is to catch and send any exception that occurs to sentry.

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': '{asctime} [{levelname:5}] ({name}) {funcName}: {message}',
            'style': '{',
        }
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'standard',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'level': DJANGO_CORE_LOG_LEVEL,  # Change to DEBUG to see db queries
        },
        'app1': {
            'handlers': ['console'],
            'level': DJANGO_LOG_LEVEL,
            'propagate': True,
        },
        'app2': {
            'handlers': ['console'],
            'level': DJANGO_LOG_LEVEL,
            'propagate': True,
        }
    },
}

UPDATE

I've managed to get the app1.views.error view to report an error to sentry when using runserver locally, but after updating the configuration and deploying it's still not working when deployed. (manage raven test does)

5

There are 5 best solutions below

5
Mehran On

From the sentry docs

LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'root': {
    'level': 'WARNING',
    'handlers': ['sentry'],
},
'formatters': {
    'verbose': {
        'format': '%(levelname)s  %(asctime)s  %(module)s '
                  '%(process)d  %(thread)d  %(message)s'
    },
},
'handlers': {
    'sentry': {
        'level': 'ERROR', # To capture more than ERROR, change to WARNING, INFO, etc.
        'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler',
        'tags': {'custom-tag': 'x'},
    },
    'console': {
        'level': 'DEBUG',
        'class': 'logging.StreamHandler',
        'formatter': 'verbose'
    }
},
'loggers': {
    'django.db.backends': {
        'level': 'ERROR',
        'handlers': ['console'],
        'propagate': False,
    },
    'raven': {
        'level': 'DEBUG',
        'handlers': ['console'],
        'propagate': False,
    },
    'sentry.errors': {
        'level': 'DEBUG',
        'handlers': ['console'],
        'propagate': False,
    },
},

}

Link to doc: https://docs.sentry.io/clients/python/integrations/django/

EDIT: From the comment

try:
    do something
except Exception:
    from raven.contrib.django.raven_compat.models import client
    client.captureException()

if you don't want to do this manually and want sentry logging to occur anytime an exception block is triggered anywhere in your project, use the logging based solution above.

1
uedemir On

As @Mehran said after configuration of your LOGGING in settings.py, you will be able to use logging. Let's assume that you have example in loggers in configuration like;

'loggers': {        
    'example': {
        'handlers': ['console', 'sentry'],
        'level': 'DEBUG',
        'propagate': False
    }
}

Then;

import logging

logger = logging.getLogger("example")

def test():
    try:
       # some staff
    except Exception as error:
       logger.error("Custom Error Message %s" %error)

logger also have warn, info etc.

0
Zephaniah Grunschlag On

It is also possible to post directly to your Sentry DSN without using any of the Sentry libraries, but using pure requests. This can be useful if you're running a version of Python or Django that isn't compatible with Sentry's latest DSN.

I've posted a code for this -including an example test- here

0
N1ngu On

Just checking in to say that the other answers are totally outdated.

The raven library has been deprecated in favor of sentry-sdk and setting this up does not involve mangling the logging configuration anymore, since a default logging integration will already spy on any logger call.

Just do

import sentry_sdk.integrations.django

sentry_sdk.init(
    integrations=[sentry_sdk.integrations.django.DjangoIntegration()],
)

in your settings.py and you are good to go (remember to export a SENTRY_DSN variable and whatnot).

See https://docs.sentry.io/platforms/python/guides/django/#configure

0
Mehdi Zare On

Updated Sentry documents mention that with Django integration, you don't need to explicitly define LOGGER in settings.py:

import logging

logging.error("Test error event", extra=dict(bar=43))