Basic Usage

This gives a basic overview of how to use the raven client with Python directly.

Capture an Error

The most basic use for raven is to record one specific error that occurs:

Copied
from raven import Client

client = Client('https://examplePublicKey@o0.ingest.sentry.io/0')

try:
    1 / 0
except ZeroDivisionError:
    client.captureException()

Reporting an Event

To report an arbitrary event you can use the capture() method. This is the most low-level method available. In most cases you would want to use the captureMessage() method instead however which directly reports a message:

Copied
client.captureMessage('Something went fundamentally wrong')

Adding Context

The raven client internally keeps a thread local mapping that can carry additional information. Whenever a message is submitted to Sentry that additional data will be passed along.

For instance if you use a web framework, you can use this to inject additional information into the context. The basic primitive for this is the context attribute. It provides a merge() and clear() function that can be used:

Copied
def handle_request(request):
    client.context.merge({'user': {
        'email': request.user.email
    }})
    try:
        ...
    finally:
        client.context.clear()

Additionally starting with Raven 5.14 you can bind the context to the current thread to enable crumb support by calling activate(). The deactivation happens upon calling clear(). This can also be achieved by using the context object with the with statement. This is needed to enable breadcrumb capturing. Framework integrations typically do this automatically.

These two examples are equivalent:

Copied
def handle_request(request):
    client.context.activate()
    client.context.merge({'user': {
        'email': request.user.email
    }})
    try:
        ...
    finally:
        client.context.clear()

With a context manager:

Copied
def handle_request(request):
    with client.context:
        client.context.merge({'user': {
            'email': request.user.email
        }})
        try:
            ...
        finally:
            client.context.clear()

Testing the Client

Once you’ve got your server configured, you can test the Raven client by using its CLI:

Copied
raven test https://examplePublicKey@o0.ingest.sentry.io/0

If you’ve configured your environment to have SENTRY_DSN available, you can simply drop the optional DSN argument:

Copied
raven test

You should get something like the following, assuming you’re configured everything correctly:

Copied
raven test sync+https://examplePublicKey@o0.ingest.sentry.io/0
Using DSN configuration:
  sync+https://examplePublicKey@o0.ingest.sentry.io/0

Client configuration:
  servers        : https://sentry.io/api/api/store/
  project        : 0
  public_key     : examplePublicKey
  secret_key     : exampleSecretKey

Sending a test message... success!