Skip to main content

Configuring Backtrace for Unity

Configure Backtrace for your Unity project. This page defines the configuration settings, classes, and methods available with the Backtrace Unity SDK.

Usage​

//Read from manager BacktraceClient instance

var backtraceClient = GameObject.Find("_Manager").GetComponent<BacktraceClient>();
try
{
//throw exception here
}
catch(Exception exception)
{
var report = new BacktraceReport(exception);
backtraceClient.Send(report);
}

After you've setup the Backtrace client and database configuration, you can retrieve database and client instances by using GameObject, then use a try/catch statement to throw an exception and start sending reports.

Configuration Settings​

The configuration settings for the Backtrace client and database are defined by the Backtrace Configuration file in the Assets folder of your Unity project. It's recommended to change the configuration settings for the Backtrace client and database in the Unity Inspector:

Customizing Backtrace client configuration options in the Unity Inspector

Alternatively, you can also specify the configuration settings in your C# project.

Backtrace Client​

SettingDescriptionTypeDefault
Server AddressThe server address (submission URL) is required to submit exceptions from your Unity project to your Backtrace instance.

The Server Address must be in the following format: https://submit.backtrace.io/{subdomain}/{submission-token}/json.
String
Handle unhandled exceptionsHandles unhandled exceptions that are not captured by try/catch statements.BooleanTrue
Reports per minuteLimits the number of reports the client will send per minute.
  • If set to '0', there is no limit.
  • If set to a value greater than '0' and the value is reached, the client will not send any reports until the next minute.
The BacktraceClient.Send and BacktraceClient.SendAsync methods will return 'false'.
Number50
Ignore SSL validationBy default, Unity validates SSL certificates. If you don't want to validate SSL certificates, set the value to 'true'.BooleanFalse

Backtrace Database​

SettingDescriptionTypeDefault
Enable DatabaseEnables an offline database for managed reports. Android native reporting also requires this database. On macOS and iOS, native capture uses separate storage and does not require this setting.BooleanFalse
Backtrace database pathSpecifies the absolute path that the local database will use to store reports for your game or app. Note that the Backtrace database will remove all existing files in the database directory when the client is first initialized.

You can use interpolated strings such as ${Application.persistentDataPath}/backtrace/database.
String
Client-Side deduplicationAggregates duplicated reports. The available options are:
  • Disable: Duplicated reports are not aggregated.
  • Everything: Aggregates by faulting callstack, exception type, and exception message.
  • Faulting callstack: Aggregates based on the current stack trace.
  • Exception type: Aggregates by stack trace and exception type.
  • Exception message: Aggregates by stack trace and exception message.
EnumDisable
Attach Unity Player.logAttaches the Unity player log file to the Backtrace report. Available only for Windows and MacOS.BooleanFalse
Auto send modeSends reports to the server based on the retry settings described below.

If the value is set to 'False', you can use the Flush or Send methods as an alternative.
BooleanTrue
Create database directoryCreates the offline database directory if the provided path doesn't exist.BooleanTrue
Attach screenshotGenerates a screenshot and creates an attachment of the frame when an exception occurs in a game scene.BooleanFalse
Maximum number of recordsThe maximum number of reports stored in the offline database. When the limit is reached, the oldest reports are removed. If the value is equal to '0', then no limit is set.Number8
Maximum database size (mb)The maximum database size in MB. When the limit is reached, the oldest reports are removed. If the value is equal to '0', then no limit is set.
(Managed reports only)
Number0
Retry intervalThe amount of time (in seconds) to wait between retries if the database is unable to send a report.Number60
Maximum retriesThe maximum number of retries to attempt if the database is unable to send a report.Number3
Retry order (FIFO/LIFO)The order in which reports are sent to the Backtrace server:
  • If you set the value to 'Queue' (FIFO), then the first report into the queue is the first report to leave the queue.
  • If you set the value to 'Stack' (LIFO), then the last report into the stack is the last report to leave the stack.
