# Sampling | Sentry for Unreal Engine

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.

## [Sampling Error Events](https://docs.sentry.io/platforms/unreal/configuration/sampling.md#sampling-error-events)

To send a representative sample of your errors to Sentry, set the `SampleRate` 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:

```cpp
#include "SentrySettings.h"

FConfigureSettingsDelegate SettingsDelegate;
SettingsDelegate.BindDynamic(this, &USomeClass::ConfigureSettingsDelegate);

void USomeClass::ConfigureSettingsDelegate(USentrySettings* Settings)
{
    Settings->SampleRate = 0.25f;
}

...

USentrySubsystem* SentrySubsystem = GEngine->GetEngineSubsystem<USentrySubsystem>();

SentrySubsystem->InitializeWithSettings(SettingsDelegate);
```

The error sample rate defaults to `1`, meaning all errors are sent to Sentry.

Changing the error sample rate 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.

## [Sampling Transaction Events](https://docs.sentry.io/platforms/unreal/configuration/sampling.md#sampling-transaction-events)

We recommend sampling your transactions for two reasons:

1. Capturing a single trace involves minimal overhead, but capturing traces for *every* level loaded or *every* API request may add an undesirable load to your system.

2. 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.

Choose a sampling rate with the goal of finding a balance between performance and volume concerns with data accuracy. You don't want to collect *too* much data, but you want to collect sufficient data from which to 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.

## [Configuring the Transaction Sample Rate](https://docs.sentry.io/platforms/unreal/configuration/sampling.md#configuring-the-transaction-sample-rate)

The Sentry SDKs have two configuration options to control the volume of transactions sent to Sentry, allowing you to take a representative sample:

