Overview
Follow the instructions below to install and configure the Datadog SDK for your platform.
This page describes how to instrument your web applications with the Datadog Browser SDK. The Browser SDK supports Real User Monitoring (RUM), Error Tracking, Session Replay, and Product Analytics.
The Browser SDK supports all modern desktop and mobile browsers.
Setup
Choose your setup method:
- Server-side auto-instrumentation: Automatically inject the RUM SDK into HTML responses through your web server or proxy.
- Agentic Onboarding (in Preview): Use AI coding agents (Cursor, Claude Code) to automatically instrument your application with one prompt.
- Manual client-side setup (below): Manually add the SDK to your application code.
Step 1 - Create the application in the UI
- In Datadog, navigate to Digital Experience > Add an Application and select the JavaScript (JS) application type.
- Enter a name for your application, then click Create Application. This generates a
clientTokenand anapplicationIdfor your application.
Step 2 - Install the Browser SDK
Choose the installation method for the Browser SDK.
Installing through Node Package Manager (npm) registry is recommended for modern web applications. The Browser SDK is packaged with the rest of your frontend JavaScript code. It has no impact on page load performance. However, the SDK may miss errors, resources, and user actions triggered before the SDK is initialized. Datadog recommends using a matching version with the Browser Logs SDK.
Add @datadog/browser-rum to your package.json file, for example if you use npm cli:
npm install --save @datadog/browser-rum
Installing through CDN async is recommended for web applications with performance targets. The Browser SDK loads from Datadog's CDN asynchronously, ensuring the SDK download does not impact page load performance. However, the SDK may miss errors, resources, and user actions triggered before the SDK is initialized.
Add the generated code snippet to the head tag of every HTML page you want to monitor in your application.
<script>
(function(h,o,u,n,d) {
h=h[d]=h[d]||{q:[],onReady:function(c){h.q.push(c)}}
d=o.createElement(u);d.async=1;d.src=n
n=o.getElementsByTagName(u)[0];n.parentNode.insertBefore(d,n)
})(window,document,'script','https://www.datadoghq-browser-agent.com/us1/v6/datadog-rum.js','DD_RUM')
</script>
<script>
(function(h,o,u,n,d) {
h=h[d]=h[d]||{q:[],onReady:function(c){h.q.push(c)}}
d=o.createElement(u);d.async=1;d.src=n
n=o.getElementsByTagName(u)[0];n.parentNode.insertBefore(d,n)
})(window,document,'script','https://www.datadoghq-browser-agent.com/eu/v6/datadog-rum.js','DD_RUM')
</script>
<script>
(function(h,o,u,n,d) {
h=h[d]=h[d]||{q:[],onReady:function(c){h.q.push(c)}}
d=o.createElement(u);d.async=1;d.src=n
n=o.getElementsByTagName(u)[0];n.parentNode.insertBefore(d,n)
})(window,document,'script','https://www.datadoghq-browser-agent.com/ap1/v6/datadog-rum.js','DD_RUM')
</script>
<script>
(function(h,o,u,n,d) {
h=h[d]=h[d]||{q:[],onReady:function(c){h.q.push(c)}}
d=o.createElement(u);d.async=1;d.src=n
n=o.getElementsByTagName(u)[0];n.parentNode.insertBefore(d,n)
})(window,document,'script','https://www.datadoghq-browser-agent.com/ap2/v6/datadog-rum.js','DD_RUM')
</script>
<script>
(function(h,o,u,n,d) {
h=h[d]=h[d]||{q:[],onReady:function(c){h.q.push(c)}}
d=o.createElement(u);d.async=1;d.src=n
n=o.getElementsByTagName(u)[0];n.parentNode.insertBefore(d,n)
})(window,document,'script','https://www.datadoghq-browser-agent.com/us3/v6/datadog-rum.js','DD_RUM')
</script>
<script>
(function(h,o,u,n,d) {
h=h[d]=h[d]||{q:[],onReady:function(c){h.q.push(c)}}
d=o.createElement(u);d.async=1;d.src=n
n=o.getElementsByTagName(u)[0];n.parentNode.insertBefore(d,n)
})(window,document,'script','https://www.datadoghq-browser-agent.com/us5/v6/datadog-rum.js','DD_RUM')
</script>
<script>
(function(h,o,u,n,d) {
h=h[d]=h[d]||{q:[],onReady:function(c){h.q.push(c)}}
d=o.createElement(u);d.async=1;d.src=n
n=o.getElementsByTagName(u)[0];n.parentNode.insertBefore(d,n)
})(window,document,'script','https://www.datadoghq-browser-agent.com/datadog-rum-v6.js','DD_RUM')
</script>
Installing through CDN sync is recommended for collecting all events. The Browser SDK loads from Datadog's CDN synchronously, ensuring the SDK loads first and collects all errors, resources, and user actions. This method may impact page load performance.
Add the generated code snippet to the head tag (in front of any other script tags) of every HTML page you want to monitor in your application. Placing the script tag higher and loading it synchronously ensures Datadog RUM can collect all performance data and errors.
<script
src="https://www.datadoghq-browser-agent.com/us1/v6/datadog-rum.js"
type="text/javascript">
</script>
<script
src="https://www.datadoghq-browser-agent.com/eu/v6/datadog-rum.js"
type="text/javascript">
</script>
<script
src="https://www.datadoghq-browser-agent.com/ap1/v6/datadog-rum.js"
type="text/javascript">
</script>
<script
src="https://www.datadoghq-browser-agent.com/ap2/v6/datadog-rum.js"
type="text/javascript">
</script>
<script
src="https://www.datadoghq-browser-agent.com/us3/v6/datadog-rum.js"
type="text/javascript">
</script>
<script
src="https://www.datadoghq-browser-agent.com/us5/v6/datadog-rum.js"
type="text/javascript">
</script>
<script
src="https://www.datadoghq-browser-agent.com/datadog-rum-v6.js"
type="text/javascript">
</script>
Step 3 - Initialize the Browser SDK
The SDK should be initialized as early as possible in the app lifecycle. This ensures all measurements are captured correctly.
In the initialization snippet, set an environment name, service name, and client token. See the full list of initialization parameters.
import { datadogRum } from '@datadog/browser-rum';
datadogRum.init({
applicationId: '<APP_ID>',
clientToken: '<CLIENT_TOKEN>',
// `site` refers to the Datadog site parameter of your organization
// see https://docs.datadoghq.com/getting_started/site/
site: '<DATADOG_SITE>',
// service: 'my-web-application',
// env: 'production',
// version: '1.0.0',
});
Types are compatible with TypeScript >= 3.8.2. For earlier versions of TypeScript, import JavaScript sources and use global variables to avoid any compilation issues.
import '@datadog/browser-rum/bundle/datadog-rum'
window.DD_RUM.init({
...
})
<script>
window.DD_RUM.onReady(function() {
window.DD_RUM.init({
clientToken: '<CLIENT_TOKEN>',
applicationId: '<APP_ID>',
// `site` refers to the Datadog site parameter of your organization
// see https://docs.datadoghq.com/getting_started/site/
site: '<DATADOG_SITE>',
// service: 'my-web-application',
// env: 'production',
// version: '1.0.0',
});
})
</script>
<script>
window.DD_RUM && window.DD_RUM.init({
clientToken: '<CLIENT_TOKEN>',
applicationId: '<APP_ID>',
// `site` refers to the Datadog site parameter of your organization
// see https://docs.datadoghq.com/getting_started/site/
site: '<DATADOG_SITE>',
// service: 'my-web-application',
// env: 'production',
// version: '1.0.0',
});
</script>
Configure tracking consent (GDPR compliance)
To be compliant with GDPR, CCPA, and similar regulations, the Browser SDK lets you provide the tracking consent value at initialization.
Configure Content Security Policy (CSP)
If you're using the Datadog Content Security Policy (CSP) integration on your site, see the CSP documentation for additional setup steps.
This page describes how to instrument your applications for Real User Monitoring (RUM) with the Android SDK. RUM includes Error Tracking by default, but if you have purchased Error Tracking as a standalone product, see the Error Tracking setup guide for specific steps.
The Datadog Android SDK supports Android 6.0+ (API level 23) and Android TV.
Setup
Choose your setup method:
- Agentic Onboarding (in Preview): Use AI coding agents (Cursor, Claude Code) to automatically instrument your application with one prompt. The agent detects your project structure and configures the RUM SDK for you.
- Manual setup (below): Follow the step-by-step instructions to manually add and configure the SDK.
Step 1 - Declare the Android SDK as a dependency
Declare dd-sdk-android-rum and the Gradle plugin as dependencies in your application module's build.gradle file.
buildscript {
dependencies {
classpath("com.datadoghq:dd-sdk-android-gradle-plugin:x.x.x")
}
}
plugins {
id("com.datadoghq.dd-sdk-android-gradle-plugin")
//(...)
}
android {
//(...)
}
dependencies {
implementation "com.datadoghq:dd-sdk-android-rum:x.x.x"
//(...)
}
Step 2 - Specify application details in the UI
- Navigate to Digital Experience > Add an Application.
- Select
androidas the application type and enter an application name to generate a unique Datadog application ID and client token. - To instrument your web views, click the Instrument your webviews toggle. For more information, see Web View Tracking.
- To disable automatic user data collection for either client IP or geolocation data, use the toggles for those settings. For more information, see RUM Android Data Collected.
For more information about setting up a client token, see the Client Token documentation.
Step 3 - Initialize the Datadog SDK with application context
Update the initialization snippet
In the initialization snippet, set an environment name, service name, and version number. In the examples below, APP_VARIANT_NAME specifies the variant of the application that generates data. For more information, see Using Tags.
During initialization, you can also set the sample rate (RUM sessions) and set the tracking consent for GDPR compliance, as described below. See other configuration options to initialize the library.
class SampleApplication : Application() {
override fun onCreate() {
super.onCreate()
val configuration = Configuration.Builder(
clientToken = "<CLIENT_TOKEN>",
env = "<ENV_NAME>",
variant = "<APP_VARIANT_NAME>"
).build()
Datadog.initialize(this, configuration, trackingConsent)
}
}
public class SampleApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Configuration configuration =
new Configuration.Builder("<CLIENT_TOKEN>", "<ENV_NAME>", "<APP_VARIANT_NAME>")
.build();
Datadog.initialize(this, configuration, trackingConsent);
}
}
class SampleApplication : Application() {
override fun onCreate() {
super.onCreate()
val configuration = Configuration.Builder(
clientToken = "<CLIENT_TOKEN>",
env = "<ENV_NAME>",
variant = "<APP_VARIANT_NAME>"
)
.useSite(DatadogSite.EU1)
.build()
Datadog.initialize(this, configuration, trackingConsent)
}
}
public class SampleApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Configuration configuration =
new Configuration.Builder("<CLIENT_TOKEN>", "<ENV_NAME>", "<APP_VARIANT_NAME>")
.useSite(DatadogSite.EU1)
.build();
Datadog.initialize(this, configuration, trackingConsent);
}
}
class SampleApplication : Application() {
override fun onCreate() {
super.onCreate()
val configuration = Configuration.Builder(
clientToken = "<CLIENT_TOKEN>",
env = "<ENV_NAME>",
variant = "<APP_VARIANT_NAME>"
)
.useSite(DatadogSite.US3)
.build()
Datadog.initialize(this, configuration, trackingConsent)
}
}
public class SampleApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Configuration configuration =
new Configuration.Builder("<CLIENT_TOKEN>", "<ENV_NAME>", "<APP_VARIANT_NAME>")
.useSite(DatadogSite.US3)
.build();
Datadog.initialize(this, configuration, trackingConsent);
}
}
class SampleApplication : Application() {
override fun onCreate() {
super.onCreate()
val configuration = Configuration.Builder(
clientToken = "<CLIENT_TOKEN>",
env = "<ENV_NAME>",
variant = "<APP_VARIANT_NAME>"
)
.useSite(DatadogSite.US5)
.build()
Datadog.initialize(this, configuration, trackingConsent)
}
}
public class SampleApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Configuration configuration =
new Configuration.Builder("<CLIENT_TOKEN>", "<ENV_NAME>", "<APP_VARIANT_NAME>")
.useSite(DatadogSite.US5)
.build();
Datadog.initialize(this, configuration, trackingConsent);
}
}
class SampleApplication : Application() {
override fun onCreate() {
super.onCreate()
val configuration = Configuration.Builder(
clientToken = "<CLIENT_TOKEN>",
env = "<ENV_NAME>",
variant = "<APP_VARIANT_NAME>"
)
.useSite(DatadogSite.US1_FED)
.build()
Datadog.initialize(this, configuration, trackingConsent)
}
}
public class SampleApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Configuration configuration =
new Configuration.Builder("<CLIENT_TOKEN>", "<ENV_NAME>", "<APP_VARIANT_NAME>")
.useSite(DatadogSite.US1_FED)
.build();
Datadog.initialize(this, configuration, trackingConsent);
}
}
class SampleApplication : Application() {
override fun onCreate() {
super.onCreate()
val configuration = Configuration.Builder(
clientToken = "<CLIENT_TOKEN>",
env = "<ENV_NAME>",
variant = "<APP_VARIANT_NAME>"
)
.useSite(DatadogSite.AP1)
.build()
Datadog.initialize(this, configuration, trackingConsent)
}
}
public class SampleApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Configuration configuration =
new Configuration.Builder("<CLIENT_TOKEN>", "<ENV_NAME>", "<APP_VARIANT_NAME>")
.useSite(DatadogSite.AP1)
.build();
Datadog.initialize(this, configuration, trackingConsent);
}
}
class SampleApplication : Application() {
override fun onCreate() {
super.onCreate()
val configuration = Configuration.Builder(
clientToken = "<CLIENT_TOKEN>",
env = "<ENV_NAME>",
variant = "<APP_VARIANT_NAME>"
)
.useSite(DatadogSite.AP2)
.build()
Datadog.initialize(this, configuration, trackingConsent)
}
}
public class SampleApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Configuration configuration =
new Configuration.Builder("<CLIENT_TOKEN>", "<ENV_NAME>", "<APP_VARIANT_NAME>")
.useSite(DatadogSite.AP2)
.build();
Datadog.initialize(this, configuration, trackingConsent);
}
}
The initialization credentials require your application's variant name and use the value of BuildConfig.FLAVOR. With the variant, the SDK can match the errors reported from your application to the mapping files uploaded by the Gradle plugin. If you do not have variants, the credentials use an empty string.
The Gradle plugin automatically uploads the appropriate ProGuard mapping.txt file at build time so you can view deobfuscated error stack traces. For more information, see the Track Android Errors.
Sample session rates
To control the data your application sends to Datadog, you can specify a sample rate for sessions when initializing RUM. The sample rate is a percentage between 0 and 100. By default, sessionSamplingRate is set to 100 (keep all sessions).
val rumConfig = RumConfiguration.Builder(applicationId)
// Here 75% of the RUM sessions are sent to Datadog
.setSessionSampleRate(75.0f)
.build()
Rum.enable(rumConfig)
Set tracking consent (GDPR compliance)
To be compliant with the GDPR regulation, the SDK requires the tracking consent value upon initialization.
Tracking consent can be one of the following values:
TrackingConsent.PENDING: (Default) The SDK starts collecting and batching the data but does not send it to the collection endpoint. The SDK waits for the new tracking consent value to decide what to do with the batched data.TrackingConsent.GRANTED: The SDK starts collecting the data and sends it to the data collection endpoint.TrackingConsent.NOT_GRANTED: The SDK does not collect any data. You are not able to manually send any logs, traces, or events.
To update the tracking consent after the SDK is initialized, call Datadog.setTrackingConsent(<NEW CONSENT>). The SDK changes its behavior according to the new consent. For example, if the current tracking consent is TrackingConsent.PENDING and you update it to:
TrackingConsent.GRANTED: The SDK sends all current batched data and future data directly to the data collection endpoint.TrackingConsent.NOT_GRANTED: The SDK wipes all batched data and does not collect any future data.
Step 4 - Enable the feature to start sending data
To enable the Android SDK to start sending data:
val rumConfig = RumConfiguration.Builder(applicationId)
.trackInteractions()
.trackLongTasks(durationThreshold) // Not applicable to Error Tracking
.useViewTrackingStrategy(strategy)
.build()
Rum.enable(rumConfig)
RumConfiguration rumConfig = new RumConfiguration.Builder(applicationId)
.trackInteractions()
.trackLongTasks(durationThreshold) // Not applicable to Error Tracking
.useViewTrackingStrategy(strategy)
.build();
Rum.enable(rumConfig);
See ViewTrackingStrategy to enable automatic tracking of all your views (activities, fragments, and more).
Step 5 - Initialize the interceptor to track network events
To initialize an interceptor for tracking network events:
- For distributed tracing, add and enable the Trace feature.
- Add the Gradle dependency to the
dd-sdk-android-okhttplibrary in the module-levelbuild.gradlefile:
dependencies {
implementation "com.datadoghq:dd-sdk-android-okhttp:x.x.x"
}
- To track your OkHttp requests as resources, add the provided interceptor:
val tracedHostsWithHeaderType = mapOf(
"example.com" to setOf(
TracingHeaderType.DATADOG,
TracingHeaderType.TRACECONTEXT),
"example.eu" to setOf(
TracingHeaderType.DATADOG,
TracingHeaderType.TRACECONTEXT))
val okHttpClient = OkHttpClient.Builder()
.addInterceptor(DatadogInterceptor.Builder(tracedHostsWithHeaderType).build())
.build()
Map<String, Set<TracingHeaderType>> tracedHostsWithHeaderType = new HashMap<>();
Set<TracingHeaderType> datadogAndW3HeadersTypes = new HashSet<>(Arrays.asList(TracingHeaderType.DATADOG, TracingHeaderType.TRACECONTEXT));
tracedHostsWithHeaderType.put("example.com", datadogAndW3HeadersTypes);
tracedHostsWithHeaderType.put("example.eu", datadogAndW3HeadersTypes);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(new DatadogInterceptor.Builder(tracedHostsWithHeaderType).build())
.build();
To automatically create RUM resources and spans for your OkHttp requests, use the
DatadogInterceptoras an interceptor.- This records each request processed by the
OkHttpClientas a resource, with all the relevant information (URL, method, status code, and error) automatically filled in. Only the network requests that started when a view is active are tracked. To track requests when your application is in the background, create a view manually.
- This records each request processed by the
To monitor the network redirects or retries, you can use the
DatadogInterceptoras a network interceptor:
val okHttpClient = OkHttpClient.Builder()
.addNetworkInterceptor(DatadogInterceptor.Builder(tracedHostsWithHeaderType).build())
.build()
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addNetworkInterceptor(new DatadogInterceptor.Builder(tracedHostsWithHeaderType).build())
.build();
Notes:
- To use spans but not RUM resources, you can use the
TracingInterceptorinstead ofDatadogInterceptoras described above. - If you use multiple interceptors, add
DatadogInterceptorfirst.
You can also add an EventListener for the OkHttpClient to automatically track resource timing for third-party providers and network requests.
Cronet
If you use Cronet instead of OkHttp, you can instrument your CronetEngine for RUM resource tracking and distributed tracing.
Add the Gradle dependencies in the module-level
build.gradlefile:dependencies { implementation "com.datadoghq:dd-sdk-android-cronet:x.x.x" }Instrument the
CronetEngine.Builder:val tracedHostsWithHeaderType = mapOf( "example.com" to setOf( TracingHeaderType.DATADOG, TracingHeaderType.TRACECONTEXT), "example.eu" to setOf( TracingHeaderType.DATADOG, TracingHeaderType.TRACECONTEXT)) val cronetEngine = CronetEngine.Builder(context) .configureDatadogInstrumentation( rumInstrumentationConfiguration = RumNetworkInstrumentationConfiguration(), apmInstrumentationConfiguration = ApmNetworkInstrumentationConfiguration( tracedHostsWithHeaderType ) ) .build()Map<String, Set<TracingHeaderType>> tracedHostsWithHeaderType = new HashMap<>(); Set<TracingHeaderType> headerTypes = new HashSet<>(Arrays.asList( TracingHeaderType.DATADOG, TracingHeaderType.TRACECONTEXT)); tracedHostsWithHeaderType.put("example.com", headerTypes); tracedHostsWithHeaderType.put("example.eu", headerTypes); CronetEngine.Builder builder = new CronetEngine.Builder(context); CronetEngine cronetEngine = CronetIntegrationPluginKt .configureDatadogInstrumentation( builder, new RumNetworkInstrumentationConfiguration(), new ApmNetworkInstrumentationConfiguration(tracedHostsWithHeaderType) ) .build();
Known limitations:
- Tracing headers are not propagated for redirected requests due to Cronet API limitations.
- Retries cannot be instrumented.
To filter out specific errors reported by DatadogInterceptor, you can configure a custom EventMapper in your RumConfiguration:
val rumConfig = RumConfiguration.Builder(applicationId)
.setErrorEventMapper { errorEvent ->
if (errorEvent.shouldBeDiscarded()) {
null
} else {
errorEvent
}
}
.build();
RumConfiguration rumConfig = new RumConfiguration.Builder("applicationId")
.setErrorEventMapper(errorEvent -> {
if (errorEvent.shouldBeDiscarded()) {
return null;
} else {
return errorEvent;
}
})
.build();
Track background events
You can track events such as crashes and network requests when your application is in the background (for example, no active view is available).
Add the following snippet during configuration:
val rumConfig = RumConfiguration.Builder(applicationId)
// …
.trackBackgroundEvents(true)
RumConfiguration rumConfig = new RumConfiguration.Builder(applicationId)
// …
.trackBackgroundEvents(true)
Tracking background events may lead to additional sessions, which can impact billing. For questions, contact Datadog support.
Sending data when device is offline
The Android SDK helps ensure availability of data when your user device is offline. In case of low-network areas, or when the device battery is too low, all events are first stored on the local device in batches.
Each batch follows the intake specification. Batches are sent as soon as the network is available, and the battery is high enough to ensure the Datadog SDK does not impact the end user's experience. If the network is not available while your application is in the foreground, or if an upload of data fails, the batch is kept until it can be sent successfully.
This means that even if users open your application while offline, no data is lost. To ensure the SDK does not use too much disk space, the data on the disk is automatically discarded if it gets too old.
Kotlin extensions
Closeable extension
You can monitor Closeable instance usage with the useMonitored method, which reports errors to Datadog and closes the resource afterwards.
val closeable: Closeable = ...
closeable.useMonitored {
// Your code here
}
Track local assets as resources
You can track access to the assets by using getAssetAsRumResource extension method:
val inputStream = context.getAssetAsRumResource(fileName)
Usage of the local resources can be tracked by using getRawResAsRumResource extension method:
val inputStream = context.getRawResAsRumResource(id)
Start monitoring
Visualize the data collected in dashboards or create a search query in the RUM Explorer.
Your application appears as pending on the Applications page until Datadog starts receiving data.
Next steps
This page describes how to instrument your iOS and tvOS applications for Real User Monitoring (RUM) with the iOS SDK. RUM includes Error Tracking by default, but if you have purchased Error Tracking as a standalone product, see the Error Tracking setup guide for specific steps.
Prerequisites
Before you begin, ensure you have:
- Xcode 12.0 or later
- iOS 11.0+ or tvOS 11.0+ deployment target
- A Datadog account with RUM or Error Tracking enabled
Setup
Choose your setup method:
- Agentic Onboarding (in Preview): Use AI coding agents (Cursor, Claude Code) to automatically instrument your iOS application with one prompt. The agent detects your project structure and configures the RUM SDK for you.
- Manual setup (below): Follow the instructions to manually add and configure the RUM SDK in your iOS application.
Manual setup
To send RUM data from your iOS or tvOS application to Datadog, complete the following steps.
Step 1 - Add the iOS SDK as a dependency
Add the iOS SDK to your project using your preferred package manager. Datadog recommends using Swift Package Manager (SPM).
To integrate using Apple's Swift Package Manager, add the following as a dependency to your Package.swift:
.package(url: "https://github.com/Datadog/dd-sdk-ios.git", .upToNextMajor(from: "3.0.0"))
In your project, link the following libraries:
DatadogCore
DatadogRUM
You can use CocoaPods to install dd-sdk-ios:
pod 'DatadogCore'
pod 'DatadogRUM'
You can use Carthage to install dd-sdk-ios:
github "DataDog/dd-sdk-ios"
Datadog does not provide prebuilt Carthage binaries. This means Carthage builds the SDK from source.
To build and integrate the SDK, run:
carthage bootstrap --use-xcframeworks --no-use-binaries
After building, add the following XCFrameworks to your Xcode project (in the "Frameworks, Libraries, and Embedded Content" section):
DatadogInternal.xcframework
DatadogCore.xcframework
DatadogRUM.xcframework
Step 2 - Specify application details in the UI
- Navigate to Digital Experience > Add an Application.
- Select
iOSas the application type and enter an application name to generate a unique Datadog application ID and client token. - To instrument your web views, click the Instrument your webviews toggle. For more information, see Web View Tracking.
Step 3 - Initialize the library
In the initialization snippet, set an environment name, service name, and client token.
The SDK should be initialized as early as possible in the app lifecycle, specifically in the AppDelegate's application(_:didFinishLaunchingWithOptions:) callback. The AppDelegate is your app's main entry point that handles app lifecycle events.
This ensures the SDK can correctly capture all measurements, including application startup duration. For apps built with SwiftUI, you can use @UIApplicationDelegateAdaptor to hook into the AppDelegate.
Initializing the SDK elsewhere (for example later during view loading) may result in inaccurate or missing telemetry, especially around app startup performance.
For more information, see Using Tags.
import DatadogCore
// Initialize Datadog SDK with your configuration
Datadog.initialize(
with: Datadog.Configuration(
clientToken: "<client token>", // From Datadog UI
env: "<environment>", // for example, "production", "staging"
service: "<service name>" // Your app's service name
),
trackingConsent: trackingConsent // GDPR compliance setting
)
@import DatadogCore;
// Initialize Datadog SDK with your configuration
DDConfiguration *configuration = [[DDConfiguration alloc] initWithClientToken:@"<client token>" env:@"<environment>"];
configuration.service = @"<service name>"; // Your app's service name
[DDDatadog initializeWithConfiguration:configuration
trackingConsent:trackingConsent]; // GDPR compliance setting
import DatadogCore
Datadog.initialize(
with: Datadog.Configuration(
clientToken: "<client token>",
env: "<environment>",
site: .eu1,
service: "<service name>"
),
trackingConsent: trackingConsent
)
@import DatadogCore;
DDConfiguration *configuration = [[DDConfiguration alloc] initWithClientToken:@"<client token>" env:@"<environment>"];
configuration.service = @"<service name>";
configuration.site = [DDSite eu1];
[DDDatadog initializeWithConfiguration:configuration
trackingConsent:trackingConsent];
import DatadogCore
Datadog.initialize(
with: Datadog.Configuration(
clientToken: "<client token>",
env: "<environment>",
site: .us3,
service: "<service name>"
),
trackingConsent: trackingConsent
)
@import DatadogCore;
DDConfiguration *configuration = [[DDConfiguration alloc] initWithClientToken:@"<client token>" env:@"<environment>"];
configuration.service = @"<service name>";
configuration.site = [DDSite us3];
[DDDatadog initializeWithConfiguration:configuration
trackingConsent:trackingConsent];
import DatadogCore
Datadog.initialize(
with: Datadog.Configuration(
clientToken: "<client token>",
env: "<environment>",
site: .us5,
service: "<service name>"
),
trackingConsent: trackingConsent
)
@import DatadogCore;
DDConfiguration *configuration = [[DDConfiguration alloc] initWithClientToken:@"<client token>" env:@"<environment>"];
configuration.service = @"<service name>";
configuration.site = [DDSite us5];
[DDDatadog initializeWithConfiguration:configuration
trackingConsent:trackingConsent];
import DatadogCore
Datadog.initialize(
with: Datadog.Configuration(
clientToken: "<client token>",
env: "<environment>",
site: .us1_fed,
service: "<service name>"
),
trackingConsent: trackingConsent
)
@import DatadogCore;
DDConfiguration *configuration = [[DDConfiguration alloc] initWithClientToken:@"<client token>" env:@"<environment>"];
configuration.service = @"<service name>";
configuration.site = [DDSite us1_fed];
[DDDatadog initializeWithConfiguration:configuration
trackingConsent:trackingConsent];
import DatadogCore
Datadog.initialize(
with: Datadog.Configuration(
clientToken: "<client token>",
env: "<environment>",
site: .ap1,
service: "<service name>"
),
trackingConsent: trackingConsent
)
@import DatadogCore;
DDConfiguration *configuration = [[DDConfiguration alloc] initWithClientToken:@"<client token>" env:@"<environment>"];
configuration.service = @"<service name>";
configuration.site = [DDSite ap1];
[DDDatadog initializeWithConfiguration:configuration
trackingConsent:trackingConsent];
import DatadogCore
Datadog.initialize(
with: Datadog.Configuration(
clientToken: "<client token>",
env: "<environment>",
site: .ap2,
service: "<service name>"
),
trackingConsent: trackingConsent
)
@import DatadogCore;
DDConfiguration *configuration = [[DDConfiguration alloc] initWithClientToken:@"<client token>" env:@"<environment>"];
configuration.service = @"<service name>";
configuration.site = [DDSite ap2];
[DDDatadog initializeWithConfiguration:configuration
trackingConsent:trackingConsent];
The iOS SDK automatically tracks user sessions based on the options you provide during SDK initialization. To add GDPR compliance for your EU users (required for apps targeting European users) and configure other initialization parameters, see the Set tracking consent documentation.
Sample session rates
To control the data your application sends to Datadog RUM, you can specify a sampling rate for RUM sessions while initializing the RUM iOS SDK. The rate is a percentage between 0 and 100. By default, sessionSamplingRate is set to 100 (keep all sessions).
For example, to only keep 50% of sessions use:
// Configure RUM with 50% session sampling
let configuration = RUM.Configuration(
applicationID: "<rum application id>",
sessionSampleRate: 50 // Only track 50% of user sessions
)
// Configure RUM with 50% session sampling
DDRUMConfiguration *configuration = [[DDRUMConfiguration alloc] initWithApplicationID:@"<rum application id>"];
configuration.sessionSampleRate = 50; // Only track 50% of user sessions
Set tracking consent (GDPR compliance)
To be compliant with the GDPR regulation (required for apps targeting European users), the iOS SDK requires the tracking consent value at initialization.
The trackingConsent setting can be one of the following values:
.pending: The iOS SDK starts collecting and batching the data but does not send it to Datadog. The iOS SDK waits for the new tracking consent value to decide what to do with the batched data..granted: The iOS SDK starts collecting the data and sends it to Datadog..notGranted: The iOS SDK does not collect any data. No logs, traces, or events are sent to Datadog.
To change the tracking consent value after the iOS SDK is initialized, use the Datadog.set(trackingConsent:) API call. The iOS SDK changes its behavior according to the new value.
For example, if the current tracking consent is .pending:
- If you change the value to
.granted, the RUM iOS SDK sends all current and future data to Datadog; - If you change the value to
.notGranted, the RUM iOS SDK wipes all current data and does not collect future data.
Step 4 - Start sending data
Enable RUM
Configure and start RUM. This should be done once and as early as possible, specifically in your AppDelegate:
import DatadogRUM
RUM.enable(
with: RUM.Configuration(
applicationID: "<rum application id>",
uiKitViewsPredicate: DefaultUIKitRUMViewsPredicate(),
uiKitActionsPredicate: DefaultUIKitRUMActionsPredicate(),
swiftUIViewsPredicate: DefaultSwiftUIRUMViewsPredicate(),
swiftUIActionsPredicate: DefaultSwiftUIRUMActionsPredicate(isLegacyDetectionEnabled: true),
urlSessionTracking: RUM.Configuration.URLSessionTracking()
)
)
@import DatadogRUM;
DDRUMConfiguration *configuration = [[DDRUMConfiguration alloc] initWithApplicationID:@"<rum application id>"];
configuration.uiKitViewsPredicate = [DDDefaultUIKitRUMViewsPredicate new];
configuration.uiKitActionsPredicate = [DDDefaultUIKitRUMActionsPredicate new];
configuration.swiftUIViewsPredicate = [DDDefaultSwiftUIRUMViewsPredicate new];
configuration.swiftUIActionsPredicate = [[DDDefaultSwiftUIRUMActionsPredicate alloc] initWithIsLegacyDetectionEnabled:YES];
[configuration setURLSessionTracking:[DDRUMURLSessionTracking new]];
[DDRUM enableWith:configuration];
Enable URLSessionInstrumentation
To monitor requests sent from the URLSession instance as resources, enable URLSessionInstrumentation for your delegate type and pass the delegate instance to the URLSession:
URLSessionInstrumentation.enable(
with: .init(
delegateClass: <YourSessionDelegate>.self
)
)
let session = URLSession(
configuration: .default,
delegate: <YourSessionDelegate>(),
delegateQueue: nil
)
DDURLSessionInstrumentationConfiguration *config = [[DDURLSessionInstrumentationConfiguration alloc] initWithDelegateClass:[<YourSessionDelegate> class]];
[DDURLSessionInstrumentation enableWithConfiguration:config];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]
delegate:[[<YourSessionDelegate> alloc] init]
delegateQueue:nil];
Instrument views
The Datadog iOS SDK allows you to instrument views of SwiftUI applications. The instrumentation also works with hybrid UIKit and SwiftUI applications.
To instrument a SwiftUI.View, add the following method to your view declaration:
import SwiftUI
import DatadogRUM
struct FooView: View {
var body: some View {
FooContent {
...
}
.trackRUMView(name: "Foo")
}
}
The trackRUMView(name:) method starts and stops a view when the SwiftUI view appears and disappears from the screen.
Instrument tap actions
The Datadog iOS SDK allows you to instrument tap actions of SwiftUI applications. The instrumentation also works with hybrid UIKit and SwiftUI applications.
Using .trackRUMTapAction(name:) for SwiftUI controls inside a List can break its default gestures. For example, it may disable the Button action or break NavigationLink. To track taps in a List element, use the Custom Actions API instead.
To instrument a tap action on a SwiftUI.View, add the following method to your view declaration:
import SwiftUI
import DatadogRUM
struct BarView: View {
var body: some View {
Button("BarButton") {
// Your button action here
}
.trackRUMTapAction(name: "Bar")
}
}
Track iOS errors
iOS Crash Reporting and Error Tracking displays any issues in your application and the latest available errors. You can view error details and attributes including JSON in the RUM Explorer.
Disable automatic user data collection
You may want to disable automatic collection of user data to comply with privacy regulations or organizational data governance policies.
To disable automatic user data collection for client IP or geolocation data:
- After creating your application, go to the Application Management page and click your application.
- Click User Data Collection.
- Use the toggles for those settings. For more information, see RUM iOS Data Collected.
To ensure the safety of your data, you must use a client token. Using only Datadog API keys to configure the dd-sdk-ios library would expose them client-side in your iOS application's byte code.
For more information about setting up a client token, see the Client token documentation.
Sending data when device is offline
The iOS SDK ensures availability of data when your user device is offline. In cases of low-network areas, or when the device battery is too low, all events are first stored on the local device in batches. They are sent as soon as the network is available, and the battery is high enough to ensure the iOS SDK does not impact the end user's experience. If the network is not available while your application is in the foreground, or if an upload of data fails, the batch is kept until it can be sent successfully.
This means that even if users open your application while offline, no data is lost.
Note: The data on the disk is automatically discarded if it gets too old to ensure the iOS SDK does not use too much disk space.
Supported versions
See Supported versions for a list of operating system versions and platforms that are compatible with the iOS SDK.
This page describes how to instrument your applications for Real User Monitoring (RUM) with the Flutter SDK. RUM includes Error Tracking by default, but if you have purchased Error Tracking as a standalone product, see the Error Tracking setup guide for specific steps.
Setup
Step 1 - Specify application details in the UI
- In Datadog, navigate to Digital Experience > Add an Application.
- Choose
Flutteras the application type. - Provide an application name to generate a unique Datadog application ID and client token.
To secure your data, you must use a client token. For more information about setting up a client token, see the Client Token documentation.
Step 2 - Instrument your application
First, make sure you have your environment set up properly for each platform.
Datadog supports Flutter Monitoring for iOS, Android, and Web for Flutter 3.27+.
Datadog supports Flutter Web starting with v3 of the SDK, with a few known limitations.
- Long running actions (
startActionandstopAction) are not supported - Actions (
addAction) and manually reported Resources (startResourceandstopResource) do not properly associate with Errors or Actions. - Event mappers are not supported.
iOS
The Datadog SDK for Flutter supports integration with both Cocoapods and Swift Package Manager (SPM).
If you are using Cocoapods, your iOS Podfile, located in ios/Podfile, must have use_frameworks! set to true (which is the default in Flutter) and must set its target iOS version >= 12.0.
This constraint is usually commented out on the top line of the Podfile, and should read:
platform :ios, '12.0'
You can replace 12.0 with any minimum version of iOS you want to support that is 12.0 or higher.
Android
For Android, your minSdkVersion version must be >= 23, and your compileSdkVersion must be >= 35. Clients using Flutter after 3.27 usually have these variables set to Flutter constants (flutter.minSdkVersion and flutter.compileSdkVersion), and they do not have to be manually changed.
If you are using Kotlin, it should be a version >= 2.1.0. Flutter versions above 3.27 emit a warning stating that older versions of Kotlin are not supported, and provide instructions for updating.
These constraints are usually held in your android/app/build.gradle file, or in your android/gradle.properties file.
Web
For Web, add the following to your index.html under the head tag:
<script type="text/javascript" src="https://www.datadoghq-browser-agent.com/"></script>
<script type="text/javascript" src="https://www.datadoghq-browser-agent.com/"></script>
This loads the CDN-delivered Datadog Browser SDKs for Logs and RUM. The synchronous CDN-delivered version of the Browser SDK is the only version supported by the Datadog Flutter Plugin.
Add the plugin
- Add the following to your
pubspec.yamlfile:
dependencies:
datadog_flutter_plugin: ^3.0.0
- Create a configuration object for each Datadog feature (such as Logs or RUM) with the following snippet. If you do not pass a configuration for a given feature, that feature is disabled.
// Determine the user's consent to be tracked
final trackingConsent = ...
final configuration = DatadogConfiguration(
clientToken: '<CLIENT_TOKEN>',
env: '<ENV_NAME>',
site: DatadogSite.us1,
nativeCrashReportEnabled: true,
loggingConfiguration: DatadogLoggingConfiguration(),
rumConfiguration: DatadogRumConfiguration(
applicationId: '<RUM_APPLICATION_ID>',
)
);
For more information on available configuration options, see the DatadogConfiguration object documentation.
To secure data, you must use a client token. You cannot use Datadog API keys to configure the Datadog Flutter Plugin.
- If you are using RUM, set up a Client Token and Application ID.
- If you are only using Logs, initialize the library with a client token.
Step 3 - Initialize the library
You can initialize the library using one of two methods in your main.dart file.
- Use
DatadogSdk.runAppto automatically set up Error Tracking.
await DatadogSdk.runApp(configuration, TrackingConsent.granted, () async {
runApp(const MyApp());
})
- You can also manually set up Error Tracking.
DatadogSdk.runAppcallsWidgetsFlutterBinding.ensureInitialized, so if you are not usingDatadogSdk.runApp, you need to call this method prior to callingDatadogSdk.instance.initialize.
WidgetsFlutterBinding.ensureInitialized();
final originalOnError = FlutterError.onError;
FlutterError.onError = (details) {
DatadogSdk.instance.rum?.handleFlutterError(details);
originalOnError?.call(details);
};
final platformOriginalOnError = PlatformDispatcher.instance.onError;
PlatformDispatcher.instance.onError = (e, st) {
DatadogSdk.instance.rum?.addErrorInfo(
e.toString(),
RumErrorSource.source,
stackTrace: st,
);
return platformOriginalOnError?.call(e, st) ?? false;
};
await DatadogSdk.instance.initialize(configuration, TrackingConsent.granted);
runApp(const MyApp());
Sample session rates
To control the data your application sends to Datadog RUM, you can specify a sampling rate for RUM sessions while initializing the Flutter RUM SDK. The rate is a percentage between 0 and 100. By default, sessionSamplingRate is set to 100 (keep all sessions).
For example, to keep only 50% of sessions, use:
final config = DatadogConfiguration(
// other configuration...
rumConfiguration: DatadogRumConfiguration(
applicationId: '<YOUR_APPLICATION_ID>',
sessionSamplingRate: 50.0,
),
);
Set tracking consent (GDPR compliance)
To be compliant with the GDPR regulation, the Datadog Flutter SDK requires the trackingConsent value during initialization.
Set trackingConsent to one of the following values:
TrackingConsent.pending: The Datadog Flutter SDK starts collecting and batching the data but does not send it to Datadog. It waits for the new tracking consent value to decide what to do with the batched data.TrackingConsent.granted: The Datadog Flutter SDK starts collecting the data and sends it to Datadog.TrackingConsent.notGranted: The Datadog Flutter SDK does not collect any data, which means no logs, traces, or events are sent to Datadog.
To change the tracking consent value after the SDK is initialized, use the DatadogSdk.setTrackingConsent API call.
The SDK changes its behavior according to the new value. For example, if the current tracking consent is TrackingConsent.pending:
- You change it to
TrackingConsent.granted, the SDK sends all current and future data to Datadog; - You change it to
TrackingConsent.notGranted, the SDK wipes all current data and does not collect any future data.
Manage user data collection
To manage user data collection settings for client IP or geolocation data:
- Go to Manage Applications.
- Select your application.
- Click User Data Collection, then toggle the settings to enable/disable Collect geolocation data and Collect client IP data.
For more information about the data collected, see Flutter Data Collected.
Automatically track views
If you are using Flutter Navigator v2.0, your setup for automatic view tracking differs depending on your routing middleware. See Flutter Integrated Libraries for instructions on how to integrate with go_router, AutoRoute, and Beamer.
Flutter Navigator v1
The Datadog Flutter Plugin can automatically track named routes using the DatadogNavigationObserver on your MaterialApp:
MaterialApp(
home: HomeScreen(),
navigatorObservers: [
DatadogNavigationObserver(DatadogSdk.instance),
],
);
This works if you are using named routes or if you have supplied a name to the settings parameter of your PageRoute.
If you are not using named routes, you can use DatadogRouteAwareMixin in conjunction with the DatadogNavigationObserverProvider widget to start and stop your RUM views automatically. With DatadogRouteAwareMixin, move any logic from initState to didPush.
Flutter Navigator v2
If you are using Flutter Navigator v2.0, which uses the MaterialApp.router named constructor, the setup varies based on the routing middleware you are using, if any. Since go_router uses the same observer interface as Flutter Navigator v1, DatadogNavigationObserver can be added to other observers as a parameter to GoRouter.
final _router = GoRouter(
routes: [
// Your route information here
],
observers: [
DatadogNavigationObserver(datadogSdk: DatadogSdk.instance),
],
);
MaterialApp.router(
routerConfig: _router,
// Your remaining setup
)
For examples that use routers other than go_router, see Automatically track views.
Renaming views
For all setups, you can rename views or supply custom paths by providing a viewInfoExtractor callback. This function can fall back to the default behavior of the observer by calling defaultViewInfoExtractor. For example:
RumViewInfo? infoExtractor(Route<dynamic> route) {
var name = route.settings.name;
if (name == 'my_named_route') {
return RumViewInfo(
name: 'MyDifferentName',
attributes: {'extra_attribute': 'attribute_value'},
);
}
return defaultViewInfoExtractor(route);
}
var observer = DatadogNavigationObserver(
datadogSdk: DatadogSdk.instance,
viewInfoExtractor: infoExtractor,
);
Automatically track actions
Use RumUserActionDetector to track user taps that happen in a given Widget tree:
RumUserActionDetector(
rum: DatadogSdk.instance.rum,
child: Scaffold(
appBar: AppBar(
title: const Text('RUM'),
),
body: // Rest of your application
),
);
RumUserActionDetector automatically detects tap user actions that occur in its tree and sends them to RUM. It detects interactions with several common Flutter widgets.
For most Button types, the detector looks for a Text widget child, which it uses for the description of the action. In other cases it looks for a Semantics object child, or an Icon with its Icon.semanticsLabel property set.
Alternatively, you can enclose any Widget tree with a RumUserActionAnnotation, which uses the provided description when reporting user actions detected in the child tree, without changing the Semantics of the tree.
Container(
margin: const EdgeInsets.all(8),
child: RumUserActionAnnotation(
description: 'My Image Button',
child: InkWell(
onTap: onTap,
child: Column(
children: [
FadeInImage.memoryNetwork(
placeholder: kTransparentImage,
image: image,
),
Center(
child: Text(
text,
style: theme.textTheme.headlineSmall,
),
)
],
),
),
),
);
Sending data when device is offline
The Flutter SDK ensures availability of data when your user device is offline. In cases of low-network areas, or when the device battery is too low, all events are first stored on the local device in batches. They are sent as soon as the network is available, and the battery is high enough to ensure the Flutter SDK does not impact the end user's experience. If the network is not available with your application running in the foreground, or if an upload of data fails, the batch is kept until it can be sent successfully.
This means that even if users open your application while offline, no data is lost.
Note: The data on the disk is automatically deleted if it gets too old to ensure the Flutter SDK does not use too much disk space.
The minimum supported version for the React Native SDK is React Native v0.65+. Compatibility with older versions is not guaranteed out-of-the-box.
Step 1 - Install the SDK
To install with npm, run:
npm install @datadog/mobile-react-native
To install with Yarn, run:
yarn add @datadog/mobile-react-native
Install dependencies for iOS
Install the added pod:
(cd ios && pod install)
Android
If you use a React Native version strictly over 0.67, make sure to use Java version 17. If you use React Native version equal or below 0.67, make sure to use Java version 11.
In your android/build.gradle file, specify the kotlinVersion to avoid clashes among kotlin dependencies:
buildscript {
ext {
// targetSdkVersion = ...
kotlinVersion = "1.8.21"
}
}
The minimum supported Android SDK version is API level 23. Make sure to set minSdkVersion to 23 (or higher) in your Android configuration.
The Datadog React Native SDK requires you to have compileSdkVersion = 31 or higher in the Android application setup, which implies that you should use Build Tools version 31 or higher, Android Gradle Plugin version 7, and Gradle version 7 or higher. To modify the versions, change the values in the buildscript.ext block of your application's top-level build.gradle file. Datadog recommends using a React Native version that's actively supported.
Step 2 - Specify application details in the UI
- In Datadog, navigate to Digital Experience > Add an Application.
- Choose
react-nativeas the application type. - Provide an application name to generate a unique Datadog application ID and client token.
- To disable automatic user data collection for client IP or geolocation data, uncheck the boxes for those settings.
If you've purchased Error Tracking as a standalone product (without RUM), navigate to Error Tracking > Settings > Browser and Mobile > Add an Application instead.
For data security, you must use a client token. If you used only Datadog API keys to configure the @datadog/mobile-react-native library, they would be exposed client-side in the React Native application's code.
For more information about setting up a client token, see the Client Token documentation.
Step 3 - Initialize the library with application context
import {
SdkVerbosity,
DatadogProvider,
DatadogProviderConfiguration,
PropagatorType
} from '@datadog/mobile-react-native';
// Configure Datadog SDK
const config = new DatadogProviderConfiguration(
'<CLIENT_TOKEN>',
'<ENVIRONMENT_NAME>',
// Optional: Configure the Datadog Site to target. Default is 'US1'.
site: 'US1',
// Optional: Set the reported service name (by default, it uses the package name or bundleIdentifier of your Android or iOS app respectively)
service: 'com.example.reactnative',
// Optional: Let the SDK print internal logs above or equal to the provided level. Default is undefined (meaning no logs)
verbosity: SdkVerbosity.WARN,
// Enable RUM
rumConfiguration: {
// Required: RUM Application ID
applicationId: '<APPLICATION_ID>',
// Track user interactions (set to false if using Error Tracking only)
trackInteractions: true,
// Track XHR resources (set to false if using Error Tracking only)
trackResources: true,
// Track errors
trackErrors: true,
// Optional: Sample sessions, for example: 80% of sessions are sent to Datadog. Default is 100%.
sessionSampleRate: 80,
// Optional: Enable or disable native crash reports.
nativeCrashReportEnabled: true,
// Optional: Sample tracing integrations for network calls between your app and your backend
// (in this example, 80% of calls to your instrumented backend are linked from the RUM view to
// the APM view. Default is 20%).
// You need to specify the hosts of your backends to enable tracing with these backends
resourceTraceSampleRate: 80,
firstPartyHosts: [
{
match: 'example.com',
propagatorTypes: [
PropagatorType.DATADOG,
PropagatorType.TRACECONTEXT
]
}
]
},
// Enable Logs with default configuration
logsConfiguration: {},
// Enable Trace with default configuration
traceConfiguration: {}
);
// Wrap the content of your App component in a DatadogProvider component, passing it your configuration:
export default function App() {
return (
<DatadogProvider configuration={config}>
<Navigation />
</DatadogProvider>
);
}
// Once the Datadog React Native SDK for RUM is initialized, you need to setup view tracking to be able to see data in a dashboard
import {
SdkVerbosity,
DatadogProvider,
DatadogProviderConfiguration,
PropagatorType
} from '@datadog/mobile-react-native';
// Configure Datadog SDK
const config = new DatadogProviderConfiguration(
'<CLIENT_TOKEN>',
'<ENVIRONMENT_NAME>',
// Optional: Configure the Datadog Site to target. Default is 'US1'.
site: 'US3',
// Optional: Set the reported service name (by default, it uses the package name or bundleIdentifier of your Android or iOS app respectively)
service: 'com.example.reactnative',
// Optional: Let the SDK print internal logs above or equal to the provided level. Default is undefined (meaning no logs)
verbosity: SdkVerbosity.WARN,
// Enable RUM
rumConfiguration: {
// Required: RUM Application ID
applicationId: '<APPLICATION_ID>',
// Track user interactions (set to false if using Error Tracking only)
trackInteractions: true,
// Track XHR resources (set to false if using Error Tracking only)
trackResources: true,
// Track errors
trackErrors: true,
// Optional: Sample sessions, for example: 80% of sessions are sent to Datadog. Default is 100%.
sessionSampleRate: 80,
// Optional: Enable or disable native crash reports.
nativeCrashReportEnabled: true,
// Optional: Sample tracing integrations for network calls between your app and your backend
// (in this example, 80% of calls to your instrumented backend are linked from the RUM view to
// the APM view. Default is 20%).
// You need to specify the hosts of your backends to enable tracing with these backends
resourceTraceSampleRate: 80,
firstPartyHosts: [
{
match: 'example.com',
propagatorTypes: [
PropagatorType.DATADOG,
PropagatorType.TRACECONTEXT
]
}
]
},
// Enable Logs with default configuration
logsConfiguration: {},
// Enable Trace with default configuration
traceConfiguration: {}
);
// Wrap the content of your App component in a DatadogProvider component, passing it your configuration:
export default function App() {
return (
<DatadogProvider configuration={config}>
<Navigation />
</DatadogProvider>
);
}
// Once the Datadog React Native SDK for RUM is initialized, you need to setup view tracking to be able to see data in a dashboard
import {
SdkVerbosity,
DatadogProvider,
DatadogProviderConfiguration,
PropagatorType
} from '@datadog/mobile-react-native';
// Configure Datadog SDK
const config = new DatadogProviderConfiguration(
'<CLIENT_TOKEN>',
'<ENVIRONMENT_NAME>',
// Optional: Configure the Datadog Site to target. Default is 'US1'.
site: 'EU1',
// Optional: Set the reported service name (by default, it uses the package name or bundleIdentifier of your Android or iOS app respectively)
service: 'com.example.reactnative',
// Optional: Let the SDK print internal logs above or equal to the provided level. Default is undefined (meaning no logs)
verbosity: SdkVerbosity.WARN,
// Enable RUM
rumConfiguration: {
// Required: RUM Application ID
applicationId: '<APPLICATION_ID>',
// Track user interactions (set to false if using Error Tracking only)
trackInteractions: true,
// Track XHR resources (set to false if using Error Tracking only)
trackResources: true,
// Track errors
trackErrors: true,
// Optional: Sample sessions, for example: 80% of sessions are sent to Datadog. Default is 100%.
sessionSampleRate: 80,
// Optional: Enable or disable native crash reports.
nativeCrashReportEnabled: true,
// Optional: Sample tracing integrations for network calls between your app and your backend
// (in this example, 80% of calls to your instrumented backend are linked from the RUM view to
// the APM view. Default is 20%).
// You need to specify the hosts of your backends to enable tracing with these backends
resourceTraceSampleRate: 80,
firstPartyHosts: [
{
match: 'example.com',
propagatorTypes: [
PropagatorType.DATADOG,
PropagatorType.TRACECONTEXT
]
}
]
},
// Enable Logs with default configuration
logsConfiguration: {},
// Enable Trace with default configuration
traceConfiguration: {}
);
// Wrap the content of your App component in a DatadogProvider component, passing it your configuration:
export default function App() {
return (
<DatadogProvider configuration={config}>
<Navigation />
</DatadogProvider>
);
}
// Once the Datadog React Native SDK for RUM is initialized, you need to setup view tracking to be able to see data in a dashboard
import {
SdkVerbosity,
DatadogProvider,
DatadogProviderConfiguration,
PropagatorType
} from '@datadog/mobile-react-native';
// Configure Datadog SDK
const config = new DatadogProviderConfiguration(
'<CLIENT_TOKEN>',
'<ENVIRONMENT_NAME>',
// Optional: Configure the Datadog Site to target. Default is 'US1'.
site: 'US1_FED',
// Optional: Set the reported service name (by default, it uses the package name or bundleIdentifier of your Android or iOS app respectively)
service: 'com.example.reactnative',
// Optional: Let the SDK print internal logs above or equal to the provided level. Default is undefined (meaning no logs)
verbosity: SdkVerbosity.WARN,
// Enable RUM
rumConfiguration: {
// Required: RUM Application ID
applicationId: '<APPLICATION_ID>',
// Track user interactions (set to false if using Error Tracking only)
trackInteractions: true,
// Track XHR resources (set to false if using Error Tracking only)
trackResources: true,
// Track errors
trackErrors: true,
// Optional: Sample sessions, for example: 80% of sessions are sent to Datadog. Default is 100%.
sessionSampleRate: 80,
// Optional: Enable or disable native crash reports.
nativeCrashReportEnabled: true,
// Optional: Sample tracing integrations for network calls between your app and your backend
// (in this example, 80% of calls to your instrumented backend are linked from the RUM view to
// the APM view. Default is 20%).
// You need to specify the hosts of your backends to enable tracing with these backends
resourceTraceSampleRate: 80,
firstPartyHosts: [
{
match: 'example.com',
propagatorTypes: [
PropagatorType.DATADOG,
PropagatorType.TRACECONTEXT
]
}
]
},
// Enable Logs with default configuration
logsConfiguration: {},
// Enable Trace with default configuration
traceConfiguration: {}
);
// Wrap the content of your App component in a DatadogProvider component, passing it your configuration:
export default function App() {
return (
<DatadogProvider configuration={config}>
<Navigation />
</DatadogProvider>
);
}
// Once the Datadog React Native SDK for RUM is initialized, you need to setup view tracking to be able to see data in a dashboard
Sample session rates
To control the data your application sends to Datadog RUM, you can specify a sampling rate for RUM sessions while initializing the RUM React Native SDK as a percentage between 0 and 100. You can specify the rate with the config.sessionSamplingRate parameter.
Set tracking consent (GDPR compliance)
To be compliant with the GDPR regulation, the React Native SDK requires the tracking consent value at initialization.
The trackingConsent setting can be one of the following values:
.PENDING: The React Native SDK starts collecting and batching the data but does not send it to Datadog. The React Native SDK waits for the new tracking consent value to decide what to do with the batched data..GRANTED: The React Native SDK starts collecting the data and sends it to Datadog..NOTGRANTED: The React Native SDK does not collect any data. No logs, traces, or RUM events are sent to Datadog.
To change the tracking consent value after the React Native SDK is initialized, use the Datadog.set(trackingConsent:) API call. The React Native SDK changes its behavior according to the new value.
For example, if the current tracking consent is .PENDING:
- If you change the value to
.GRANTED, the React Native SDK sends all current and future data to Datadog; - If you change the value to
.NOTGRANTED, the React Native SDK wipes all current data and does not collect future data.
User interactions tracking
The preferred way to set up interaction tracking is by using the Datadog React Native Babel Plugin (@datadog/mobile-react-native-babel-plugin). This plugin automatically enriches React components with contextual metadata, improving interaction tracking accuracy and enabling a range of configuration options.
Installation
To install with npm, run:
npm install @datadog/mobile-react-native-babel-plugin
To install with Yarn, run:
yarn add @datadog/mobile-react-native-babel-plugin
Configure Babel
Add the plugin to your Babel configuration file (babel.config.js, .babelrc, or similar):
module.exports = {
presets: ['module:@react-native/babel-preset'],
plugins: ['@datadog/mobile-react-native-babel-plugin']
};
After the plugin is installed and configured, it automatically tracks interactions on standard React Native components. No additional code changes are required for basic usage.
CodePush integration (optional)
If you're deploying updates with CodePush, see the CodePush setup documentation for additional configuration steps.
Step 1 - Install the SDK
The RUM React Native SDK supports Expo and Expo Go. To use it, install expo-datadog and @datadog/mobile-react-native.
expo-datadog supports Expo starting from SDK 45 and the plugin's versions follow Expo versions. For example, if you use Expo SDK 45, use expo-datadog version 45.x.x. Datadog recommends using Expo SDK 45 as a minimum version; previous versions may require manual steps.
To install with npm, run:
npm install expo-datadog @datadog/mobile-react-native
To install with Yarn, run:
yarn add expo-datadog @datadog/mobile-react-native
Step 2 - Specify application details in the UI
- In Datadog, navigate to Digital Experience > Add an Application.
- Choose
react-nativeas the application type. - Provide an application name to generate a unique Datadog application ID and client token.
- To disable automatic user data collection for client IP or geolocation data, uncheck the boxes for those settings.
If you've purchased Error Tracking as a standalone product (without RUM), navigate to Error Tracking > Settings > Browser and Mobile > Add an Application instead.
For data security, you must use a client token. For more information about setting up a client token, see the Client Token documentation.
Step 3 - Initialize the library with application context
Add the following code snippet to your initialization file:
import {
SdkVerbosity,
DatadogProvider,
DatadogProviderConfiguration,
PropagatorType
} from 'expo-datadog';
const config = new DatadogProviderConfiguration(
'<CLIENT_TOKEN>',
'<ENVIRONMENT_NAME>',
// Optional: Configure the Datadog Site to target. Default is 'US1'.
site: 'US1',
// Optional: Set the reported service name (by default, it uses the package name or bundleIdentifier of your Android or iOS app respectively)
service: 'com.example.reactnative',
// Optional: Let the SDK print internal logs above or equal to the provided level. Default is undefined (meaning no logs)
verbosity: SdkVerbosity.WARN,
// Enable RUM
rumConfiguration: {
// Required: RUM Application ID
applicationId: '<APPLICATION_ID>',
// Track user interactions (set to false if using Error Tracking only)
trackInteractions: true,
// Track XHR resources (set to false if using Error Tracking only)
trackResources: true,
// Track errors
trackErrors: true,
// Optional: Sample sessions, for example: 80% of sessions are sent to Datadog. Default is 100%.
sessionSampleRate: 80,
// Optional: Enable or disable native crash reports.
nativeCrashReportEnabled: true,
// Optional: Sample tracing integrations for network calls between your app and your backend
// (in this example, 80% of calls to your instrumented backend are linked from the RUM view to
// the APM view. Default is 20%).
// You need to specify the hosts of your backends to enable tracing with these backends
resourceTraceSampleRate: 80,
firstPartyHosts: [
{
match: 'example.com',
propagatorTypes: [
PropagatorType.DATADOG,
PropagatorType.TRACECONTEXT
]
}
]
},
// Enable Logs with default configuration
logsConfiguration: {},
// Enable Trace with default configuration
traceConfiguration: {}
);
// Wrap the content of your App component in a DatadogProvider component, passing it your configuration:
export default function App() {
return (
<DatadogProvider configuration={config}>
<Navigation />
</DatadogProvider>
);
}
// Once the Datadog React Native SDK for RUM is initialized, you need to setup view tracking to be able to see data in a dashboard
Sample session rates
To control the data your application sends to Datadog RUM, you can specify a sampling rate for RUM sessions. To set this rate, use the config.sessionSamplingRate parameter and specify a percentage between 0 and 100.
Upload source maps on EAS builds
To enable crash reporting and error symbolication, add expo-datadog to your plugins in the app.json file:
{
"expo": {
"plugins": ["expo-datadog"]
}
}
This plugin takes care of uploading the dSYMs, source maps and Proguard mapping files on every EAS build.
Add @datadog/datadog-ci as a development dependency. This package contains scripts to upload the source maps. You can install it with npm:
npm install @datadog/datadog-ci --save-dev
or with Yarn:
yarn add -D @datadog/datadog-ci
Run eas secret:create to set DATADOG_API_KEY to your Datadog API key, and DATADOG_SITE to the host of your Datadog site (for example, datadoghq.com).
User interactions tracking
Datadog recommends setting up interaction tracking by using the Datadog React Native Babel Plugin (@datadog/mobile-react-native-babel-plugin). This plugin automatically enriches React components with contextual metadata, improving interaction tracking accuracy and enabling a range of configuration options.
To install with npm, run:
npm install @datadog/mobile-react-native-babel-plugin
To install with Yarn, run:
yarn add @datadog/mobile-react-native-babel-plugin
Add the plugin to your Babel configuration file (babel.config.js, .babelrc, or similar):
module.exports = {
presets: ["babel-preset-expo"],
plugins: ['@datadog/mobile-react-native-babel-plugin']
};
After the plugin is installed and configured, it automatically tracks interactions on standard React Native components. No additional code changes are required for basic usage.
CodePush integration (optional)
If you're deploying updates with CodePush, see the CodePush setup documentation for additional configuration steps.
This page describes how to instrument your applications for Real User Monitoring (RUM) with the Kotlin Multiplatform SDK. RUM includes Error Tracking by default, but if you have purchased Error Tracking as a standalone product, see the Error Tracking setup guide for specific steps.
The Datadog Kotlin Multiplatform SDK supports Android 5.0+ (API level 21) and iOS v12+.
Setup
Step 1 - Declare the Kotlin Multiplatform SDK as a dependency
Declare dd-sdk-kotlin-multiplatform-rum as a common source set dependency in your Kotlin Multiplatform module's build.gradle.kts file.
kotlin {
// declare targets
// ...
sourceSets {
// ...
commonMain.dependencies {
implementation("com.datadoghq:dd-sdk-kotlin-multiplatform-rum:<latest_version>")
}
}
}
Step 2 - Add native dependencies for iOS
Kotlin 2.0.20 or higher is required if crash tracking is enabled on iOS. Otherwise, due to the compatibility with PLCrashReporter, the application may hang if crash tracking is enabled.
Add the following Datadog iOS SDK dependencies, which are needed for the linking step:
DatadogCoreDatadogRUMDatadogCrashReporting
Note: Versions of these dependencies should be aligned with the version used by the Datadog Kotlin Multiplatform SDK itself. You can find the complete mapping of iOS SDK versions for each Kotlin Multiplatform SDK release in the version compatibility guide. If you are using Kotlin Multiplatform SDK version 1.3.0 or below, add DatadogObjc dependency instead of DatadogCore and DatadogRUM.
Adding native iOS dependencies using the CocoaPods plugin
If you are using Kotlin Multiplatform library as a CocoaPods dependency for your iOS application, you can add dependencies as following:
cocoapods {
// ...
framework {
baseName = "sharedLib"
}
pod("DatadogCore") {
linkOnly = true
version = x.x.x
}
pod("DatadogRUM") {
linkOnly = true
version = x.x.x
}
pod("DatadogCrashReporting") {
linkOnly = true
version = x.x.x
}
}
Adding native iOS dependencies using Xcode
If you are integrating Kotlin Multiplatform library as a framework with an embedAndSignAppleFrameworkForXcode Gradle task as a part of your Xcode build, you can add the necessary dependencies directly in Xcode as following:
- Click on your project in Xcode and go to the Package Dependencies tab.
- Add the iOS SDK package dependency by adding
https://github.com/DataDog/dd-sdk-ios.gitas a package URL. - Select the version from the table above.
- Click on the necessary application target and open the General tab.
- Scroll down to the Frameworks, Libraries, and Embedded Content section and add the dependencies mentioned above.
Step 3 - Specify application details in the UI
- Navigate to Digital Experience > Add an Application.
- Select
Kotlin Multiplatformas the application type and enter an application name to generate a unique Datadog application ID and client token. - To disable automatic user data collection for either client IP or geolocation data, uncheck the boxes for those settings. For more information, see RUM Kotlin Multiplatform Data Collected.
If you've purchased Error Tracking as a standalone product (without RUM), navigate to Error Tracking > Settings > Browser and Mobile > Add an Application instead.
To ensure the safety of your data, you must use a client token. If you use only Datadog API keys to configure the Datadog SDK, they are exposed client-side in the Android application's APK byte code.
For more information about setting up a client token, see the Client Token documentation.
Step 4 - Initialize Datadog SDK
In the initialization snippet, set an environment name. For Android, set a variant name if it exists. For more information, see Using Tags.
See trackingConsent to add GDPR compliance for your EU users, and other configuration options to initialize the library.
// in common source set
fun initializeDatadog(context: Any? = null) {
// context should be application context on Android and can be null on iOS
val appClientToken = <CLIENT_TOKEN>
val appEnvironment = <ENV_NAME>
val appVariantName = <APP_VARIANT_NAME>
val configuration = Configuration.Builder(
clientToken = appClientToken,
env = appEnvironment,
variant = appVariantName
)7ae6e469-e055-4ddf-af26-9a785f2dc717
.build()
Datadog.initialize(context, configuration, trackingConsent)
}
Step 5 - Sample RUM sessions
To control the data your application sends to Datadog RUM, you can specify a sample rate for RUM sessions while initializing the RUM feature. The rate is a percentage between 0 and 100. By default, sessionSamplingRate is set to 100 (keep all sessions).
val rumConfig = RumConfiguration.Builder(applicationId)
// Here 75% of the RUM sessions are sent to Datadog
.setSessionSampleRate(75.0f)
.build()
Rum.enable(rumConfig)
Step 6 - Enable RUM to start sending data
// in a common source set
fun initializeRum(applicationId: String) {
val rumConfiguration = RumConfiguration.Builder(applicationId)
.trackLongTasks(durationThreshold)
.apply {
// platform specific setup
rumPlatformSetup(this)
}
.build()
Rum.enable(rumConfiguration)
}
internal expect fun rumPlatformSetup(rumConfigurationBuilder: RumConfiguration.Builder)
// in iOS source set
internal actual fun rumPlatformSetup(rumConfigurationBuilder: RumConfiguration.Builder) {
with(rumConfigurationBuilder) {
trackUiKitViews()
trackUiKitActions()
// check more iOS-specific methods
}
}
// in Android source set
internal actual fun rumPlatformSetup(rumConfigurationBuilder: RumConfiguration.Builder) {
with(rumConfigurationBuilder) {
useViewTrackingStrategy(/** choose view tracking strategy **/)
trackUserInteractions()
// check more Android-specific methods
}
}
See Automatically track views to enable automatic tracking of all your views.
Set tracking consent (GDPR compliance)
To be compliant with GDPR, the SDK requires the tracking consent value at initialization. Tracking consent can be one of the following values:
TrackingConsent.PENDING: (Default) The SDK starts collecting and batching the data but does not send it to the collection endpoint. The SDK waits for the new tracking consent value to decide what to do with the batched data.TrackingConsent.GRANTED: The SDK starts collecting the data and sends it to the data collection endpoint.TrackingConsent.NOT_GRANTED: The SDK does not collect any data. You are not able to manually send any logs, traces, or RUM events.
To update the tracking consent after the SDK is initialized, call Datadog.setTrackingConsent(<NEW CONSENT>). The SDK changes its behavior according to the new consent. For example, if the current tracking consent is TrackingConsent.PENDING and you update it to:
TrackingConsent.GRANTED: The SDK sends all current batched data and future data directly to the data collection endpoint.TrackingConsent.NOT_GRANTED: The SDK wipes all batched data and does not collect any future data.
Step 7 - Initialize the RUM Ktor plugin to track network events made with Ktor
- In your
build.gradle.ktsfile, add the Gradle dependency todd-sdk-kotlin-multiplatform-ktorfor Ktor 2.x, ordd-sdk-kotlin-multiplatform-ktor3for Ktor 3.x:
kotlin {
// ...
sourceSets {
// ...
commonMain.dependencies {
// Use this line if you are using Ktor 2.x
implementation("com.datadoghq:dd-sdk-kotlin-multiplatform-ktor:x.x.x")
// Use this line if you are using Ktor 3.x
// implementation("com.datadoghq:dd-sdk-kotlin-multiplatform-ktor3:x.x.x")
}
}
}
- To track your Ktor requests as resources, add the provided Datadog Ktor plugin:
val ktorClient = HttpClient {
install(
datadogKtorPlugin(
tracedHosts = mapOf(
"example.com" to setOf(TracingHeaderType.DATADOG),
"example.eu" to setOf(TracingHeaderType.DATADOG)
),
traceSampleRate = 100f
)
)
}
This records each request processed by the HttpClient as a resource in RUM, with all the relevant information automatically filled (URL, method, status code, and error). Only the network requests that started when a view is active are tracked. To track requests when your application is in the background, create a view manually or enable background view tracking.
Track errors
Kotlin Multiplatform Crash Reporting and Error Tracking displays any issues in your application and the latest available errors. You can view error details and attributes including JSON in the RUM Explorer.
Sending data when device is offline
RUM ensures availability of data when your user device is offline. In case of low-network areas, or when the device battery is too low, all the RUM events are first stored on the local device in batches.
Each batch follows the intake specification. They are sent as soon as the network is available, and the battery is high enough to ensure the Datadog SDK does not impact the end user's experience. If the network is not available while your application is in the foreground, or if an upload of data fails, the batch is kept until it can be sent successfully.
This means that even if users open your application while offline, no data is lost. To ensure the SDK does not use too much disk space, the data on the disk is automatically discarded if it gets too old.
This page describes how to instrument your applications for Real User Monitoring (RUM) with the Roku SDK. RUM includes Error Tracking by default, but if you have purchased Error Tracking as a standalone product, see the Error Tracking setup guide for specific steps.
The Datadog Roku SDK supports BrightScript channels for Roku OS 10 and higher.
Setup
Step 1 - Declare the SDK as a dependency
Using ROPM (recommended)
ROPM is a package manager for the Roku platform (based on NPM). If you're not already using ROPM in your Roku project, read their Getting started guide. Once your project is set up to use ROPM, you can use the following command to install the Datadog dependency:
ropm install datadog-roku
Setup manually
If your project does not use ROPM, install the library manually by downloading the Roku SDK zip archive and unzipping it in your project's root folder.
Make sure you have a roku_modules/datadogroku subfolder in both the components and source folders of your project.
Step 2 - Specify application details in the UI
- Navigate to Digital Experience > Add an Application.
- Select Roku as the application type and enter an application name to generate a unique Datadog application ID and client token.
- To disable automatic user data collection for client IP or geolocation data, uncheck the boxes for those settings. For more information, see Roku Data Collected.
If you've purchased Error Tracking as a standalone product (without RUM), navigate to Error Tracking > Settings > Browser and Mobile > Add an Application instead.
To ensure the safety of your data, you must use a client token. If you use only Datadog API keys to configure the dd-sdk-roku library, they are exposed client-side in the Roku channel's BrightScript code.
For more information about setting up a client token, see the Client Token documentation.
Step 3 - Initialize the library
In the initialization snippet, set an environment name. For more information, see Using Tags.
sub RunUserInterface(args as dynamic)
screen = CreateObject("roSGScreen")
scene = screen.CreateScene("MyScene")
screen.show()
datadogroku_initialize({
clientToken: "<CLIENT_TOKEN>",
applicationId: "<APPLICATION_ID>"
site: "",
env: "<ENV_NAME>",
sessionSampleRate: 100, ' the percentage (integer) of sessions to track
launchArgs: args
})
' complete your channel setup here
end sub
Sample session rates
To control the data your application sends to Datadog RUM, you can specify a sampling rate for RUM sessions while initializing the RUM Roku SDK. The rate is a percentage between 0 and 100. By default, sessionSamplingRate is set to 100 (keep all sessions).
Instrument the channel
See Track RUM Resources to enable automatic tracking of all your resources, and Enrich user sessions to add custom global or user information to your events.
Track Views
To split user sessions into logical steps, manually start a View using the following code. Every navigation to a new screen within your channel should correspond to a new View.
viewName = "VideoDetails"
viewUrl = "components/screens/VideoDetails.xml"
m.global.datadogRumAgent.callfunc("startView", viewName, viewUrl)
Track RUM Actions
RUM Actions represent the interactions your users have with your channel. You can forward actions to Datadog as follows:
targetName = "playButton" ' the name of the SG Node the user interacted with
actionType = "click" ' the type of interaction, should be one of "click", "back", or "custom"
m.global.datadogRumAgent.callfunc("addAction", { target: targetName, type: actionType})
Track RUM errors
Whenever you perform an operation that might throw an exception, you can forward the error to Datadog as follows:
try
doSomethingThatMightThrowAnException()
catch error
m.global.datadogRumAgent.callfunc("addError", error)
end try
Sending data when device is offline
RUM ensures availability of data when your user device is offline. In case of low-network areas, or when the device battery is too low, all the RUM events are first stored on the local device in batches.
Each batch follows the intake specification. They are sent as soon as the network is available, and the battery is high enough to ensure the Datadog SDK does not impact the end user's experience. If the network is not available while your application is in the foreground, or if an upload of data fails, the batch is kept until it can be sent successfully.
This means that even if users open your application while offline, no data is lost. To ensure the SDK does not use too much disk space, the data on the disk is automatically discarded if it gets too old.
This page describes how to instrument your applications for Real User Monitoring (RUM) with the Unity SDK. RUM includes Error Tracking by default, but if you have purchased Error Tracking as a standalone product, see the Error Tracking setup guide for specific steps.
Datadog supports Unity Monitoring for iOS and Android for Unity LTS 2022+.
Datadog does not support Desktop (Windows, Mac, or Linux) or console deployments from Unity. If you have a game or application and want to use Datadog RUM to monitor its performance, create a ticket with Datadog support.
Step 1 - Install the SDK
Install the External Dependency Manager for Unity (EDM4U). This can be done using Open UPM.
Add the Datadog SDK Unity package from its Git URL at https://github.com/DataDog/unity-package. The package URL is
https://github.com/DataDog/unity-package.git.(Android only) Configure your project to use Gradle templates, and enable both
Custom Main TemplateandCustom Gradle Properties Template.(Android only) If you build and receive
Duplicate classerrors (common in Unity 2022.x), add the following code to thedependenciesblock of yourmainTemplate.gradle:
constraints {
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.8.0") {
because("kotlin-stdlib-jdk8 is now a part of kotlin-stdlib")
}
}
WebGL
Create a custom WebGL template, following the instructions provided by Unity, or by using the minimally modified version in Datadog's GitHub repo.
If you are using your own WebGL template, or have added a new WebGL template, modify it to include the Datadog Browser SDK delivered by CDN.
<script type="text/javascript" src="https://www.datadoghq-browser-agent.com/us1/v6/datadog-logs.js"></script>
<script type="text/javascript" src="https://www.datadoghq-browser-agent.com/us1/v6/datadog-rum-slim.js"></script>
Step 2 - Specify application details in the UI
- In Datadog, navigate to Digital Experience > Add an Application.
- Choose Unity as the application type.
- Provide an application name to generate a unique Datadog application ID and client token.
- To disable automatic user data collection for either client IP or geolocation data, uncheck the boxes for those settings.
To ensure the safety of your data, you must use a client token. For more information about setting up a client token, see the Client Token documentation.
Step 3 - Configure Datadog settings in Unity
After installing the Datadog Unity SDK, you need to set Datadog's settings in the Unity UI. Navigate to your Project Settings and click on the Datadog section on the left hand side.
The following parameters are available:
| Parameter | Required? | Description |
|---|---|---|
| Enable Datadog | No | Whether Datadog should be enabled. Disabling Datadog does not cause any of the Datadog APIs to fail, throw exceptions, or return null from any calls. It only stops the SDK from sending any information. |
| Output Symbol Files | No | This option enables the output of symbol files for Datadog symbolication and file/line mapping features in Datadog Error Tracking. |
| Perform Native Stack Mapping | No | Converts C# stacks traces to native stack traces in non-development builds. This allows for file and line mapping to C# code if symbol files are uploaded to Datadog. This is not supported if Output Symbols is disabled. |
| Client Token | Yes | Your client token created for your application on Datadog's website. |
| Env | No | The name of the environment for your application. Defaults to "prod". |
| Service Name | No | The service name for your application. If this is not set, it is automatically set to your application's package name or bundle name (e.g.: com.example.android). |
| Datadog Site | Yes | The site you send your data to. |
| Batch Size | Yes | Sets the preferred size of batched data uploaded to Datadog. This value impacts the size and number of requests performed by the SDK (small batches mean more requests, but each request becomes smaller in size). |
| Upload Frequency | Yes | Sets the preferred frequency of uploading data to Datadog. |
| Batch Processing Level | Yes | Defines the maximum amount of batches processed sequentially without a delay within one reading/uploading cycle. |
| Enable Crash Reporting | No | Enables crash reporting in the RUM SDK. |
| Forward Unity Logs | No | Whether to forward logs made from Unity's Debug.Log calls to Datadog's default logger. |
| Remote Log Threshold | Yes | The level at which the default logger forwards logs to Datadog. Logs below this level are not sent. |
| Enable RUM | No | Whether to enable sending data from Datadog's Real User Monitoring APIs |
| Enable Automatic Scene Tracking | No | Whether Datadog should automatically track new Views by intercepting Unity's SceneManager loading. |
| RUM Application ID | Yes (if RUM is enabled) | The RUM Application ID created for your application on Datadog's website. |
| Session Sample Rate | Yes | The percentage of sessions to send to Datadog. Between 0 and 100. |
| Trace Sample Rate | Yes | The percentage of distributed traces to send to Datadog. Between 0 and 100. |
| Trace Context Injection | Yes | Whether to inject trace context into All or Only Sampled resource requests. |
| Track Non-Fatal ANRs | No | (Android Only) Whether to track non-fatal ANRs (Application Not Responding) errors. The "SDK Default" option disables ANR detection on Android 30+ because it would create too much noise over fatal ANRs. On Android 29 and below, however, the reporting of non-fatal ANRs is enabled by default, as fatal ANRs cannot be reported on those versions. |
| Track Non-Fatal App Hangs | No | (iOS Only) Whether to track non-fatal app hangs. App hangs are detected when the app is unresponsive for a certain amount of time. The supplied "Threshold" is the amount of time in seconds that the app must be unresponsive before it is considered a non-fatal app hang. |
| First Party Hosts | No | To enable distributed tracing, you must specify which hosts are considered "first party" and have trace information injected. |
Sample RUM sessions
You can control the data your application sends to Datadog RUM during instrumentation of the RUM Unity SDK. Specify the Session Sample Rate as a percentage between 0 and 100 in the Project Settings window in Unity.
Using Datadog
Setting tracking consent
To be compliant with data protection and privacy policies, the Datadog Unity SDK requires setting a tracking consent value.
The trackingConsent setting can be one of the following values:
TrackingConsent.Pending: The Unity SDK starts collecting and batching the data but does not send it to Datadog. The Unity SDK waits for the new tracking consent value to decide what to do with the batched data.TrackingConsent.Granted: The Unity SDK starts collecting the data and sends it to Datadog.TrackingConsent.NotGranted: The Unity SDK does not collect any data. No logs are sent to Datadog.
Before Datadog sends any data, confirm the user's Tracking Consent. This is set to TrackingConsent.Pending during initialization, and needs to be set to TrackingConsent.Granted before Datadog sends any information.
DatadogSdk.Instance.SetTrackingConsent(TrackingConsent.Granted);
Logging
You can intercept and send logs from Unity's default debug logger by enabling the option and threshold in your projects settings.
Datadog maps the Unity levels to the following in Datadog's Logging Levels:
| Unity LogType | Datadog Log Level |
|---|---|
| Log | Info |
| Error | Error |
| Assert | Critical |
| Warning | Warn |
| Exception | Critical |
You can access this default logger to add attributes or tags through the DatadogSdk.DefaultLogger property.
You can also create additional loggers for more fine grained control of thresholds, service names, logger names, or to supply additional attributes.
var logger = DatadogSdk.Instance.CreateLogger(new DatadogLoggingOptions()
{
NetworkInfoEnabled = true,
DatadogReportingThreshold = DdLogLevel.Debug,
});
logger.Info("Hello from Unity!");
logger.Debug("Hello with attributes", new()
{
{ "my_attribute", 122 },
{ "second_attribute", "with_value" },
{ "bool_attribute", true },
{
"nested_attribute", new Dictionary<string, object>()
{
{ "internal_attribute", 1.234 },
}
},
});
Real User Monitoring (RUM)
Manual Scene (View) Tracking
To manually track new Scenes (Views in Datadog), use the StartView and StopView methods:
public void Start()
{
DatadogSdk.Instance.Rum.StartView("My View", new()
{
{ "view_attribute": "active" }
});
}
Starting a new view automatically ends the previous view.
Automatic Scene Tracking
You can also set Enable Automatic Scene Tracking in your Project Settings to enable automatically tracking active scenes. This uses Unity's SceneManager.activeSceneChanged event to automatically start new scenes.
Web Requests / Resource Tracking
Datadog offers DatadogTrackedWebRequest, which is a UnityWebRequest wrapper intended to be a drop-in replacement for UnityWebRequest. DatadogTrackedWebRequest enables Datadog Distributed Tracing.
To enable Datadog Distributed Tracing, you must set the First Party Hosts in your project settings to a domain that supports distributed tracing. You can also modify the sampling rate for distributed tracing by setting the Tracing Sampling Rate.
First Party Hosts does not allow wildcards, but matches any subdomains for a given domain. For example, api.example.com matches staging.api.example.com and prod.api.example.com, but not news.example.com.
Sending data when device is offline
RUM helps ensure availability of data when your user device is offline. In case of low-network areas, or when the device battery is too low, all the RUM events are first stored on the local device in batches.
Each batch follows the intake specification. They are sent as soon as the network is available, and the battery is high enough to help ensure the Datadog SDK does not impact the end user's experience. If the network is not available while your application is in the foreground, or if an upload of data fails, the batch is kept until it can be sent successfully.
This means that even if users open your application while offline, no data is lost. To help ensure the SDK does not use too much disk space, the data on the disk is automatically discarded if it gets too old.