EnumStack

Enable Stack Traces for WebGL​

To enable stack traces for WebGL, in your Unity project's Player Settings, under Publishing Settings, set Enable Exceptions to 'Full With Stacktrace'.

Player setting in Unity required to enable stack traces for WebGL.

WebGL Log-Callback Diagnostics​

Unity WebGL can emit exception-like log callback events with a valid exception message but an empty stackTrace string. The Backtrace Unity SDK records explicit diagnostics for these reports and, on WebGL, can observe original exceptions passed through Debug.LogException(exception) so the report can include real managed frames when available. For details on the diagnostic attributes and stack-source classification, see WebGL log-callback exceptions with empty stack traces.

SettingDescriptionTypeDefault
Unity log handler exception captureControls whether the SDK wraps Debug.unityLogger.logHandler to observe original Exception objects passed through Debug.LogException. The log handler records the original exception only and forwards to Unity's original handler; Unity's log callback remains the send trigger.
  • Automatic: Enabled on WebGL builds, disabled elsewhere.
  • Disabled: Never wrap the Unity log handler.
  • Enabled: Always wrap the Unity log handler.
EnumAutomatic
WebGL JavaScript stack fallbackWebGL only. Optional supplemental browser JavaScript stack annotation captured at SDK report creation time for stackless Unity log-callback reports. This stack is context only; it is not used as the managed C# faulting stack.
  • Disabled: Do not capture a browser JavaScript stack.
  • StacklessUnityLogsOnly: Capture a browser JavaScript stack only when Unity sends an Error or Exception log callback with an empty stackTrace string.
EnumDisabled

You can also set these in code:

using Backtrace.Unity.Types;

backtraceClient.Configuration.UnityLogHandlerExceptionCapture =
BacktraceUnityLogHandlerExceptionCaptureMode.Automatic;

backtraceClient.Configuration.WebGLJavaScriptStackFallback =
BacktraceWebGLJavaScriptStackFallbackMode.Disabled;

Advanced Client Settings​

SettingDescriptionTypeDefault
Use normalized exception messageGenerates a fingerprint with a normalized exception message if an exception doesn't have a stack trace.BooleanFalse
Send unhandled native game crashes on startupSends native crashes when the game or app starts. Available only for Windows.BooleanTrue
Filter reportsIgnores managed error reports based on error type:
  • Disable: Sends error reports for all error types.
  • Everything: Ignores error reports for all error types.
  • Message: Ignores error reports for error messages.
  • Handled Exception: Ignores error reports for handled exceptions.
  • Unhandled Exception: Ignores error reports for unhandled exceptions.
  • Hang: Ignores error reports for ANR (Application not responding) or hang errors. Mobile only.
  • Game Error: Ignores error reports for game crashes in the managed environment.
EnumDisable
Collect last n game logsCollects last n number of logs generated in the game.Number10
Enable performance statisticsAllows the Backtrace client to measure execution time and include performance information as report attributes.BooleanFalse
Destroy client on new scene loadRemoves the Backtrace client component when loading a new game scene.

By default, the Backtrace client will be available in every game scene.
BooleanFalse
Log random sampling rateThe rate at which random sample reports for DebugLog.error messages are sent to Backtrace.

By default, 1% of the DebugLog.error messages will be sent to Backtrace. To send all DebugLog.error messages to Backtrace, set the value to '1'.
Decimal0.01
Game object depth limitFilters the number of GameObject children in Backtrace reports.Number-1
Disable error reporting integration in editorIgnores errors encountered while the project is running in the Unity Editor and only reports errors encountered in a build.BooleanFalse

Crash Free Metrics Reporting​

Once enabled, unique application launches and unique player identifiers (default: guid) will be submitted to Backtrace so you can get an overview of how many errors, hangs, crashes, and memory problems occur compared to all active users for a given platform, version, and more.