1. Uniform sample rate (`TracesSampleRate`):

   * Provides an even cross-section of transactions, no matter where in your app or under what circumstances they occur.
   * Uses default [inheritance](https://docs.sentry.io/platforms/unreal/configuration/sampling.md#inheritance) and [precedence](https://docs.sentry.io/platforms/unreal/configuration/sampling.md#precedence) behavior

2. Sampling function (`TracesSampler`) which:

   * Samples different transactions at different rates
   * [Filters](https://docs.sentry.io/platforms/unreal/configuration/filtering.md) out some transactions entirely
   * Modifies default [precedence](https://docs.sentry.io/platforms/unreal/configuration/sampling.md#precedence) and [inheritance](https://docs.sentry.io/platforms/unreal/configuration/sampling.md#inheritance) behavior

By default, none of these options are set, meaning no transactions will be sent to Sentry. You must set one of the options to start sending transactions.

### [Setting a Uniform Sample Rate](https://docs.sentry.io/platforms/unreal/configuration/sampling.md#setting-a-uniform-sample-rate)

To do this, set the `TracesSampleRate` option to a number between 0 and 1. With this option set, every transaction created will have that percentage chance of being sent to Sentry. For example, if you set `TracesSampleRate` to `0.2`, approximately 20% of your transactions will be recorded and sent. That looks like this:

```cpp
#include "SentrySettings.h"

FConfigureSettingsDelegate SettingsDelegate;
SettingsDelegate.BindDynamic(this, &USomeClass::ConfigureSettingsDelegate);

void USomeClass::ConfigureSettingsDelegate(USentrySettings* Settings)
{
    Settings->TracesSampleRate = 0.2f;
}

...

USentrySubsystem* SentrySubsystem = GEngine->GetEngineSubsystem<USentrySubsystem>();

SentrySubsystem->InitializeWithSettings(SettingsDelegate);
```

### [Setting a Sampling Function](https://docs.sentry.io/platforms/unreal/configuration/sampling.md#setting-a-sampling-function)

To use the sampling function, set the `TracesSampler` option in your SDK configuration to a function that will accept a `SamplingContext` dictionary and return a sample rate between 0 and 1. For example:

```cpp
UCLASS()
class USomeTraceSampler : public USentryTraceSampler
{
	GENERATED_BODY()

public:
	virtual bool Sample_Implementation(USentrySamplingContext* samplingContext, float& samplingValue) override
    {
        const FSentryVariant& gameMode =
            *samplingContext->GetCustomSamplingContext().Find("GameMode");

        if (gameMode.GetValue<FString>().Equals(TEXT("ranked")))
        {
            // Ranked matches are important - take a big sample
            samplingValue = 0.5;
        }
        else if (gameMode.GetValue<FString>().Equals(TEXT("quick_match")))
        {
            // Quick matches less important and happen more frequently - only take 20%
            samplingValue = 0.2;
        }
        else if (gameMode.GetValue<FString>().Equals(TEXT("training")))
        {
            // Training matches are just noise - drop all transactions
            samplingValue = 0.0;
        }
        else
        {
            // Default sample rate for other game modes
            samplingValue = 0.1;
        }

	    return true;

        // Or return false to fallback to options.TracesSampleRate (1.0 in this case)
    }
};

...

FConfigureSettingsDelegate SettingsDelegate;
SettingsDelegate.BindDynamic(this, &USomeClass::HandleSettingsDelegate);

void USomeClass::HandleSettingsDelegate(USentrySettings* Settings)
{
    // Set a uniform sample rate
    Settings->TracesSampleRate = 1.0f;

    // OR: Determine traces sample rate based on the sampling context
    Settings->TracesSampler = USomeTraceSampler::StaticCLass();
}

...

USentrySubsystem* SentrySubsystem = GEngine->GetEngineSubsystem<USentrySubsystem>();

SentrySubsystem->InitializeWithSettings(SettingsDelegate);
```

Currently there's no support for sampling functions on Windows/Linux (`TracesSampler`).

Additionally, your sampling function may also return `false`, which indicates that no sampling decision has been made. In such case, the trace will retain the previous decision if it has been made (for example if it was started from an incoming trace header), or fall back to the value configured in `TracesSampleRate`.

## [Sampling Context Data](https://docs.sentry.io/platforms/unreal/configuration/sampling.md#sampling-context-data)

### [Default Sampling Context Data](https://docs.sentry.io/platforms/unreal/configuration/sampling.md#default-sampling-context-data)

The information contained in the `SamplingContext` object passed to the `TracesSampler` when a transaction is created varies by platform and integration.

`SamplingContext` includes a [Transaction Context](https://github.com/getsentry/sentry-unreal/blob/6e4ee91fd538cede13e95635dd1e38c3ad0ab0ba/plugin-dev/Source/Sentry/Public/SentryTransactionContext.h) and a custom sampling context (`FString` to `FString` map).

### [Custom Sampling Context Data](https://docs.sentry.io/platforms/unreal/configuration/sampling.md#custom-sampling-context-data)

When using custom instrumentation to create a transaction, you can add data to the `SamplingContext` by passing it as an optional second argument to `StartTransaction`. This is useful if there's data you want the sampler to have access to, but you don't want to attach it to the transaction as `tags` or `data`, such as information that's sensitive or that’s too large to send with the transaction. For example:

```cpp
USentrySubsystem* SentrySubsystem = GEngine->GetEngineSubsystem<USentrySubsystem>();

// The following data will take part in the sampling decision
TMap<FString, FString> options;
options.Add(TEXT("user_id"), TEXT("12312012"));
options.Add(TEXT("search_results"), TEXT("..."));

USentryTransactionContext* transactionContext = NewObject<USentryTransactionContext>();
transactionContext->Initialize(
    TEXT("GET /search"),
    TEXT("http")
);

USentryTransaction* transaction =
    SentrySubsystem->StartTransactionWithContextAndOptions(
        transactionContext,
        options
    );
```

## [Inheritance](https://docs.sentry.io/platforms/unreal/configuration/sampling.md#inheritance)

Whatever a transaction's sampling decision, that decision will be passed to its child spans and from there to any transactions they subsequently trigger in other services.

(See [Distributed Tracing](https://docs.sentry.io/platforms/unreal/tracing/trace-propagation.md) for more about how that propagation is done.)

If the transaction currently being created is one of those subsequent transactions (in other words, if it has a parent transaction), the upstream (parent) sampling decision will be included in the sampling context data. Your `TracesSampler` can use this information to choose whether to inherit that decision. In most cases, inheritance is the right choice, to avoid breaking distributed traces. A broken trace will not include all your services.

If you're using a `TracesSampleRate` rather than a `TracesSampler`, the decision will always be inherited.

## [Precedence](https://docs.sentry.io/platforms/unreal/configuration/sampling.md#precedence)

There are multiple ways for a transaction to end up with a sampling decision.

* Random sampling according to a static sample rate set in `TracesSampleRate`
* Random sampling according to a sample function rate returned by `TracesSampler`
* Absolute decision (100% chance or 0% chance) returned by `TracesSampler`
* If the transaction has a parent, inheriting its parent's sampling decision
* Absolute decision passed to `StartTransaction`

When there's the potential for more than one of these to come into play, the following precedence rules apply:

1. If a sampling decision is passed to `StartTransaction`, that decision will be used, overriding everything else.
2. If `TracesSampler` is defined, its decision will be used. It can choose to keep or ignore any parent sampling decision, use the sampling context data to make its own decision, or choose a sample rate for the transaction. We advise against overriding the parent sampling decision because it will break distributed traces
3. If `TracesSampler` is not defined, but there's a parent sampling decision, the parent sampling decision will be used.
4. If `TracesSampler` is not defined and there's no parent sampling decision, `TracesSampleRate` will be used.

Currently there is no support for forcing a sampling decision by passing it into `StartTransaction`.
