Filtering and Sampling Events

Adding Sentry to your app gives you a great deal of very valuable information about errors and performance you wouldn't otherwise get. And lots of information is good -- as long as it's the right information, at a reasonable volume.

The Sentry SDKs have several configuration options to help you control this, allowing you to both filter out events you don't want and to take a representative sample of those you do.

Note:: The Sentry UI also offers methods to filter events, by using Inbound Filters. We recommend filtering at the client level though, because it removes the overhead of sending events you don't actually want.

Filtering Error Events

Configure your SDK to filter error events by using the beforeSend callback method and configuring, enabling, or disabling integrations.

Using beforeSend

All Sentry SDKs support the beforeSend callback method. beforeSend is called immediately before the event is sent to the server, so it’s the final place where you can edit its data. It receives the event object as a parameter, so you can use that to modify the event’s data or drop it completely (by returning null) based on custom logic and the data available on the event.

In Python a function can be used to modify the event or return a completely new one. If you return None, the event will be discarded.

Copied
import sentry_sdk

def strip_sensitive_data(event, hint):
    # modify event here
    return event

sentry_sdk.init(
    before_send=strip_sensitive_data
)

Note also that breadcrumbs can be filtered, as discussed in our Breadcrumbs documentation.

Event Hints

The before-send callback is passed both the event and a second argument, hint, that holds one or more hints.

Typically a hint holds the original exception so that additional data can be extracted or grouping is affected. In this example, the fingerprint is forced to a common value if an exception of a certain type has been caught:

Copied
import sentry_sdk

def before_send(event, hint):
    if 'exc_info' in hint:
        exc_type, exc_value, tb = hint['exc_info']
        if isinstance(exc_value, DatabaseUnavailable):
            event['fingerprint'] = ['database-unavailable']
    return event

sentry_sdk.init(before_send=before_send)

For information about which hints are available see hints in Python.

When the SDK creates an event or breadcrumb for transmission, that transmission is typically created from some sort of source object. For instance, an error event is typically created from a log record or exception instance. For better customization, SDKs send these objects to certain callbacks (beforeSendbeforeBreadcrumb or the event processor system in the SDK).

Using Hints

Hints are available in two places:

  1. beforeSend / beforeBreadcrumb
  2. eventProcessors

Event and breadcrumb hints are objects containing various information used to put together an event or a breadcrumb. Typically hints hold the original exception so that additional data can be extracted or grouping can be affected.

For events, such as event_idoriginalException, syntheticException (used internally to generate cleaner stack trace), and any other arbitrary data that you attach.

For breadcrumbs, the use of hints is implementation dependent. For XHR requests, the hint contains the xhr object itself; for user interactions the hint contains the DOM element and event name and so forth.

In this example, the fingerprint is forced to a common value if an exception of a certain type has been caught:

Copied
import sentry_sdk

def before_send(event, hint):
    exc_info = hint.get("exc_info")
    if exc_info and isinstance(exc_info[0], DatabaseUnavailable):
        event["fingerprint"] = ["database-unavailable"]

    return event

sentry_sdk.init(
    dsn="https://examplePublicKey@o0.ingest.sentry.io/0",
    before_send=before_send,
)

Hints for Events

originalException
The original exception that caused the Sentry SDK to create the event. This is useful for changing how the Sentry SDK groups events or to extract additional information.

syntheticException
When a string or a non-error object is raised, Sentry creates a synthetic exception so you can get a basic stack trace. This exception is stored here for further data extraction.

Hints for Breadcrumbs

event
For breadcrumbs created from browser events, the Sentry SDK often supplies the event to the breadcrumb as a hint. This, for instance, can be used to extract data from the target DOM element into a breadcrumb.

level / input
For breadcrumbs created from console log interceptions. This holds the original console log level and the original input data to the log function.

response / input
For breadcrumbs created from HTTP requests. This holds the response object (from the fetch API) and the input parameters to the fetch function.

request / response / event
For breadcrumbs created from HTTP requests. This holds the request and response object (from the node HTTP API) as well as the node event (response or error).

xhr
For breadcrumbs created from HTTP requests done via the legacy XMLHttpRequest API. This holds the original xhr object.

Decluttering Sentry

By default the Python SDK captures all error logs as events. If you see a particular kind of error very often that has a logger tag, you can ignore that particular logger entirely. For more information see our logging integration.

Sampling Error Events

To send a representative sample of your errors to Sentry, set the sample_rate option in your SDK configuration to a number between 0 (0% of errors sent) and 1 (100% of errors sent). This is a static rate, which will apply equally to all errors. For example, to sample 25% of your errors:

Copied
import sentry_sdk

sentry_sdk.init(..., sample_rate=0.25)

Note: The error sample rate is not dynamic; changing it requires re-deployment. In addition, setting an SDK sample rate limits visibility into the source of events. Setting a rate limit for your project (which only drops events when volume is high) may better suit your needs.

Filtering Transaction Events

To prevent certain transactions from being reported to Sentry, use the traces_sampler configuration option, which allows you to provide a function to evaluate the current transaction and drop it if it's not one you want. (It also allows you to sample different transactions at different rates.)

Note: The traces_sampler and traces_sample_rate config options are mutually exclusive. If you define a traces_sampler to filter out certain transactions, you must also handle the case of non-filtered transactions by returning the rate at which you'd like them sampled.

In its simplest form, used just for filtering, it looks like this:

Copied
def traces_sampler(sampling_context):
    if "...":
        # Drop this transaction, by setting its sample rate to 0%
        return 0
    else:
        # Default sample rate for all others (replaces traces_sample_rate)
        return 0.1

sentry_sdk.init(
    # ...

    traces_sampler=traces_sampler,
)

To learn more about the traces_sampler option, please see your SDK's performance docs.

Sampling Transaction Events

For Sentry's Performance Monitoring, we recommend sampling your data for two reasons. First, though capturing a single trace involves minimal overhead, capturing traces for every single page load, or every single API request, has the potential to add an undesirable amount of load to your system. Second, enabling sampling allows you to better manage the number of events sent to Sentry, so you can tailor your volume to your organization's needs.

When choosing a sampling rate, the goal is not to collect too much data, but to collect sufficient data so you can draw meaningful conclusions. If you’re not sure what rate to choose, start with a low value and gradually increase it as you learn more about your traffic patterns and volume, until you’ve found a rate that balances performance and volume concerns with data accuracy.

To sample your transactions, either set the traces_sample_rate configuration option to a number between 0 (0% of transactions sent) and 1 (100% of transactions sent), or set the traces_sampler option to a function which will return such a number, varying by transaction.

For example, setting the traces_sample_rate option to 0.2 will cause the SDK to only send 20% of possible transaction events:

Copied
sentry_sdk.init(
    # ...

    traces_sample_rate=0.2,
)

Alternatively, you can provide a traces_sampler function, to sample different transactions at different rates:

Copied
def traces_sampler(sampling_context):
    # Examine provided context data (including parent decision, if any)
    # along with anything in the global namespace to compute the sample rate
    # or sampling decision for this transaction

    if "...":
        # These are important - take a big sample
        return 0.5
    elif "...":
        # These are less important or happen much more frequently - only take 1%
        return 0.01
    elif "...":
        # These aren't something worth tracking - drop all transactions like this
        return 0
    else:
        # Default sample rate
        return 0.1

sentry_sdk.init(
    # ...

    traces_sampler=traces_sampler,
)

To learn more about the traces_sampler option, please see your SDK's performance docs.

You can edit this page on GitHub.