note

This functionality is supported on all platforms except WebGL.

SettingDescriptionTypeDefault
Enable crash free metrics reportingEnables metrics such as crash free users and crash free sessions.BooleanTrue
Auto send interval in minIndicates how often crash free metrics are sent to Backtrace.

By default, session events are sent on application startup, when the game ends, and every 30 minutes while the game is running.
Number30

You can enable crash free metrics at runtime with backtraceClient.EnableMetrics().

You can also add custom metrics groups and attributes with backtraceClient.Instance.Metrics.AddSummedEvent.

Capturing Native Crashes​

The following native reporting guidance applies to SDK 3.17.0 and later. Check the platform requirements before building. Native reports are captured in the player, not in the Unity Editor.

Android native capture requires API level 21 or newer and a supported process architecture: arm64-v8a, armeabi-v7a, or x86_64. Managed reporting remains available on 32-bit x86, but native capture does not.The SDK supports APK, Android App Bundle, and split-APK installations, including native libraries loaded directly from an APK. It selects libraries for the running process architecture. You do not need to force native-library extraction.The Backtrace Unity SDK also captures memory and process information from the underlying Android OS, JNI, and NDK layers, including:
  • system.memory.free
  • system.memory.swap.free
  • system.memory.vmalloc.total
  • sched.cs.involuntary
  • sched.cs.voluntary
For more information about other data that is captured, see Attributes.
SettingDescriptionTypeDefault
Capture native crashesCaptures native crashes, stores reports locally, and submits them after the application restarts. Requires Enable Database and a writable database path. Matching debug symbols are required for symbolication, not capture.BooleanTrue
Capture ANR (Application not responding)Generates a hang report when the application remains unresponsive beyond the configured watchdog timeout. The default timeout is five seconds, and the report's error.type is Hang.BooleanTrue
Send Out of Memory exceptions to BacktraceAnnotates native state with memory.warning and memory.warning.date when Unity notifies the SDK of low memory. The callback does not create or send a report, and reporting is not guaranteed for every memory-related termination.BooleanFalse
Enable client-side unwindingDoes not change Android native crash capture. Upload matching native debug symbols for symbolication; this setting is not a substitute for symbols.BooleanFalse
Symbols upload tokenRequired for automatic upload of matching Android IL2CPP symbols. To generate a token, in Backtrace go to Project Settings > Symbols > Access tokens, then select +.String
For Android native crash startup behavior, APK and Android App Bundle support, supported ABIs, failure containment, and diagnostic codes, see Android Native Crash Integration for Unity.

ProGuard Rules​

See Configure ProGuard for the required keep rules and symbolication ID configuration.

Uploading Debug Symbols​

Native capture does not depend on symbol upload. To resolve function names and source locations, upload debug symbols that match the exact application and native library builds.See Upload Debug Symbols for Android IL2CPP build and symbol-upload configuration.

Apple Native Lifecycle and Delivery​

On macOS and iOS, native capture owns its storage independently of the managed Backtrace database. Managed retry, capacity, and Auto send mode settings do not configure the native queue.

The SDK passes Reports per minute (ReportPerMin) to the native reporter at initialization; 0 means no local rate limit. Managed and native reporting apply the configured limit independently, not as a combined quota. Changing the managed limit at runtime does not reconfigure an active native reporter.

Keep one native client active for the application process and update the managed sources and native artifacts together. Once a native handler has been installed, disabling the client does not uninstall that handler. Restart the application before enabling native capture again, or after an initialization failure that might have partially installed a handler. Repeated Refresh() calls are not an initialization retry mechanism.

An existing Apple native client is retained across refreshes; native settings are not reapplied to it. If capture starts disabled, configure it before the first native initialization. Native initialization failures do not prevent managed reporting. For recovery steps, see Troubleshooting.

Logging Breadcrumbs​

