Backtrace Unity Integration

repository·master·Indexed 41 days ago

https://github.com/backtrace-labs/backtrace-unity

Integration for Unity games (version 3.17.0-rc) to capture and report handled/unhandled exceptions, log errors, native crashes, and hangs to the Backtrace platform. Supports a wide range of platforms including Android, iOS, WebGL, Windows, macOS, Linux, Nintendo Switch, PS4/5, and Xbox One/S/X. Features include an offline database for deferred uploads, client-side deduplication, and programmatic initialization via BacktraceClient.

Tokens
7.2K
Snippets
14
Records
30
Agent score
50%

What's inside Backtrace

  1. Backtrace Unity Prerequisites and Platform Support

    master

    Prerequisites

    • Unity Version: 2017.4.x or newer.
    • Scripting Runtime: .NET 2.0/3.5/4.5 or Standard 2.0.
    • Scripting Backend: Mono or IL2CPP.
    • Backtrace Instance: You must have a Backtrace instance (create one at backtrace.io/create-unity).

    Platform Support Summary

    • All Platforms: Supports errors, unhandled/handled exceptions, custom metadata, file attachments, log lines, screenshots, client-side de-duplication, filtering, and performance diagnostics.
    • Android: Supports ANR (hangs), native process/memory info, Java exception handlers, and NDK crashes.
    • iOS: Supports ANR (hangs), native engine/memory/plugin crashes.
    • WebGL: Supports WebGL errors (ensure 'Enable Exceptions' is enabled in Publishing Settings to see stack traces).
    • Nintendo Switch: Supports errors and exceptions. Note: Offline database and related features are not supported on Switch. Device GUID changes on every reboot.
    • Windows: Supports engine crash mini-dumps.
    • PlayStation 4/5, Xbox One/S/X, Mac: Fully supported.
  2. Configure client-side deduplication

    master

    The Backtrace Unity integration allows you to aggregate identical error reports so that only one message is sent to the Backtrace API. You can configure this using the DeduplicationStrategy enum in the Unity UI.

    Available deduplication strategies:

    • Ignore: Disables deduplication.
    • Default: Searches for duplicate reports using the current stack trace.
    • Classifier: Searches for duplicate reports using both the stack trace and the exception type.
    • Message: Searches for duplicate reports using both the stack trace and the exception message.

    Important Notes:

    • When aggregating reports via the Backtrace C# library, the BacktraceDatabaseRecord.Counter property increases.
    • The deduplication algorithm uses BacktraceReport, Fingerprint, and Factor properties. The Fingerprint property overrides the algorithm's result, while the Factor property modifies the generated hash.
    • If the game is closed before the plugin can send aggregated data to Backtrace, counter information may be lost.
    • You can inspect aggregated diagnostic data using BacktraceDatabase. Use the Hash property to check the generated hash and the Counter property to see the number of detected identical records.
    # Example of interacting with BacktraceDatabase for aggregated data
    // Check the hash and count of aggregated records
    var hash = database.BacktraceDatabaseRecord.Hash;
    var count = database.BacktraceDatabaseRecord.Counter;
    
    // Get total records in database (including duplicates)
    int totalCount = database.Count();
    
    // Delete records (including duplicates)
    database.Delete(record);
  3. Understand the 6 error classes reported by Backtrace

    master

    The Backtrace Unity plugin categorizes and reports six distinct types of errors to help you diagnose issues:

    1. Log Errors: Errors recorded to the Unity console using Debug.LogError (or its variants).
    2. Unhandled Exceptions: Exceptions occurring in-game that are not caught by an explicit try/catch block.
    3. Handled Exceptions: Exceptions that are explicitly identified and handled by your code.
    4. Crashes: Instances where the gameplay terminates, causing the game to crash or restart.
    5. Hangs: States where the game becomes unresponsive (e.g., the "This app has stopped responding" dialog on certain platforms).
    6. Out of Memory (OOM) Crashes: Crashes caused by memory pressure (supported on mobile only).
  4. Use Client-side Deduplication to reduce report volume

    master

    To prevent flooding the Backtrace server with identical errors, you can use Client-side deduplication. This allows the plugin to merge multiple reports into a single message based on specific rules. The plugin aggregates reports based on:

    • Call stack
    • Error message
    • Classifiers

    This ensures that when the offline database is flushed, only one unique message is sent for a group of identical errors.

  5. Configure ANR and Hang reporting for Android and iOS

    master

    You can enable or disable reporting for ANRs (Application Not Responding) and hangs using the backtrace-unity GUI within the Unity Editor.

    • Android: The default threshold for a hang is 5 seconds. When a hang is reported, the error.type will be set to Hang.
    • iOS: Similar to Android, you can toggle hang reporting in the Unity Editor GUI. Reported hangs will have an error.type of Hang.
  6. Understand the Backtrace architecture components

    master

    The Backtrace Unity integration is composed of several key classes:

    • BacktraceReport: Represents a single error report.
    • BacktraceClient: A MonoBehaviour that manages the connection to the Backtrace endpoint and error report behavior (e.g., saving minidumps, rate limiting). It requires configuration via the Backtrace configuration window.
    • BacktraceData: A serializable class holding diagnostic JSON data. You can add pre-processors by attaching event handlers to BacktraceClient.BeforeSend.
    • BacktraceApi: Handles the asynchronous transmission of diagnostic JSON to the Backtrace endpoint. It is instantiated when BacktraceClient.Awake is called.
    • BacktraceDatabase: Stores error reports locally on the hard drive if network or server issues prevent transmission. It periodically attempts to resend cached reports.
    • ReportWatcher: Validates transmission requests against the reportPerMin limit set in the BacktraceClient to prevent rate-limit violations.
  7. Enable Out-of-Memory (OOM) reporting for Android and iOS

    master

    Backtrace can detect and flag low-memory states to help diagnose crashes caused by memory pressure.

    Android (Early Access)

    When a low-memory state is detected, the following attributes are added to the report:

    • memory.warning is set to true.
    • memory.warning.date is set to the device's local time at the moment of detection.

    If the game fails to recover and is terminated by the OS, a crash report is sent containing these attributes.

    iOS (Early Access)

    On iOS, when the OS indicates memory pressure, Backtrace creates an application state snapshot. If the OS eventually terminates the game, Backtrace uses these snapshots to determine if the termination was due to memory pressure. Snapshots are taken at most every 2 minutes during sustained low-memory states.

    Note: This feature can be toggled on or off in the Backtrace settings.

  8. Upload debug symbols for iOS (dSYM)

    master

    To symbolicate iOS crashes, you must provide dSYM files.

    1. Xcode Configuration: In your Xcode project build settings, ensure that DWARF with dSYM files is enabled for your targets (the default may be just DWARF).
    2. Locate Files: After building, dSYM files are located in .../Build/Products/<build_folder>.
    3. Package and Upload: Compress these dSYM files into a .zip archive and upload them to Backtrace via the Project Settings > Symbols menu in Unity or the Backtrace UI.

    For more details on managing upload tokens or external symbol servers, refer to the Backtrace Symbolication documentation.

  9. Install the backtrace-unity package

    master

    There are three ways to install the library:

    1. OpenUPM (Recommended): Follow the instructions on the OpenUPM package page.
    2. Git URL: Use the Unity Package Manager to install directly via the Git URL from the repository.
    3. Manual Download:
      • Download the zip file from GitHub Releases.
      • Extract it to a known location.
      • In Unity, go to Window -> Package Manager -> Add Package From Disk and select the package.json file.
  10. Configure Backtrace via Unity Editor

    master

    To set up Backtrace using the Unity IDE:

    1. Generate Configuration: Go to Assets -> Create -> Backtrace -> Configuration. This creates a Backtrace configuration asset in your Assets folder.
    2. Attach Client: Select a GameObject in your scene (e.g., a Manager object) and click Add Component to add the Backtrace Client component.
    3. Link Configuration: Drag and drop the generated Backtrace configuration asset into the Backtrace Configuration field in the Backtrace Client Inspector panel.
  11. Integrate Backtrace into Unity via Code

    master

    To integrate Backtrace programmatically, you should use the BacktraceClient.Initialize method. This allows you to set up the client with a specific server URL, database path, and custom attributes. You can also provide a BacktraceConfiguration ScriptableObject for more advanced settings like sampling rates and database creation.

    // Basic initialization
    var backtraceClient = BacktraceClient.Initialize(
        url: serverUrl,
        databasePath: "${Application.persistentDataPath}/sample/backtrace/path",
        gameObjectName: "game-object-name",
        attributes: attributes);
    
    // Advanced initialization using BacktraceConfiguration
    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;
    
    _backtraceClient = BacktraceClient.Initialize(
        configuration,
        gameObjectName: "game-object-name",
        attributes: attributes);