### Emit a Distribution Metric in Unity with Sentry Source: https://docs.sentry.io/platforms/unity/metrics Capture a set of values for statistical analysis, such as percentiles, min, max, and average, using Sentry's distribution metric API. This example emits a distribution for scene load times. ```csharp // Add '15.0' to a distribution used for tracking the loading times per scene. SentrySdk.Experimental.Metrics.EmitDistribution("scene_load", 15.0, MeasurementUnit.Duration.Millisecond, new[] { new KeyValuePair("scene", "Level1") }); ``` -------------------------------- ### Install Sentry SDK for Unity via Package Manager Source: https://docs.sentry.io/platforms/unity/index Instructions to install the Sentry SDK for Unity using the Unity Package Manager with a Git URL. You can specify a version by appending it to the URL. ```bash https://github.com/getsentry/unity.git # To use a specific version, append #, e.g., #4.1.1 ``` -------------------------------- ### Verify Sentry Unity SDK Setup with C# Source: https://docs.sentry.io/platforms/unity/index This C# script demonstrates how to verify your Sentry Unity SDK setup. It logs various message types (Info, Warning, Error) which are captured as breadcrumbs, and then intentionally throws a NullReferenceException to ensure errors are captured by Sentry. This snippet is intended to be run within a Unity MonoBehaviour. ```csharp using UnityEngine; public class TestMonoBehaviour : MonoBehaviour { private GameObject testObject = null; void Start() { Debug.Log("Captured Log"); // Adds a Breadcrumb Debug.LogWarning("Captured Warning"); // Adds a Breadcrumb Debug.LogError("Captured Error"); // Get's captured as an Error by default // This will throw an unhandled 'NullReferenceException' testObject.GetComponent(); // Get's captured as an Error } } ``` -------------------------------- ### Sentry Unity SDK API Call Example Source: https://docs.sentry.io/platforms/unity/migration This snippet demonstrates an API call to capture a message using the Sentry SDK. Calls like this are expected to continue working without changes after migrating from Sentry Unity Lite to the Sentry Unity SDK. ```csharp SentrySdk.CaptureMessage("Test event"); ``` -------------------------------- ### Create a Transaction for User Interaction in C# Source: https://docs.sentry.io/platforms/unity/tracing/instrumentation/custom-instrumentation This example shows how to create a transaction for a specific user action like checkout, including starting child spans for distinct operations within that action. It associates the transaction with the current scope for error reporting. ```csharp public async Task PerformCheckoutAsync() { var transaction = SentrySdk.StartTransaction( "checkout", "perform-checkout" ); SentrySdk.ConfigureScope(scope => scope.Transaction = transaction); var validationSpan = transaction.StartChild( "validation", "validating shopping cart" ); await ValidateShoppingCartAsync(); validationSpan.Finish(); var processSpan = transaction.StartChild( "process", "processing shopping cart" ) await ProcessShoppingCartAsync(); processSpan.Finish(); transaction.Finish(); } ``` -------------------------------- ### Emit a Counter Metric in Unity with Sentry Source: https://docs.sentry.io/platforms/unity/metrics Record the occurrences of a specific event using Sentry's counter metric API. This example shows how to emit a counter with a value and associated tags. ```csharp // Record five total player interactions SentrySdk.Experimental.Metrics.EmitCounter("player_interaction", 5, new[] { new KeyValuePair("scene", "MainMenu"), new KeyValuePair("app_version", "1.0.0") }); ``` -------------------------------- ### Start and Finish Transactions and Spans in C# Source: https://docs.sentry.io/platforms/unity/tracing/instrumentation/custom-instrumentation This snippet demonstrates the basic usage of Sentry SDK for starting and finishing transactions and their child spans. It requires the Sentry SDK to be initialized. ```csharp var transaction = SentrySdk.StartTransaction( "test-transaction-name", "test-transaction-operation" ); var span = transaction.StartChild("test-child-operation"); // ... // (Perform the operation represented by the span/transaction) // ... span.Finish(); transaction.Finish(); ``` -------------------------------- ### Programmatic Configuration in Sentry for Unity Source: https://docs.sentry.io/platforms/unity/migration Demonstrates how to configure Sentry options programmatically in Unity using the `OptionsConfiguration` script. It shows how to apply platform-specific settings using preprocessor directives for iOS and Android, along with common configurations. ```csharp public class SentryOptionsConfiguration : OptionsConfiguration { public override void Configure(SentryUnityOptions options) { #if UNITY_IOS // iOS-specific configuration options.IosNativeInitializationType = NativeInitializationType.Runtime; #elif UNITY_ANDROID // Android-specific configuration options.AndroidNativeInitializationType = NativeInitializationType.Runtime; #endif // Common configuration options.Debug = true; } } ``` -------------------------------- ### Emit a Gauge Metric in Unity with Sentry Source: https://docs.sentry.io/platforms/unity/metrics Track values that can fluctuate over time, like current memory usage or temperature, using Sentry's gauge metric API. This example emits a gauge for scene load times. ```csharp // Add '15.0' to a gauge used for tracking the loading times for a scene. SentrySdk.Experimental.Metrics.EmitGauge("scene_load", 15.0, MeasurementUnit.Duration.Millisecond, new[] { new KeyValuePair("scene", "Level1") }); ``` -------------------------------- ### Force Transaction Sampling Decision in Unity Source: https://docs.sentry.io/platforms/unity/configuration/sampling Demonstrates how to create a `TransactionContext` with a predefined sampling decision (true for sampled) and start a transaction with it. This bypasses `TracesSampleRate` and `TracesSampler` for this specific transaction. ```csharp var transactionContext = new TransactionContext("GET /search", "http", true); var transaction = SentrySdk.StartTransaction(transactionContext); ``` -------------------------------- ### Configure Sentry DSN in Unity Source: https://docs.sentry.io/platforms/unity/index Example of a JSON configuration file for Sentry in Unity, specifying the public DSN. This configuration is saved in Assets/Resources/Sentry/SentryOptions.asset. ```json { "public-dsn": "___PUBLIC_DSN___" } ``` -------------------------------- ### Enable Automatic Tracing in Unity with C# Source: https://docs.sentry.io/platforms/unity/tracing/instrumentation/automatic-instrumentation This C# code snippet demonstrates how to programmatically enable automatic tracing for scene loading and application startup within the Sentry SDK for Unity. It requires the Sentry Unity SDK to be installed and configured. The `Configure` method modifies the `SentryUnityOptions` to activate these tracing features. ```csharp public override void Configure(SentryUnityOptions options) { options.AutoSceneLoadTraces = true; options.AutoStartupTraces = true; } ``` -------------------------------- ### Using `IDisposable` for Span and Transaction Lifecycle Source: https://docs.sentry.io/platforms/unity/migration Shows how spans and transactions in Sentry for Unity now implement `IDisposable`, allowing them to be used with `using` statements or declarations. This ensures spans and transactions are automatically finished with an OK status when they go out of scope. ```csharp using (var transaction = SentrySdk.StartTransaction("my-transaction", "operation")) { // Transaction will automatically finish when the using block exits } ``` ```csharp // Or with using declaration using var span = transaction.StartChild("child-operation"); // Span will automatically finish at the end of the scope ``` -------------------------------- ### Group Unity Errors Granularly with Custom Exception Source: https://docs.sentry.io/platforms/unity/usage/sdk-fingerprinting This C# example shows how to group Unity errors more granularly by including custom exception attributes in the fingerprint. It defines a `MyRpcException` with `Function` and `Code` properties and uses `{{ default }}` along with these attributes to create a more specific fingerprint. This is useful when the stack trace is similar but the underlying RPC call or API response differs. ```csharp public class MyRpcException : Exception { // The name of the RPC function that was called (e.g. "getAllBlogArticles") public string Function { get; set; } // For example a HTTP status code returned by the server. public HttpStatusCode Code { get; set; } } // Add this to the SDK initialization callback options.SetBeforeSend(@event => { if (@event.Exception is MyRpcException ex) { @event.SetFingerprint( new [] { "{{ default }}", ex.Function, ex.Code.ToString(), } ); } return @event; }); ``` -------------------------------- ### Enable Sentry Metrics Programmatically in Unity Source: https://docs.sentry.io/platforms/unity/metrics Configure Sentry SDK to enable metrics collection within a Unity application. This is done via a callback function during SDK initialization or manual initialization. ```csharp public override void Configure(SentryUnityOptions options) { options.Experimental.EnableMetrics = true; } ``` ```csharp SentrySdk.Init(options => { options.Dsn = "___PUBLIC_DSN___"; // Enable metrics to be sent to Sentry options.Experimental.EnableMetrics = true; }); ``` -------------------------------- ### Login and Upload Debug Files using sentry-cli Source: https://docs.sentry.io/platforms/unity/data-management/debug-files/upload This snippet demonstrates how to log in to sentry-cli and upload debug files for a specified organization and project. It requires the organization slug, project slug, and the path to the directory containing the debug files. Ensure you have sentry-cli installed and configured. ```bash sentry-cli login sentry-cli debug-files upload -o {YOUR ORGANISATION} -p {PROJECT} bin/Release ``` -------------------------------- ### Remove Old Sentry Unity Lite Initialization Source: https://docs.sentry.io/platforms/unity/migration This snippet shows the old way of initializing the Sentry Unity Lite SDK, which needs to be removed when migrating to the new Sentry Unity SDK. It highlights the specific line of code to be deleted from your project. ```csharp gameObject.AddComponent().Dsn = "___PUBLIC_DSN___"; ``` -------------------------------- ### AutoStartupTraces Configuration Source: https://docs.sentry.io/platforms/unity/configuration/options Controls whether the SDK automatically traces the application's startup sequence. ```APIDOC ## AutoStartupTraces ### Description Controls whether the SDK will automatically trace the app's startup. ### Method Configuration Option ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **AutoStartupTraces** (bool) - Optional - Set to `true` to enable automatic startup tracing, `false` to disable. Default is `true`. ### Request Example ```json { "AutoStartupTraces": false } ``` ### Response #### Success Response (200) N/A (This is a configuration option, not an endpoint) #### Response Example N/A ``` -------------------------------- ### Configure Traces Sample Rate in Unity SDK Source: https://docs.sentry.io/platforms/unity/tracing This snippet shows how to configure the Sentry SDK in Unity to capture 100% of transactions by setting the `TracesSampleRate` option during initialization. This is useful for testing and ensuring all transactions are sent. ```csharp // Add this to the SDK initialization callback // Example uniform sample rate: capture 100% of transactions options.TracesSampleRate = 1.0; ``` -------------------------------- ### Retrieve or Start a Span/Transaction in C# Source: https://docs.sentry.io/platforms/unity/tracing/instrumentation/custom-instrumentation This snippet illustrates how to retrieve an ongoing span or transaction using `SentrySdk.GetSpan()`. If none exists, it starts a new transaction; otherwise, it starts a child span on the existing one. This is useful for nested operations. ```csharp var span = SentrySdk.GetSpan(); if (span == null) { span = SentrySdk.StartTransaction("task", "op"); } else { span = span.StartChild("subtask"); } ``` -------------------------------- ### Manual Logging with SentrySdk.Logger in Unity Source: https://docs.sentry.io/platforms/unity/logs Demonstrates how to use the SentrySdk.Logger instance to send messages at different log levels (Info, Error) in Unity. These messages are sent to Sentry and can be searched in the Logs UI. Supports formatted messages. ```csharp SentrySdk.Logger.LogInfo("A simple debug log message"); SentrySdk.Logger.LogError("A {0} log message", "formatted"); ``` -------------------------------- ### Example of PDB Age Mismatch Source: https://docs.sentry.io/platforms/unity/data-management/debug-files/identifiers This example illustrates a PDB age mismatch, where the identifier in the PE file header differs from the actual PDB file's age. Sentry-cli can detect and associate these files if uploaded together, but divergence can occur if they are uploaded separately. ```text PE: 3003763b-afcb-4a97-aae3-28de8f188d7c-2 PDB: 3003763b-afcb-4a97-aae3-28de8f188d7c-4 ``` -------------------------------- ### ServerName Option Source: https://docs.sentry.io/platforms/unity/configuration/options Allows specifying a server name to be included with events, often corresponding to the device hostname. ```APIDOC ## ServerName Option ### Description This option can be used to supply a server name. When provided, the name of the server is sent along and persisted in the event. For many integrations, the server name actually corresponds to the device hostname, even in situations where the machine is not actually a server. ### Method Configuration Option ### Endpoint N/A (SDK Configuration) ### Parameters #### Query Parameters N/A #### Request Body N/A ### Request Example ```csharp SentryUnityOptions options = new SentryUnityOptions { ServerName = "my-unity-device" }; SentrySdk.Init(options); ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Compressing Debug Information in ELF Executables (Bash) Source: https://docs.sentry.io/platforms/unity/data-management/debug-files/file-formats This command uses `objcopy` with the `--compress-debug-sections=zlib` option to create a debug companion file (`binary.debug`) with compressed debug sections. This reduces the upload time and file size for debug information. ```bash objcopy --only-keep-debug --compress-debug-sections=zlib binary binary.debug ``` -------------------------------- ### Renaming Breadcrumb Level from Critical to Fatal Source: https://docs.sentry.io/platforms/unity/migration Illustrates the renaming of the `BreadcrumbLevel.Critical` enum value to `BreadcrumbLevel.Fatal`. This change aligns the Unity SDK's breadcrumb levels with those used in other Sentry SDKs for consistency. ```csharp SentrySdk.AddBreadcrumb("Critical error", level: BreadcrumbLevel.Critical); ``` ```csharp SentrySdk.AddBreadcrumb("Critical error", level: BreadcrumbLevel.Fatal); ``` -------------------------------- ### Updating User Feedback API Usage Source: https://docs.sentry.io/platforms/unity/migration Demonstrates the transition from the deprecated `SentrySdk.CaptureUserFeedback` method to the newer `SentrySdk.CaptureFeedback`. The updated API returns a `SentryId` and includes a `CaptureFeedbackResult` out parameter for success or failure indication. ```csharp SentrySdk.CaptureUserFeedback(new UserFeedback(eventId, "user@example.com", "User comment", "User Name")); ``` ```csharp var feedbackResult = SentrySdk.CaptureFeedback(new UserFeedback { Email = "user@example.com", Message = "User comment", Name = "User Name" }, out var captureResult); ``` -------------------------------- ### Verifying Compressed Debug Sections with readelf (Bash) Source: https://docs.sentry.io/platforms/unity/data-management/debug-files/file-formats This command uses `readelf -S` to list all section headers of a file and identify if debug sections are compressed. The output will show a 'C' flag for compressed sections, such as `.debug_info`. ```bash readelf -S path/to/file ``` -------------------------------- ### Add Data Attributes to Transactions in C# Source: https://docs.sentry.io/platforms/unity/tracing/instrumentation/custom-instrumentation This example demonstrates how to add custom data attributes (strings, numbers, booleans, and arrays) to a Sentry transaction using `SetData()`. These attributes are queryable in the Sentry trace explorer. ```csharp var transaction = SentrySdk.StartTransaction("ProcessOrderBatch()", "task"); SentrySdk.ConfigureScope(scope => scope.Transaction = transaction); transaction.SetData("my-data-attribute-1", "value1"); transaction.SetData("my-data-attribute-2", 42); transaction.SetData("my-data-attribute-3", true); transaction.SetData("my-data-attribute-4", new[] {"value1", "value2", "value3"}); transaction.SetData("my-data-attribute-5", new[] {42, 43, 44}); transaction.SetData("my-data-attribute-6", new[] {true, false, true}); ``` -------------------------------- ### Updating Screenshot Capture Callback Signature Source: https://docs.sentry.io/platforms/unity/migration Illustrates the change in the callback signature for `SetBeforeCaptureScreenshot`. The updated version now receives the `SentryEvent` object, allowing for context-aware decisions before capturing a screenshot. The previous version did not provide event context. ```csharp options.SetBeforeCaptureScreenshot(() => { return true; // Capture screenshot }); ``` ```csharp options.SetBeforeCaptureScreenshot(sentryEvent => { // You can now make decisions based on the actual event return sentryEvent.Level >= SentryLevel.Error; }); ``` -------------------------------- ### HttpProxy Configuration Source: https://docs.sentry.io/platforms/unity/configuration/options Configures an HTTP proxy to be used for outbound requests made by the SDK. This can also be used for HTTPS requests if `https-proxy` is not separately configured. ```APIDOC ## HttpProxy ### Description When set, a proxy can be configured that should be used for outbound requests. This is also used for HTTPS requests unless a separate `https-proxy` is configured. SDKs will attempt to default to the system-wide configured proxy, if possible. ### Method Configuration Option ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **HttpProxy** (string) - Optional - The URL of the HTTP proxy to use for outbound requests. ### Request Example ```json { "HttpProxy": "http://localhost:8080" } ``` ### Response #### Success Response (200) N/A (This is a configuration option, not an endpoint) #### Response Example N/A ``` -------------------------------- ### Implement Before-Send Log Handler in Unity Source: https://docs.sentry.io/platforms/unity/logs Customize log filtering and modification before sending to Sentry using a `BeforeSendLog` callback. This handler can discard logs or enrich them with custom attributes. ```csharp options.SetBeforeSendLog(log => { if (log.Message.StartsWith("Sensitive:")) { return null; } // Set a custom attribute for all other logs sent to Sentry log.SetAttribute("my.attribute", "value"); return log; }); ``` -------------------------------- ### Manually Initialize Sentry SDK in Unity Source: https://docs.sentry.io/platforms/unity/troubleshooting This C# code snippet shows how to manually initialize the Sentry SDK within a Unity project, which is a workaround for Android APK+OBB initialization failures. By embedding the DSN and other configuration options directly in code, it bypasses the reliance on ScriptableObject configuration files that might end up in OBBs. This method is recommended for Unity SDK versions 4.0.0 and later. ```csharp using Sentry; public class GameInitializer : MonoBehaviour { private void Start() { SentrySdk.Init(options => { options.Dsn = "YOUR_DSN_HERE"; options.Debug = true; // Add other configuration options as needed }); } } ``` -------------------------------- ### Start Transaction with Custom Sampling Context in Sentry Unity SDK Source: https://docs.sentry.io/platforms/unity/configuration/sampling Initiates a Sentry transaction with custom data that can be used by the sampling function. This allows sensitive or large data to influence sampling decisions without being attached directly to the transaction as tags or data. ```csharp // The following data will take part in the sampling decision var samplingContext = new Dictionary { ["user_id"] = 12312012, ["search_results"] = searchResults }; var transaction = SentrySdk.StartTransaction( new TransactionContext("GET /search", "http") samplingContext ); // The following is set on transaction, so does not take part in // the sampling decision transaction.Operation = "http"; transaction.Description = "search results"; ``` -------------------------------- ### Sample Transaction Events Uniformly in Unity Source: https://docs.sentry.io/platforms/unity/configuration/sampling Configure the Sentry SDK in Unity to send a uniform sample of transaction events. Set the `TracesSampleRate` option to a value between 0 and 1 during SDK initialization. This provides an even cross-section of transactions, with each transaction having a defined percentage chance of being sent. ```csharp // Add this to the SDK initialization callback options.TracesSampleRate = 0.2; ``` -------------------------------- ### Customize Sentry Diagnostic Logger Implementation in Unity Source: https://docs.sentry.io/platforms/unity/configuration/diagnostic-logger This code shows how to customize the diagnostic logger for Sentry in Unity. By default, messages are sent to the console. You can assign a custom `IDiagnosticLogger` implementation to the `DiagnosticLogger` option to redirect logs, for example, to trace listeners or files. ```csharp options.Debug = true; options.DiagnosticLogger = new ExampleDiagnosticLogger(SentryLevel.Debug); ``` -------------------------------- ### Updating View Hierarchy Capture Callback Signature Source: https://docs.sentry.io/platforms/unity/migration Shows the updated callback signature for `SetBeforeCaptureViewHierarchy`. Similar to screenshot capture, this callback now receives the `SentryEvent`, enabling conditional capture of the view hierarchy based on event details. The older signature lacked this contextual information. ```csharp options.SetBeforeCaptureViewHierarchy(() => { return true; // Capture view hierarchy }); ``` ```csharp options.SetBeforeCaptureViewHierarchy(sentryEvent => { // You can now make decisions based on the actual event return sentryEvent.Level >= SentryLevel.Error; }); ``` -------------------------------- ### Configure Automatic Unity Log Forwarding in Unity Source: https://docs.sentry.io/platforms/unity/logs Control which Unity log types are automatically forwarded to Sentry. This allows fine-grained control over log capture based on severity, and can be configured programmatically. ```csharp // Configure automatic log forwarding programmatically options.EnableLogs = true; options.CaptureStructuredLogsForLogType[LogType.Log] = false; options.CaptureStructuredLogsForLogType[LogType.Warning] = true; options.CaptureStructuredLogsForLogType[LogType.Assert] = true; options.CaptureStructuredLogsForLogType[LogType.Error] = true; options.CaptureStructuredLogsForLogType[LogType.Exception] = true; options.AddBreadcrumbsWithStructuredLogs = false; // Send as structured logs instead of breadcrumbs ``` -------------------------------- ### Manual Debug Symbol Upload using sentry-cli Source: https://docs.sentry.io/platforms/unity/native-support This command uploads debug symbols to Sentry using the sentry-cli tool. It requires authentication token, organization slug, project slug, and the path to the symbol files. This method is an alternative to the automated upload process. ```bash sentry-cli --auth-token ___ORG_AUTH_TOKEN___ debug-files upload --org ___ORG_SLUG___ --project ___PROJECT_SLUG___ PATH_TO_SYMBOLS ```