SettingDescriptionTypeDefault
Enable breadcrumbs supportLogs breadcrumb events, such as the app going to a background process, logging messages, network connectivity lost, and more.

By default, breadcrumbs are limited to 64kB and older events will automatically be removed.
BooleanFalse
Breadcrumbs event typeSpecifies which type of events to log.EnumEverything
Breadcrumbs log levelSpecifies which log level severity to include.EnumEverything

You can also add custom breadcrumb events, with information like "player completed a level" and sub attributes:

GetComponent<BacktraceClient>().Breadcrumbs.Info("Player Base Upgraded", new Dictionary<string, string>() {
{"base.name", "MtGox"},
{"base.level", "15"}
});

Advanced Configuration​

backtraceApi​

| CLASS | REQUIRED |

Class used to send diagnostic data in JSON format to the Backtrace endpoint, including asynchronous reports. backtraceApi is instantiated when the backtraceClient awake method is called.


backtraceClient​

| CLASS | REQUIRED |

Class used to send backtraceReport to the Backtrace server by using backtraceApi. backtraceClient requires a Backtrace Configuration window.

note

This class inherits MonoBehavior functions.


//Read from manager BacktraceClient instance
var backtraceClient = GameObject.Find("manager name").GetComponent<BacktraceClient>();

//Set custom client attribute
backtraceClient["attribute"] = "attribute value";

//Read from manager BacktraceClient instance
var database = GameObject.Find("manager name").GetComponent<BacktraceDatabase>();


try{
//throw exception here
}
catch(Exception exception){
var report = new BacktraceReport(exception);
backtraceClient.Send(report);
}

backtraceClient.Initialize​

| METHOD | REQUIRED |

Method used to initialize the Backtrace Unity SDK directly in the C# code of your Unity project.

var backtraceClient = BacktraceClient.Initialize(
url: serverUrl,
databasePath: "${Application.persistentDataPath}/sample/backtrace/path",
gameObjectName: "game-object-name",
attributes: attributes);

If you need to use more advanced configuration settings, the Initialize method accepts a BacktraceConfiguration scriptable object. For example:

var configuration = ScriptableObject.CreateInstance<BacktraceConfiguration>();
configuration.ServerUrl = serverUrl;
configuration.Enabled = true;
configuration.DatabasePath = "${Application.persistentDataPath}/sample/backtrace/path";
configuration.CreateDatabase = true;
configuration.Sampling = 0.002;
configuration.ClientSideUnwinding = true;
_backtraceClient = BacktraceClient.Initialize(
configuration,
gameObjectName: "game-object-name",
attributes: attributes);

backtraceClient.Instance.Metrics.AddSummedEvent​

| METHOD | OPTIONAL |

Used to add custom metrics groups and attributes to capture your game or apps' stability.

For example, if you want to know details about the levels that a user has played in your game, you can add a "LevelsPlayed" event with the application.version and score attributes.

BacktraceClient.Instance.Metrics.AddSummedEvent("levels_played", new Dictionary<string, string>() {
{"application.version", BacktraceClient.Instance["application.version"]},
{"score", "" + score}
}
);

As another example, if you want to know how many minutes a user has played your game, you can add a "MinutesPlayed" event with the application.version and uname.sysname attributes.

private void Update()
{
timeElapsedSeconds += Time.deltaTime;

// Every second, add an event for this metric group
if (timeElapsedSeconds >= 60)
{
timeElapsedSeconds = 0;

// Generate your attribute values for the attributes you want linked
Dictionary<string,string> attributes = new Dictionary<string, string>()
{
{ "application.version", BacktraceClient.Instance["application.version"] },
{ "uname.sysname", BacktraceClient.Instance["uname.sysname"] },
{ "custom.field", "custom.value" },
};

// Add the summed event using the metric group name and attributes
BacktraceClient.Instance.Metrics.AddSummedEvent("MinutesPlayed", attributes);
}
}

