Interaction, error, and resource automated tracking is disabled in your tests if you initialize the SDK with the DatadogProvider component.
All SDK methods are mocked by jest.fn(), so you can assert that a Datadog SDK method was called:
import{DdLogs}from'@datadog/mobile-react-native';describe('App',()=>{it('calls DdLogs.debug on mount',()=>{renderer.create(<App/>);expect(DdLogs.debug).toHaveBeenCalledWith('app started');});});
If you use a test runner other than Jest, you need to create the mocks for your test runner.
Initialization parameters
You can specify the following parameters in your configuration when initializing the SDK:
Optional Type: String The service name for your application. Follows the tag syntax requirements.
version
Optional Type: String The application’s version. For example: 1.2.3, 6c44da20, and 2020.02.13. Follows the tag syntax requirements.
versionSuffix
Optional Type: String Add a suffix to the reported version of the app. Accepted characters are alphanumerics and _, -, :, ., /. Other special characters are converted to underscores. A dash (-) is automatically added between the version and the suffix. Follows the tag syntax requirements.
Optional - Deprecated Type: Number Default: 100 See sessionSampleRate.
sessionSamplingRate
Optional Type: Number Default: 100 The percentage of sessions to track: 100 for all, 0 for none. Only tracked sessions send RUM events.
resourceTracingSamplingRate
Optional Type: Number Default: 20 The percentage of requests to trace: 100 for all, 0 for none. For more information, see Connect RUM and Traces.
verbosity
Optional Type: SdkVerbosity Default: undefined Verbosity for internal SDK logging. Set to SdkVerbosity.DEBUG to debug your SDK implementation.
nativeViewTracking
Optional Type: Boolean Default: false Enables native views tracking. Set to true if you use a custom navigation system relying on native views.
nativeInteractionTracking
Optional Type: Boolean Default: false Enables native interaction tracking. Set to true if you want to track interactions on native screens.
firstPartyHosts
Optional Type: List Default: [] List of your backends hosts to enable tracing with. For more information, see Connect RUM and Traces.
telemetrySampleRate
Optional Type: Number Default: 20 Telemetry data (such as errors and debug logs) about SDK execution is sent to Datadog in order to detect and solve potential issues. Set this option to 0 to opt out from telemetry collection.
longTaskThresholdMs
Optional Type: Number | false Default: 0 The threshold for JavaScript long tasks reporting in milliseconds. Setting it to 0 or false disables JavaScript long task reporting. Values below 100 are raised to 100. Values above 5000 are lowered to 5000.
nativeLongTaskThresholdMs
Optional Type: Number | false Default: 200 The threshold for native long tasks reporting in milliseconds. Setting it to 0 or false disables native long task reporting. Values below 100 are raised to 100. Values above 5000 are lowered to 5000.
vitalsUpdateFrequency
Optional Type: VitalsUpdateFrequency Default: VitalsUpdateFrequency.AVERAGE Sets the preferred frequency for collecting mobile vitals.
uploadFrequency
Optional Type: UploadFrequency Default: UploadFrequency.AVERAGE Sets the preferred frequency for uploading batches of data.
batchSize
Optional Type: BatchSize Default: BatchSize.MEDIUM Defines the Datadog SDK policy when batching data together before uploading it to Datadog servers. Smaller batches mean smaller but more network requests, whereas larger batches mean fewer but larger network requests.
trackBackgroundEvents
Optional Type: Boolean Default: false Enables tracking of RUM event when no RUM View is active. By default, background events are not tracked. Enabling this feature might increase the number of sessions tracked and impact your billing.
Optional Type: Boolean Default: true Determines whether the accessibility labels are used to name RUM actions (default is true).
bundleLogsWithRum
Optional Type: Boolean Default: true Enables RUM correlation with logs (default is true).
bundleLogsWithTraces
Optional Type: Boolean Default: true Enables trace correlation with logs (default is true).
Manual instrumentation
If automatic instrumentation doesn’t suit your needs, you can manually create RUM Events and Logs:
Send logs
When you instrument your code to send logs, it can include debug, info, warn, or error details:
DdLogs.debug('Lorem ipsum dolor sit amet…',{});DdLogs.info('Lorem ipsum dolor sit amet…',{});DdLogs.warn('Lorem ipsum dolor sit amet…',{});DdLogs.error('Lorem ipsum dolor sit amet…',{});
Manually track RUM Views
To manually track RUM Views, provide a view key, view name, and action name at initialization. Depending on your needs, you can choose one of the following strategies:
You can notify the SDK that your view has finished loading by calling the addViewLoadingTime method on DdRum.
Call this method when your view is fully loaded and ready to be displayed to the user:
DdRum.addViewLoadingTime(true);
Use the overwrite parameter to replace the previously calculated loading time for the current view.
After the loading time is sent, it is accessible as @view.loading_time and is visible in the RUM UI.
If you want to clear the user information (for example, when the user signs out), you can do so by passing an empty object, as follows:
DdSdkReactNative.setUser({});
Global attributes
You can also keep global attributes to track information about a specific session, such as A/B testing configuration, ad campaign origin, or cart status.
Because React Native offers a wide range of libraries to create screen navigation, only manual view tracking is supported by default. To see RUM or Error tracking sessions populate in Datadog, you need to implement view tracking.
You can manually start and stop a view using the following startView() and stopView methods.
import{DdRum}from'@datadog/mobile-react-native';// Start a view with a unique view identifier, a custom view name, and an object to attach additional attributes to the view
DdRum.startView('<view-key>',// <view-key> has to be unique, for example it can be ViewName-unique-id
'View Name',{'custom.foo':'something'},Date.now());// Stops a previously started view with the same unique view identifier, and an object to attach additional attributes to the view
DdRum.stopView('<view-key>',{'custom.bar':42},Date.now());
Use one of Datadog’s integrations to automatically track views for the following libraries:
If you experience any issues setting up View tracking with @datadog/mobile-react-navigation you can see this Datadog example application as a reference.
Clear all data
Use clearAllData to clear all data that has not been sent to Datadog.
DdSdkReactNative.clearAllData();
Modify or drop RUM events
To modify attributes of a RUM event before it is sent to Datadog, or to drop an event entirely, use the Event Mappers API when configuring the RUM React Native SDK:
constconfig=newDdSdkReactNativeConfiguration('<CLIENT_TOKEN>','<ENVIRONMENT_NAME>','<RUM_APPLICATION_ID>',true,// track user interactions (such as a tap on buttons)
true,// track XHR resources
true// track errors
);config.logEventMapper=(event)=>event;config.errorEventMapper=(event)=>event;config.resourceEventMapper=(event)=>event;config.actionEventMapper=(event)=>event;
Each mapper is a function with a signature of (T) -> T?, where T is a concrete RUM event type. This allows changing portions of the event before it is sent, or dropping the event entirely.
For example, to redact sensitive information from a RUM error message, implement a custom redacted function and use it in errorEventMapper:
Contains the global user info set by DdSdkReactNative.setUser.
actionEvent.additionalInformation.attributes
Contains the global attributes set by DdSdkReactNative.setAttributes.
ErrorEvent
errorEvent.additionalInformation.userInfo
Contains the global user info set by DdSdkReactNative.setUser.
errorEvent.additionalInformation.attributes
Contains the global attributes set by DdSdkReactNative.setAttributes.
ResourceEvent
resourceEvent.resourceContext
XMLHttpRequest corresponding to the resource or undefined.
resourceEvent.additionalInformation.userInfo
Contains the global user info set by DdSdkReactNative.setUser.
resourceEvent.additionalInformation.attributes
Contains the global attributes set by DdSdkReactNative.setAttributes.
Retrieve the RUM session ID
Retrieving the RUM session ID can be helpful for troubleshooting. For example, you can attach the session ID to support requests, emails, or bug reports so that your support team can later find the user session in Datadog.
You can access the RUM session ID at runtime without waiting for the sessionStarted event:
First Byte: The time between the scheduled request and the first byte of the response. This includes time for the request preparation on the native level, network latency, and the time it took the server to prepare the response.
Download: The time it took to receive a response.
Initializing asynchronously
If your app includes a lot of animations when it starts, running code during these animations might delay them on some devices. To delay the Datadog React Native SDK for RUM to run after all current animations are started, set the initializationMode to InitializationMode.ASYNC in your configuration:
All interactions with the RUM SDK (view tracking, actions, resources tracing, and so on) are still recorded and kept in a queue with a limit of 100 events.
Logs are not recorded and calling a DdLogs method before the actual initialization might break logging.
If you experience any issue setting up the asynchronous initialization of Datadog, you can check out our example application.
Delaying the initialization
There may be situations where you want to wait before initializing the SDK. For example, when you want to use a different configuration based on the user role or to fetch the configuration from one of your servers.
In that case, you can auto-instrument your app from the start (automatically collect user interactions, XHR resources, and errors) and record up to 100 RUM and span events before initializing the SDK.
import{DatadogProvider,DatadogProviderConfiguration}from'@datadog/mobile-react-native';constdatadogAutoInstrumentation={trackErrors:true,trackInteractions:true,trackResources:true,firstPartyHosts:[''],resourceTracingSamplingRate:100};constinitializeApp=async()=>{constconfiguration=awaitfetchDatadogConfiguration();// Fetches the configuration from one of your servers
awaitDatadogProvider.initialize(configuration);};exportdefaultfunctionApp(){useEffect(()=>initializeApp(),[]);return(<DatadogProviderconfiguration={datadogAutoInstrumentation}><Navigation/></DatadogProvider>);}
Where your configuration has the following keys:
import{ProxyConfig,SdkVerbosity,TrackingConsent}from'@datadog/mobile-react-native';constconfiguration={clientToken:'<CLIENT_TOKEN>',env:'<ENVIRONMENT_NAME>',applicationId:'<RUM_APPLICATION_ID>',sessionSamplingRate:80,// Optional: sample RUM sessions (here, 80% of session will be sent to Datadog). Default = 100%
site:'US1',// Optional: specify Datadog site. Default = 'US1'
verbosity:SdkVerbosity.WARN,// Optional: let the SDK print internal logs (above or equal to the provided level). Default = undefined (no logs)
serviceName:'com.myapp',// Optional: set the reported service name. Default = package name / bundleIdentifier of your Android / iOS app respectively
nativeCrashReportEnabled:true,// Optional: enable native crash reports. Default = false
version:'1.0.0',// Optional: see overriding the reported version in the documentation. Default = VersionName / Version of your Android / iOS app respectively
versionSuffix:'codepush.v3',// Optional: see overriding the reported version in the documentation. Default = undefined
trackingConsent:TrackingConsent.GRANTED,// Optional: disable collection if user has not granted consent for tracking. Default = TrackingConsent.GRANTED
nativeViewTracking:true,// Optional: enables tracking of native views. Default = false
proxyConfig:newProxyConfig()// Optional: send requests through a proxy. Default = undefined
};