### Install Backtrace Unity Package Source: https://github.com/backtrace-labs/backtrace-unity/blob/master/README.md Install the Backtrace Unity package using the openupm-cli. Ensure you navigate to your Unity project directory before running the command. ```bash npm install -g openupm-cli cd YOUR_UNITY_PROJECT_DIR openupm add io.backtrace.unity ``` -------------------------------- ### Initialize BacktraceClient Programmatically Source: https://context7.com/backtrace-labs/backtrace-unity/llms.txt Demonstrates various ways to initialize the BacktraceClient at runtime. Use the minimal overload for basic setup, or include database path, custom attributes, and attachments for more comprehensive reporting. The configuration object provides the most granular control over SDK behavior. ```csharp using Backtrace.Unity; using Backtrace.Unity.Model; using System.Collections.Generic; using UnityEngine; public class GameBootstrap : MonoBehaviour { void Start() { // Minimal initialization — URL only var client = BacktraceClient.Initialize( url: "https://submit.backtrace.io/my-universe/TOKEN/json"); // With database, attributes, and attachments var attributes = new Dictionary { { "game.version", Application.version }, { "player.region", "EU" } }; var attachments = new[] { Application.persistentDataPath + "/game.log" }; BacktraceClient clientFull = BacktraceClient.Initialize( url: "https://submit.backtrace.io/my-universe/TOKEN/json", databasePath: Application.persistentDataPath + "/backtrace-db", attributes: attributes, attachments: attachments); // Using a BacktraceConfiguration ScriptableObject (most configurable) var config = ScriptableObject.CreateInstance(); config.ServerUrl = "https://submit.backtrace.io/my-universe/TOKEN/json"; config.Enabled = true; config.DatabasePath = "${Application.persistentDataPath}/bt"; config.CreateDatabase = true; config.ReportPerMin = 30; config.HandleUnhandledExceptions = true; config.DestroyOnLoad = false; // persist across scenes BacktraceClient configuredClient = BacktraceClient.Initialize(config, attributes); } } ``` -------------------------------- ### BacktraceClient.Initialize Source: https://context7.com/backtrace-labs/backtrace-unity/llms.txt Provides methods to programmatically initialize the BacktraceClient and an optional BacktraceDatabase at runtime. Overloads allow for minimal setup with just a URL, or more comprehensive configurations including attributes, attachments, and a BacktraceConfiguration ScriptableObject. ```APIDOC ## BacktraceClient.Initialize — Programmatic client initialization Creates a `BacktraceClient` and optional `BacktraceDatabase` GameObject at runtime without requiring a scene prefab. All overloads accept an optional `attributes` dictionary and a custom `gameObjectName`. The single-URL overload auto-enables WebGL offline storage. ### Method Overloads 1. **Minimal Initialization (URL only):** ```csharp public static BacktraceClient Initialize(string url) ``` Initializes the client with the specified server URL. 2. **Comprehensive Initialization (URL, database path, attributes, attachments): ```csharp public static BacktraceClient Initialize(string url, string databasePath, Dictionary attributes = null, string[] attachments = null) ``` Initializes the client with a URL, an optional database path for offline storage, custom attributes, and optional file attachments. 3. **Configuration Object Initialization (ScriptableObject): ```csharp public static BacktraceClient Initialize(BacktraceConfiguration configuration, Dictionary attributes = null) ``` Initializes the client using a `BacktraceConfiguration` ScriptableObject for detailed settings, along with optional custom attributes. ### Usage Examples **Minimal initialization:** ```csharp var client = BacktraceClient.Initialize( url: "https://submit.backtrace.io/my-universe/TOKEN/json"); ``` **With database, attributes, and attachments:** ```csharp var attributes = new Dictionary { { "game.version", Application.version }, { "player.region", "EU" } }; var attachments = new[] { Application.persistentDataPath + "/game.log" }; BacktraceClient clientFull = BacktraceClient.Initialize( url: "https://submit.backtrace.io/my-universe/TOKEN/json", databasePath: Application.persistentDataPath + "/backtrace-db", attributes: attributes, attachments: attachments); ``` **Using a `BacktraceConfiguration` ScriptableObject:** ```csharp var config = ScriptableObject.CreateInstance(); config.ServerUrl = "https://submit.backtrace.io/my-universe/TOKEN/json"; config.Enabled = true; config.DatabasePath = "${Application.persistentDataPath}/bt"; config.CreateDatabase = true; config.ReportPerMin = 30; config.HandleUnhandledExceptions = true; config.DestroyOnLoad = false; // persist across scenes BacktraceClient configuredClient = BacktraceClient.Initialize(config, attributes); ``` ``` -------------------------------- ### Configure BacktraceClient with ScriptableObject Source: https://context7.com/backtrace-labs/backtrace-unity/llms.txt Build and configure the Backtrace client entirely in code using ScriptableObject. This is useful for tests or procedural setups. Ensure all required fields like ServerUrl are set. ```csharp using Backtrace.Unity.Model; using Backtrace.Unity.Model.Breadcrumbs; using Backtrace.Unity.Types; using UnityEngine; // Build configuration entirely in code (useful in tests or procedural setups) var config = ScriptableObject.CreateInstance(); // Required config.ServerUrl = "https://submit.backtrace.io///json"; // Client behaviour config.ReportPerMin = 50; // 0 = unlimited config.Sampling = 0.1d; // 10% of Debug.LogError reports config.HandleUnhandledExceptions = true; config.DisableInEditor = true; // quiet during development config.DestroyOnLoad = false; // survive scene loads config.IgnoreSslValidation = false; config.GameObjectDepth = -1; // -1 = default (16 levels) config.NumberOfLogs = 10; // last N Unity log lines attached config.PerformanceStatistics = false; config.UseNormalizedExceptionMessage = false; config.ReportFilterType = ReportFilterType.None; // send everything // Native integrations config.CaptureNativeCrashes = true; config.HandleANR = true; config.AnrWatchdogTimeout = 5000; // ms config.OomReports = false; config.ClientSideUnwinding = false; config.GenerateScreenshotOnException = false; config.MinidumpType = MiniDumpType.None; config.AttachmentPaths = new[] { "${Application.persistentDataPath}/game.log" }; // Database (offline store) config.Enabled = true; config.DatabasePath = "${Application.persistentDataPath}/backtrace"; config.CreateDatabase = true; config.AutoSendMode = true; config.MaxRecordCount = 8; // 0 = unlimited config.MaxDatabaseSize = 0; // MB, 0 = unlimited config.RetryInterval = 60; // seconds between retry attempts config.RetryLimit = 3; config.RetryOrder = RetryOrder.Queue; config.DeduplicationStrategy = DeduplicationStrategy.None; // Breadcrumbs config.EnableBreadcrumbsSupport = true; config.BacktraceBreadcrumbsLevel = BacktraceBreadcrumbType.Manual | BacktraceBreadcrumbType.Log | BacktraceBreadcrumbType.System; config.LogLevel = UnityEngineLogLevel.Error | UnityEngineLogLevel.Warning; // Metrics config.EnableMetricsSupport = true; config.TimeIntervalInMin = 30; // 0 = manual Send() only Debug.Log("Config valid: " + config.IsValid()); ``` -------------------------------- ### BacktraceConfiguration Source: https://context7.com/backtrace-labs/backtrace-unity/llms.txt Scriptable object for configuring Backtrace SDK settings. Can be created via Assets → Create → Backtrace → Configuration or programmatically. ```APIDOC ## `BacktraceConfiguration` — Scriptable object settings reference All fields are serializable Unity inspector properties. Create via **Assets → Create → Backtrace → Configuration**. ```csharp using Backtrace.Unity.Model; using Backtrace.Unity.Model.Breadcrumbs; using Backtrace.Unity.Types; using UnityEngine; // Build configuration entirely in code (useful in tests or procedural setups) var config = ScriptableObject.CreateInstance(); // Required config.ServerUrl = "https://submit.backtrace.io///json"; // Client behaviour config.ReportPerMin = 50; // 0 = unlimited config.Sampling = 0.1d; // 10% of Debug.LogError reports config.HandleUnhandledExceptions = true; config.DisableInEditor = true; // quiet during development config.DestroyOnLoad = false; // survive scene loads config.IgnoreSslValidation = false; config.GameObjectDepth = -1; // -1 = default (16 levels) config.NumberOfLogs = 10; // last N Unity log lines attached config.PerformanceStatistics = false; config.UseNormalizedExceptionMessage = false; config.ReportFilterType = ReportFilterType.None; // send everything // Native integrations config.CaptureNativeCrashes = true; config.HandleANR = true; config.AnrWatchdogTimeout = 5000; // ms config.OomReports = false; config.ClientSideUnwinding = false; config.GenerateScreenshotOnException = false; config.MinidumpType = MiniDumpType.None; config.AttachmentPaths = new[] { "${Application.persistentDataPath}/game.log" }; // Database (offline store) config.Enabled = true; config.DatabasePath = "${Application.persistentDataPath}/backtrace"; config.CreateDatabase = true; config.AutoSendMode = true; config.MaxRecordCount = 8; // 0 = unlimited config.MaxDatabaseSize = 0; // MB, 0 = unlimited config.RetryInterval = 60; // seconds between retry attempts config.RetryLimit = 3; config.RetryOrder = RetryOrder.Queue; config.DeduplicationStrategy = DeduplicationStrategy.None; // Breadcrumbs config.EnableBreadcrumbsSupport = true; config.BacktraceBreadcrumbsLevel = BacktraceBreadcrumbType.Manual | BacktraceBreadcrumbType.Log | BacktraceBreadcrumbType.System; config.LogLevel = UnityEngineLogLevel.Error | UnityEngineLogLevel.Warning; // Metrics config.EnableMetricsSupport = true; config.TimeIntervalInMin = 30; // 0 = manual Send() only Debug.Log("Config valid: " + config.IsValid()); ``` ``` -------------------------------- ### Enable and use breadcrumbs for structured event trails Source: https://context7.com/backtrace-labs/backtrace-unity/llms.txt Activate breadcrumbs support by calling EnableBreadcrumbsSupport() and access the IBacktraceBreadcrumbs interface to log events. Use severity-based helpers like Info, Warning, Debug, and Exception, or the generic Log method for custom levels and attributes. Breadcrumbs require the database to be enabled in the BacktraceConfiguration. ```csharp using Backtrace.Unity; using Backtrace.Unity.Model.Breadcrumbs; using System.Collections.Generic; using UnityEngine; public class BreadcrumbExample : MonoBehaviour { private IBacktraceBreadcrumbs _crumbs; void Start() { var client = BacktraceClient.Instance; // Activate breadcrumbs (requires database enabled in config) bool activated = client.EnableBreadcrumbsSupport(); Debug.Log("Breadcrumbs active: " + activated); _crumbs = client.Breadcrumbs; if (_crumbs == null) return; // Severity-based helpers _crumbs.Info("Game session started"); _crumbs.Warning("Low memory warning received"); _crumbs.Debug("AI path-finding recalculated", new Dictionary { { "agent.id", "enemy-42" }, { "nodes", "17" } }); _crumbs.Exception("Serialization partial failure"); // Generic Log — full control over BreadcrumbLevel and LogType _crumbs.Log( message: "Player purchased item", level: BreadcrumbLevel.User, logType: LogType.Log, attributes: new Dictionary { { "item.id", "sword-99" } }); // Clear all stored breadcrumbs (e.g. on new game session) _crumbs.ClearBreadcrumbs(); // Retrieve the breadcrumb log file path (useful for manual attachment) string logPath = _crumbs.GetBreadcrumbLogPath(); Debug.Log("Breadcrumb file: " + logPath); } void OnLevelLoaded(int level) { _crumbs?.Log( message: $"Level {level} loaded", logType: LogType.Log, attributes: new Dictionary { { "level", level.ToString() } }); } } ``` -------------------------------- ### Send Exception Report with BacktraceClient Source: https://github.com/backtrace-labs/backtrace-unity/blob/master/README.md Capture exceptions and send them as a Backtrace report using the BacktraceClient instance. This snippet demonstrates how to access the client and send a report for a caught exception. ```csharp //Read from manager BacktraceClient instance var backtraceClient = GameObject.Find("_Manager").GetComponent(); try { //throw exception here } catch(Exception exception) { var report = new BacktraceReport(exception); backtraceClient.Send(report); } ``` -------------------------------- ### Intercept and filter reports with BacktraceClient event hooks Source: https://context7.com/backtrace-labs/backtrace-unity/llms.txt Use delegate properties like BeforeSend, SkipReport, OnClientReportLimitReached, OnServerError, RequestHandler, and OnUnhandledApplicationException to customize report handling. BeforeSend allows mutation or dropping of reports, SkipReport filters by type, and OnServerError handles server-side issues. SetClientReportLimit adjusts the rate limit. ```csharp using Backtrace.Unity; using Backtrace.Unity.Model; using Backtrace.Unity.Types; using System; using UnityEngine; public class EventHookExample : MonoBehaviour { void Start() { var client = BacktraceClient.Instance; // Mutate or discard a report — returning null drops it client.BeforeSend = (BacktraceData data) => { data.Attributes.Attributes["custom.tag"] = "processed"; // Drop reports tagged as noise if (data.Report?.Message?.Contains("[noise]") == true) return null; return data; }; // Filter by report type — return true to skip client.SkipReport = (ReportFilterType type, Exception ex, string msg) => { // Only forward hangs and unhandled exceptions to Backtrace return type != ReportFilterType.Hang && type != ReportFilterType.UnhandledException; }; // Notification when the per-minute rate limit is hit client.OnClientReportLimitReached = (BacktraceReport report) => { Debug.LogWarning("Rate limit reached, dropped: " + report.Message); }; // Server-side error notification client.OnServerError = (Exception serverEx) => { Debug.LogError("Backtrace server error: " + serverEx.Message); }; // Custom HTTP handler (replaces default UnityWebRequest) client.RequestHandler = (string url, BacktraceData data) => { Debug.Log("Would POST to: " + url); return new BacktraceResult(); }; // Observe every unhandled exception before Backtrace processes it client.OnUnhandledApplicationException = (Exception ex) => { Debug.Log("Unhandled: " + ex.GetType().Name); }; // Adjust rate limit at runtime (0 = disable all sends) client.SetClientReportLimit(100); } } ``` -------------------------------- ### BacktraceClient Attributes - Per-report and global metadata Source: https://context7.com/backtrace-labs/backtrace-unity/llms.txt Explains how to attach key-value string metadata to reports using indexers and `SetAttribute`/`SetAttributes` methods. These attributes apply to all subsequent reports, including native crashes. ```APIDOC ## `BacktraceClient` attributes — Per-report and global metadata The indexer and `SetAttribute`/`SetAttributes` methods attach key-value string metadata to every subsequent report, including native crashes. The native layer is updated in the same call. ### Setting Single Attributes via Indexer ```csharp var client = BacktraceClient.Instance; client["player.id"] = "user-8821"; client["session.mode"] = "ranked"; ``` ### Setting Single Attributes via `SetAttribute` ```csharp // Via SetAttribute (returns false for null/empty key) bool ok = client.SetAttribute("build.commit", "abc1234"); ``` ### Setting Multiple Attributes via `SetAttributes` ```csharp client.SetAttributes(new Dictionary { { "matchmaking.region", "EU-West" }, { "graphics.quality", "High" } }); ``` ### Getting Attribute Count ```csharp Debug.Log("Total attributes: " + client.GetAttributesCount()); ``` ``` -------------------------------- ### BacktraceClient.Send - Manual Report Submission Source: https://context7.com/backtrace-labs/backtrace-unity/llms.txt Demonstrates the three overloads for sending reports: plain messages, captured exceptions, and pre-built BacktraceReport objects. All methods are non-blocking and support an optional callback for asynchronous server response delivery. ```APIDOC ## `BacktraceClient.Send` — Manual report submission Three overloads cover plain-message reports, captured exceptions, and pre-built `BacktraceReport` objects. All are non-blocking (coroutine-based). The optional `sendCallback` delivers the server response asynchronously. ### Overload 1: Send a plain diagnostic message ```csharp _client.Send( message: "Checkpoint reached: level 3 loaded", attributes: new Dictionary { { "level.id", "3" } }); ``` ### Overload 2: Send a caught exception with an attachment ```csharp try { int[] arr = new int[0]; int _ = arr[5]; // IndexOutOfRangeException } catch (Exception ex) { _client.Send( exception: ex, attachmentPaths: new List { Application.persistentDataPath + "/save.dat" }, attributes: new Dictionary { { "scene", "MainMenu" } }); } ``` ### Overload 3: Build a BacktraceReport explicitly and provide a send callback ```csharp try { throw new InvalidOperationException("State machine error"); } catch (Exception ex) { var report = new BacktraceReport( exception: ex, attributes: new Dictionary { { "state", "Idle" } }, attachmentPaths: new List()); // Optional: override deduplication fingerprint report.Fingerprint = "state-machine-idle-invariant"; // Optional: override grouping factor report.Factor = "state-machine"; _client.Send(report, result => { // BacktraceResultStatus: Ok | NetworkError | LimitReached | Empty if (result.Status == Backtrace.Unity.Types.BacktraceResultStatus.Ok) Debug.Log("Report sent. Object id: " + result.Object); else Debug.LogWarning("Send failed: " + result.Message); }); } ``` ``` -------------------------------- ### BacktraceClient.EnableMetrics and IBacktraceMetrics Source: https://context7.com/backtrace-labs/backtrace-unity/llms.txt Enables the metrics subsystem to send unique-event and summed-event data to Backtrace for crash-free users and sessions dashboards. This feature is not supported on WebGL. ```APIDOC ## `BacktraceClient.EnableMetrics` / `IBacktraceMetrics` — Crash-free users and sessions The metrics subsystem periodically sends unique-event and summed-event data to Backtrace to power crash-free-users/sessions dashboards. Not supported on WebGL. ### Usage ```csharp // Enable via configuration (auto-starts on Refresh() when config flag is set) // OR enable manually here (overrides config flag): bool enabled = client.EnableMetrics(); // uses guid as unique attribute // — or with a custom unique attribute (e.g. Steam ID stored as attribute): // bool enabled = client.EnableMetrics("steam.id"); // — or with explicit URLs and interval (seconds): // bool enabled = client.EnableMetrics( // uniqueEventsSubmissionUrl: "https://events.backtrace.io/unique/TOKEN", // summedEventsSubmissionUrl: "https://events.backtrace.io/summed/TOKEN", // timeIntervalInSec: 1800, // 30 min // uniqueAttributeName: "guid"); IBacktraceMetrics metrics = client.Metrics; if (metrics == null) return; // Track a game event (must be configured server-side as a summed event group) metrics.AddSummedEvent("level-completed"); metrics.AddSummedEvent("item-purchased", new Dictionary { { "item.category", "weapon" }, { "item.price", "4.99" } }); // Inspect limits metrics.MaximumSummedEvents = 100; metrics.MaximumUniqueEvents = 10; // Access session ID Debug.Log("Session: " + metrics.SessionId); // Manual flush (also triggered automatically at the configured interval) metrics.Send(); ``` ### Parameters for `EnableMetrics` - `uniqueEventsSubmissionUrl` (string, Optional): URL for submitting unique events. - `summedEventsSubmissionUrl` (string, Optional): URL for submitting summed events. - `timeIntervalInSec` (int, Optional): Interval in seconds for sending metrics. - `uniqueAttributeName` (string, Optional): The name of the attribute to use as a unique identifier for events. ### Properties of `IBacktraceMetrics` - `MaximumSummedEvents` (int): Gets or sets the maximum number of summed events to track. - `MaximumUniqueEvents` (int): Gets or sets the maximum number of unique events to track. - `SessionId` (string): Gets the current session ID. ### Methods of `IBacktraceMetrics` - `AddSummedEvent(string eventName, Dictionary attributes = null)`: Tracks a summed event. - `Send()`: Manually flushes all tracked metrics. ``` -------------------------------- ### Manage Offline Storage with BacktraceDatabase Source: https://context7.com/backtrace-labs/backtrace-unity/llms.txt Persists reports to disk for offline storage and automatic retransmission. Inspect database state, adjust screenshot quality and size, and modify deduplication strategies. Supports iterating, flushing, sending, clearing, deleting records, and reloading configuration. ```csharp using Backtrace.Unity; using Backtrace.Unity.Model.Database; using Backtrace.Unity.Types; using UnityEngine; public class DatabaseExample : MonoBehaviour { void Start() { var db = BacktraceDatabase.Instance; if (db == null || !db.Enabled()) return; // Inspect state Debug.Log("Stored records: " + db.Count()); Debug.Log("Database size (bytes): " + db.GetDatabaseSize()); Debug.Log("Consistent: " + db.ValidConsistency()); // Screenshot quality for attachments (0–100) db.ScreenshotQuality = 75; db.ScreenshotMaxHeight = 720; // Change deduplication strategy at runtime db.DeduplicationStrategy = DeduplicationStrategy.Default | DeduplicationStrategy.Classifier; // Iterate stored records foreach (BacktraceDatabaseRecord record in db.Get()) { Debug.Log("Record: " + record.Id + " duplicates: " + record.Count); } // Force send all records ignoring rate limits db.Flush(); // Respect rate limits during retry db.Send(); // Wipe all stored data db.Clear(); // Delete a single record var first = db.Get().GetEnumerator(); if (first.MoveNext()) db.Delete(first.Current); // Reload configuration (call after changing Configuration properties) db.Reload(); } } ``` -------------------------------- ### Enable Backtrace Metrics and Track Events Source: https://context7.com/backtrace-labs/backtrace-unity/llms.txt Enables the metrics subsystem to send unique-event and summed-event data to Backtrace. Not supported on WebGL. Metrics can be enabled via configuration or manually, with options for custom attributes, URLs, and intervals. Use AddSummedEvent to track game events and inspect limits and session IDs. ```csharp #if !UNITY_WEBGL using Backtrace.Unity; using Backtrace.Unity.Interfaces; using System.Collections.Generic; using UnityEngine; public class MetricsExample : MonoBehaviour { void Start() { var client = BacktraceClient.Instance; // Enable via configuration (auto-starts on Refresh() when config flag is set) // OR enable manually here (overrides config flag): bool enabled = client.EnableMetrics(); // uses guid as unique attribute // — or with a custom unique attribute (e.g. Steam ID stored as attribute): // bool enabled = client.EnableMetrics("steam.id"); // — or with explicit URLs and interval (seconds): // bool enabled = client.EnableMetrics( // uniqueEventsSubmissionUrl: "https://events.backtrace.io/unique/TOKEN", // summedEventsSubmissionUrl: "https://events.backtrace.io/summed/TOKEN", // timeIntervalInSec: 1800, // 30 min // uniqueAttributeName: "guid"); IBacktraceMetrics metrics = client.Metrics; if (metrics == null) return; // Track a game event (must be configured server-side as a summed event group) metrics.AddSummedEvent("level-completed"); metrics.AddSummedEvent("item-purchased", new Dictionary { { "item.category", "weapon" }, { "item.price", "4.99" } }); // Inspect limits metrics.MaximumSummedEvents = 100; metrics.MaximumUniqueEvents = 10; // Access session ID Debug.Log("Session: " + metrics.SessionId); // Manual flush (also triggered automatically at the configured interval) metrics.Send(); } } #endif ``` -------------------------------- ### Construct Custom Backtrace Reports Source: https://context7.com/backtrace-labs/backtrace-unity/llms.txt Creates custom reports using `BacktraceReport`, wrapping messages or exceptions with attributes, attachments, and fingerprinting hints. Supports setting client-side deduplication fingerprints, grouping factors, and Proguard symbolication for Android. ```csharp using Backtrace.Unity.Model; using System; using System.Collections.Generic; // Message report var msgReport = new BacktraceReport( message: "Player fell through the floor", attributes: new Dictionary { { "map", "dungeon-01" } }, attachmentPaths: new List { "/persistent/screenshot.jpg" }); // Exception report try { throw new OverflowException("Score overflow"); } catch (Exception ex) { var exReport = new BacktraceReport( exception: ex, attributes: new Dictionary { { "score", "99999" } }, attachmentPaths: new List()); // Client-side deduplication fingerprint (overrides auto-generated hash) exReport.Fingerprint = "score-overflow-stable"; // Grouping factor exReport.Factor = "score-system"; // Proguard symbolication (Android only) // exReport.UseSymbolication("proguard"); } ``` -------------------------------- ### BacktraceClient.UseProguard Source: https://context7.com/backtrace-labs/backtrace-unity/llms.txt Attaches a Proguard symbolication ID to all subsequent reports for Android builds to deobfuscate stack traces. ```APIDOC ## `BacktraceClient.UseProguard` — Android Proguard deobfuscation (Android only) Attaches a Proguard symbolication ID to all subsequent reports so the Backtrace server can deobfuscate stack traces from ProGuard-processed Android builds. ```csharp #if UNITY_ANDROID using Backtrace.Unity; using UnityEngine; public class AndroidSetup : MonoBehaviour { void Start() { var client = BacktraceClient.Instance; // symbolicationId must match the mapping file uploaded to Backtrace client.UseProguard("a1b2c3d4-proguard-map-id"); } } #endif ``` ``` -------------------------------- ### Manage Report Attachments Source: https://context7.com/backtrace-labs/backtrace-unity/llms.txt Add arbitrary file paths to all managed reports after initialization using `AddAttachment`. Native reports can only receive attachments at initialization time via `BacktraceConfiguration.AttachmentPaths`. Use `GetAttachments` to inspect registered attachments. ```csharp using Backtrace.Unity; using System.Linq; using UnityEngine; public class AttachmentExample : MonoBehaviour { void Start() { var client = BacktraceClient.Instance; // Add a log file to all future managed reports client.AddAttachment(Application.persistentDataPath + "/player.log"); client.AddAttachment(Application.persistentDataPath + "/settings.json"); // Inspect registered attachments foreach (var path in client.GetAttachments()) Debug.Log("Attachment: " + path); Debug.Log("Count: " + client.GetAttachments().Count()); } } ``` -------------------------------- ### Send Plain Message with Attributes Source: https://context7.com/backtrace-labs/backtrace-unity/llms.txt Submits a simple diagnostic message with associated key-value attributes. Useful for tracking specific events or checkpoints in your application. ```csharp using Backtrace.Unity; using Backtrace.Unity.Model; using System; using System.Collections.Generic; using UnityEngine; public class ReportingExample : MonoBehaviour { private BacktraceClient _client; void Awake() { _client = BacktraceClient.Instance ?? GetComponent(); } // 1. Send a plain diagnostic message public void SendMessage() { _client.Send( message: "Checkpoint reached: level 3 loaded", attributes: new Dictionary { { "level.id", "3" } }); } // 2. Send a caught exception with an attachment public void SendException() { try { int[] arr = new int[0]; int _ = arr[5]; // IndexOutOfRangeException } catch (Exception ex) { _client.Send( exception: ex, attachmentPaths: new List { Application.persistentDataPath + "/save.dat" }, attributes: new Dictionary { { "scene", "MainMenu" } }); } } // 3. Build a BacktraceReport explicitly and provide a send callback public void SendReport() { try { throw new InvalidOperationException("State machine error"); } catch (Exception ex) { var report = new BacktraceReport( exception: ex, attributes: new Dictionary { { "state", "Idle" } }, attachmentPaths: new List()); // Optional: override deduplication fingerprint report.Fingerprint = "state-machine-idle-invariant"; // Optional: override grouping factor report.Factor = "state-machine"; _client.Send(report, result => { // BacktraceResultStatus: Ok | NetworkError | LimitReached | Empty if (result.Status == Backtrace.Unity.Types.BacktraceResultStatus.Ok) Debug.Log("Report sent. Object id: " + result.Object); else Debug.LogWarning("Send failed: " + result.Message); }); } } } ``` -------------------------------- ### BacktraceDatabase — Offline storage and retry Source: https://context7.com/backtrace-labs/backtrace-unity/llms.txt Persists reports to disk when the network is unavailable and retransmits them on the next run. It is automatically attached to the same GameObject as BacktraceClient when Initialize is used with a database path. ```APIDOC ## `BacktraceDatabase` — Offline storage and retry `BacktraceDatabase` persists reports to disk when the network is unavailable and retransmits them on the next run. It is automatically attached to the same GameObject as `BacktraceClient` when `Initialize` is used with a database path. ### Usage ```csharp var db = BacktraceDatabase.Instance; if (db == null || !db.Enabled()) return; // Inspect state Debug.Log("Stored records: " + db.Count()); Debug.Log("Database size (bytes): " + db.GetDatabaseSize()); Debug.Log("Consistent: " + db.ValidConsistency()); // Screenshot quality for attachments (0–100) db.ScreenshotQuality = 75; db.ScreenshotMaxHeight = 720; // Change deduplication strategy at runtime db.DeduplicationStrategy = DeduplicationStrategy.Default | DeduplicationStrategy.Classifier; // Iterate stored records foreach (BacktraceDatabaseRecord record in db.Get()) { Debug.Log("Record: " + record.Id + " duplicates: " + record.Count); } // Force send all records ignoring rate limits db.Flush(); // Respect rate limits during retry db.Send(); // Wipe all stored data db.Clear(); // Delete a single record var first = db.Get().GetEnumerator(); if (first.MoveNext()) db.Delete(first.Current); // Reload configuration (call after changing Configuration properties) db.Reload(); ``` ### Properties of `BacktraceDatabase` - `ScreenshotQuality` (int): Quality of screenshots for attachments (0-100). - `ScreenshotMaxHeight` (int): Maximum height of screenshots for attachments. - `DeduplicationStrategy` (DeduplicationStrategy): Strategy used for deduplicating records. ### Methods of `BacktraceDatabase` - `Count()`: Returns the number of stored records. - `GetDatabaseSize()`: Returns the size of the database in bytes. - `ValidConsistency()`: Checks if the database is consistent. - `Get()`: Returns an enumerable collection of stored records. - `Flush()`: Forces sending all stored records, ignoring rate limits. - `Send()`: Sends stored records, respecting rate limits. - `Clear()`: Wipes all stored data. - `Delete(BacktraceDatabaseRecord record)`: Deletes a single specified record. - `Reload()`: Reloads the database configuration. ``` -------------------------------- ### Enable Proguard Deobfuscation for Android Source: https://context7.com/backtrace-labs/backtrace-unity/llms.txt Attaches a Proguard symbolication ID to all subsequent reports for Android builds. The symbolication ID must match the mapping file uploaded to Backtrace. ```csharp #if UNITY_ANDROID using Backtrace.Unity; using UnityEngine; public class AndroidSetup : MonoBehaviour { void Start() { var client = BacktraceClient.Instance; // symbolicationId must match the mapping file uploaded to Backtrace client.UseProguard("a1b2c3d4-proguard-map-id"); } } #endif ``` -------------------------------- ### BacktraceClient Breadcrumbs Support Source: https://context7.com/backtrace-labs/backtrace-unity/llms.txt Enables a chronological trail of events attached to every report. ```APIDOC ## `BacktraceClient.EnableBreadcrumbsSupport` / `IBacktraceBreadcrumbs` — Structured event trail Breadcrumbs record a chronological trail of events (navigation, user actions, system events, log messages) that is attached to every report. The database must be enabled and `EnableBreadcrumbsSupport` must be `true` in `BacktraceConfiguration`. ```csharp using Backtrace.Unity; using Backtrace.Unity.Model.Breadcrumbs; using System.Collections.Generic; using UnityEngine; public class BreadcrumbExample : MonoBehaviour { private IBacktraceBreadcrumbs _crumbs; void Start() { var client = BacktraceClient.Instance; // Activate breadcrumbs (requires database enabled in config) bool activated = client.EnableBreadcrumbsSupport(); Debug.Log("Breadcrumbs active: " + activated); _crumbs = client.Breadcrumbs; if (_crumbs == null) return; // Severity-based helpers _crumbs.Info("Game session started"); _crumbs.Warning("Low memory warning received"); _crumbs.Debug("AI path-finding recalculated", new Dictionary { { "agent.id", "enemy-42" }, { "nodes", "17" } }); _crumbs.Exception("Serialization partial failure"); // Generic Log — full control over BreadcrumbLevel and LogType _crumbs.Log( message: "Player purchased item", level: BreadcrumbLevel.User, logType: LogType.Log, attributes: new Dictionary { { "item.id", "sword-99" } }); // Clear all stored breadcrumbs (e.g. on new game session) _crumbs.ClearBreadcrumbs(); // Retrieve the breadcrumb log file path (useful for manual attachment) string logPath = _crumbs.GetBreadcrumbLogPath(); Debug.Log("Breadcrumb file: " + logPath); } void OnLevelLoaded(int level) { _crumbs?.Log( message: $"Level {level} loaded", logType: LogType.Log, attributes: new Dictionary { { "level", level.ToString() } }); } } ``` ``` -------------------------------- ### Attachment management — AddAttachment / GetAttachments Source: https://context7.com/backtrace-labs/backtrace-unity/llms.txt Allows attaching arbitrary file paths to managed reports after initialization. Native reports require attachments at initialization. ```APIDOC ## Attachment management — `AddAttachment` / `GetAttachments` Attach arbitrary file paths to every managed report after initialization. Native reports can only receive attachments at initialization time via `BacktraceConfiguration.AttachmentPaths`. ```csharp using Backtrace.Unity; using System.Linq; using UnityEngine; public class AttachmentExample : MonoBehaviour { void Start() { var client = BacktraceClient.Instance; // Add a log file to all future managed reports client.AddAttachment(Application.persistentDataPath + "/player.log"); client.AddAttachment(Application.persistentDataPath + "/settings.json"); // Inspect registered attachments foreach (var path in client.GetAttachments()) Debug.Log("Attachment: " + path); Debug.Log("Count: " + client.GetAttachments().Count()); } } ``` ``` -------------------------------- ### Set Global Attributes for Reports Source: https://context7.com/backtrace-labs/backtrace-unity/llms.txt Configures global attributes that will be appended to all subsequent reports sent by the client. This method supports both individual attribute setting and bulk updates. ```csharp using Backtrace.Unity; using System.Collections.Generic; using UnityEngine; public class AttributeExample : MonoBehaviour { void Start() { var client = BacktraceClient.Instance; // Single attribute via indexer client["player.id"] = "user-8821"; client["session.mode"] = "ranked"; // Via SetAttribute (returns false for null/empty key) bool ok = client.SetAttribute("build.commit", "abc1234"); // Bulk update client.SetAttributes(new Dictionary { { "matchmaking.region", "EU-West" }, { "graphics.quality", "High" } }); Debug.Log("Total attributes: " + client.GetAttributesCount()); } } ``` -------------------------------- ### BacktraceClient Event Hooks Source: https://context7.com/backtrace-labs/backtrace-unity/llms.txt Allows inspection or mutation of reports before transmission, selective filtering, and custom server-error handling. ```APIDOC ## `BacktraceClient` event hooks — Intercept and filter reports Four delegate properties allow inspection or mutation of reports before transmission, selective filtering, and custom server-error handling. ```csharp using Backtrace.Unity; using Backtrace.Unity.Model; using Backtrace.Unity.Types; using System; using UnityEngine; public class EventHookExample : MonoBehaviour { void Start() { var client = BacktraceClient.Instance; // Mutate or discard a report — returning null drops it client.BeforeSend = (BacktraceData data) => { data.Attributes.Attributes["custom.tag"] = "processed"; // Drop reports tagged as noise if (data.Report?.Message?.Contains("[noise]") == true) return null; return data; }; // Filter by report type — return true to skip client.SkipReport = (ReportFilterType type, Exception ex, string msg) => { // Only forward hangs and unhandled exceptions to Backtrace return type != ReportFilterType.Hang && type != ReportFilterType.UnhandledException; }; // Notification when the per-minute rate limit is hit client.OnClientReportLimitReached = (BacktraceReport report) => { Debug.LogWarning("Rate limit reached, dropped: " + report.Message); }; // Server-side error notification client.OnServerError = (Exception serverEx) => { Debug.LogError("Backtrace server error: " + serverEx.Message); }; // Custom HTTP handler (replaces default UnityWebRequest) client.RequestHandler = (string url, BacktraceData data) => { Debug.Log("Would POST to: " + url); return new BacktraceResult(); }; // Observe every unhandled exception before Backtrace processes it client.OnUnhandledApplicationException = (Exception ex) => { Debug.Log("Unhandled: " + ex.GetType().Name); }; // Adjust rate limit at runtime (0 = disable all sends) client.SetClientReportLimit(100); } } ``` ``` -------------------------------- ### BacktraceReport — Report construction Source: https://context7.com/backtrace-labs/backtrace-unity/llms.txt Represents a DTO that wraps either a plain message or an exception along with attributes, attachments, and optional fingerprinting hints. ```APIDOC ## `BacktraceReport` — Report construction `BacktraceReport` is the DTO that wraps either a plain message or an exception together with attributes, attachments, and optional fingerprinting hints. ### Usage ```csharp // Message report var msgReport = new BacktraceReport( message: "Player fell through the floor", attributes: new Dictionary { { "map", "dungeon-01" } }, attachmentPaths: new List { "/persistent/screenshot.jpg" }); // Exception report try { throw new OverflowException("Score overflow"); } catch (Exception ex) { var exReport = new BacktraceReport( exception: ex, attributes: new Dictionary { { "score", "99999" } }, attachmentPaths: new List()); // Client-side deduplication fingerprint (overrides auto-generated hash) exReport.Fingerprint = "score-overflow-stable"; // Grouping factor exReport.Factor = "score-system"; // Proguard symbolication (Android only) // exReport.UseSymbolication("proguard"); } ``` ### Constructors for `BacktraceReport` - `BacktraceReport(string message, Dictionary attributes = null, IList attachmentPaths = null)`: Creates a report from a message. - `BacktraceReport(Exception exception, Dictionary attributes = null, IList attachmentPaths = null)`: Creates a report from an exception. ### Properties of `BacktraceReport` - `Fingerprint` (string): A client-side deduplication fingerprint that overrides the auto-generated hash. - `Factor` (string): A grouping factor for the report. ### Methods of `BacktraceReport` - `UseSymbolication(string type)`: Enables symbolication for the report (e.g., "proguard" for Android). ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.