The example above adds an event for this metric group to a queue, which will be sent based on the Auto send interval setting in the Backtrace Configuration in Unity.

You can adjust the frequency of that send process to suit your needs and/or manually send the events with BacktraceClient.Instance.Metrics.Send().

caution

Adding multiple events with many linked attributes or sending the metrics events too frequently may affect the performance of your game or app and contribute a lot of data towards your Backtrace data storage limits.


backtraceClient.Refresh​

| METHOD | OPTIONAL |

Use this method to refresh the managed client's configuration when changing settings dynamically. On Apple platforms, an existing native client is retained: Refresh() does not reinstall its handler, reapply native settings, or retry a failed native initialization. See Apple Native Lifecycle and Delivery. For example:

//Read from manager BacktraceClient instance
var backtraceClient = GameObject.Find("manager name").GetComponent<BacktraceClient>();

//Set custom client attribute
backtraceClient["attribute"] = "attribute value";

//Change configuration value
backtraceClient.configuration.DeduplicationStrategy = deduplicationStrategy;

//Refresh configuration
backtraceClient.Refresh();

backtraceClient.Send​

| METHOD | REQUIRED |

Method used to send error reports to the Backtrace endpoint.

try
{
//throw exception here
}
catch (Exception exception)
{
var report = new BacktraceReport(
exception: exception,
attributes: new Dictionary<string, string>() { { "key", "value" } },
attachmentPaths: new List<string>() { @"file_path_1", @"file_path_2" }
);
backtraceClient.Send(report);
}

Custom Event Handlers​

You can also add custom event handlers to the client. For example, you can use BeforeSend to trigger actions before the Send method:

//Add a custom event handler
backtraceClient.BeforeSend =
(Model.BacktraceData model) =>
{
var data = model;

//do something with the data, for example:
data.Attributes.Attributes.Add("eventAttribute", "EventAttributeValue");
if(data.Classifier == null || !data.Classifier.Any())
{
data.Attachments.Add("path to attachment");
}

return data;
};

BacktraceClient currently supports the following events:

  • BeforeSend
  • OnClientReportLimitReached
  • OnServerResponse
  • OnServerError

You can also use the backtraceReport class to customize the data included in the error reports sent by the backtraceClient.


backtraceClient.SkipReport​

| SETTING | OPTIONAL |

If you want to ignore specific types of error reports, we recommend that you use the Filter reports settings in the Backtrace Configuration in the Unity Editor.

However, for more advanced use cases, you can use BacktraceClient.SkipReport to set the ReportFilterType. For example:

// Return 'true' to ignore a report,
// Return 'false' to handle the report and generate it for the error.
BacktraceClient.SkipReport = (ReportFilterType type, Exception e, string msg) =>
{
// ReportFilterType is one of None, Message, Exception, UnhandledException or Hang.
// It is also possible to filter based on the exception and exception message.

// Report hangs and crashes only.
return type != ReportFilterType.Hang && type != ReportFilterType.UnhandledException;
};

backtraceData​

| CLASS | OPTIONAL |

Serializable class that holds the diagnostic data in JSON format to be sent to the backtrace endpoint via backtraceApi.


backtraceDatabase​

| CLASS | REQUIRED |

Class that stores error report data in your local hard drive when reports fail to send due to network outages or server unavailability. backtraceDatabase will periodically try to resend reports cached in the database.


backtraceDatabase.Clear​

| METHOD | OPTIONAL |

Clears all reports from the database without sending them to Backtrace server.

backtraceDatabase.Clear();

backtraceDatabase.Count​

| METHOD | OPTIONAL |

Returns the number of reports stored in the database, including deduplicated reports.

backtraceDatabase.Count();

backtraceDatabase.Delete​

| METHOD | OPTIONAL |

Removes a report stored in the database, including deduplicated reports.

backtraceDatabase.Delete();

backtraceDatabase.Flush​

| METHOD | OPTIONAL |

Sends all reports to the Backtrace server then removes them from the database. This method is only needed to support the offline database when the Auto send mode is disabled.

note

The Flush method ignores client side deduplication and retry settings.

caution

If the Send method fails, the database will no longer store data.

backtraceDatabase.Flush();

backtraceDatabase.Send​

| METHOD | OPTIONAL |

Sends all reports to the Backtrace server, as defined by the client side deduplication and database retry settings. This method is only needed to support the offline database when the Auto send mode is disabled.

backtraceDatabase.Send();

backtraceReport​

| CLASS | OPTIONAL |

Class that defines a single error report.

Attributes and Attachment Paths​

For managed reports, submit custom attributes using the attributes parameter or attach files using the attachmentPaths parameter. For native reports, configure attachment paths before native initialization using BacktraceConfiguration.AttachmentPaths or the client's initialization arguments. Calling AddAttachment(...) later affects managed reports only.

The following example attaches attributes and files to a managed report:

try
{
//throw exception here
}
catch (Exception exception)
{
var report = new BacktraceReport(
exception: exception,
attributes: new Dictionary<string, string>() { { "key", "value" } },
attachmentPaths: new List<string>() { @"file_path_1", @"file_path_2" }
);
backtraceClient.Send(report);
}

Fingerprint and Factor​

You can use the Fingerprint and Factor properties to modify the client side deduplication strategy. The Fingerprint property changes the hash that is generated, while the Factor property changes how duplicated reports are aggregated.

note

Fingerprint values must be a valid SHA-256 string.

For example:

try
{
//throw exception here
}
catch (Exception exception)
{
var report = new BacktraceReport(...){
Fingerprint = "sha256 string",
Factor = exception.GetType().Name
};
...
}

The Backtrace client will send a single report when an exception occurs and maintain a count for every other time it occurs, which reduces the volume of reports that are generated and sent to Backtrace.

The count is reset when the offline database is cleared (usually when the reports are sent to the server) or if the game is closed before the reports are sent. A new single report is created the next time the exception occurs.

Information about aggregated reports is stored in backtraceDatabaseRecord. You can use the Hash property to verify the generated hash for the diagnostic data, and the Counter property to verify the count of duplicated reports.


reportWatcher​

| CLASS | REQUIRED |

Class that validates send requests from backtraceApi to the Backtrace endpoint. If ReportPerMin is set to a value greater than '0' in the backtraceClient configuration, reportWatcher will limit the number of reports sent by the client.


Data Management​

The Backtrace Unity SDK allows you to modify and remove data that the library collects when an exception occurs using the following methods:

backtraceClient.BeforeSend​

| EVENT | OPTIONAL |

Triggers an event every time an exception in the managed environment occurs, which allows you to skip the report (by returning a null value) or to modify data that library collected before sending the report.

You can use the BeforeSend event to extend attributes or JSON object data based on data the application has at the time of exception.

//Read from manager BacktraceClient instance

var backtraceClient = GameObject.Find("manager name").GetComponent<BacktraceClient>();

// set beforeSend event

_backtraceClient.BeforeSend = (BacktraceData data) =>
{
data.Attributes.Attributes["my-dynamic-attribute"] = "value";
return data;
};

Annotation.EnvironmentVariables​

| CLASS | OPTIONAL | STRING |

The Annotation class exposes the EnvironmentVariablesCache dictionary, which stores environment variables collected by the library. You can manipulate the data in this cache before the report is sent.

For example, you can use an annotation to replace the USERNAME environment variable with a random string, which will be used to create reports.

Annotations.EnvironmentVariablesCache["USERNAME"] = "%USERNAME%";
}

You can also use the BeforeSend event along with annotations for environment variables to edit collected diagnostic data.

client.BeforeSend = (BacktraceData data) =>
{
data.Annotation.EnvironmentVariables["USERNAME"] = "%USERNAME%";
return data;
}