- 필수 기능
- 시작하기
- Glossary
- 표준 속성
- Guides
- Agent
- 통합
- 개방형텔레메트리
- 개발자
- Administrator's Guide
- API
- Datadog Mobile App
- CoScreen
- Cloudcraft
- 앱 내
- 서비스 관리
- 인프라스트럭처
- 애플리케이션 성능
- APM
- Continuous Profiler
- 스팬 시각화
- 데이터 스트림 모니터링
- 데이터 작업 모니터링
- 디지털 경험
- 소프트웨어 제공
- 보안
- AI Observability
- 로그 관리
- 관리
If you have not set up the SDK yet, follow the in-app setup instructions or see the React Native RUM setup documentation.
Testing apps using '@datadog/mobile-react-native'
might require completing extra steps, since Native Modules do not exist in testing environments.
Datadog provides mocks for the '@datadog/mobile-react-native'
package. To use them with Jest, add the following in your Jest setup file:
jest.mock('@datadog/mobile-react-native', () => {
return require('@datadog/mobile-react-native/jest/mock');
});
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.
You can specify the following parameters in your configuration when initializing the SDK:
clientToken
env
applicationId
trackInteractions
false
trackResources
false
trackErrors
false
site
US1
serviceName
version
versionSuffix
_
, -
, :
, .
, /
. Other special characters are converted to underscores. A dash (-
) is automatically added between the version and the suffix. Follows the tag syntax requirements.trackFrustrations
true
trackInteractions: true
.nativeCrashReportEnabled
false
sampleRate
100
sessionSampleRate
.sessionSampleRate
100
100
for all, 0
for none. Only tracked sessions send RUM events.resourceTracingSamplingRate
20
100
for all, 0
for none. For more information, see Connect RUM and Traces.verbosity
undefined
SdkVerbosity.DEBUG
to debug your SDK implementation.nativeViewTracking
false
true
if you use a custom navigation system relying on native views.nativeInteractionTracking
false
true
if you want to track interactions on native screens.firstPartyHosts
[]
telemetrySampleRate
20
0
to opt out from telemetry collection.longTaskThresholdMs
0
0
or false
disables javascript long task reporting. Values below 100
are raised to 100
. Values above 5000
are lowered to 5000
.nativeLongTaskThresholdMs
200
0
or false
disables javascript long task reporting. Values below 100
are raised to 100
. Values above 5000
are lowered to 5000
.vitalsUpdateFrequency
VitalsUpdateFrequency.AVERAGE
uploadFrequency
UploadFrequency.AVERAGE
batchSize
BatchSize.MEDIUM
trackBackgroundEvents
false
proxyConfig
useAccessibilityLabel
true
bundleLogsWithRum
true
bundleLogsWithTraces
true
If automatic instrumentation doesn’t suit your needs, you can manually create RUM Events and 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…', {});
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:
DdRum.startView('<view-key>', 'View Name', {}, Date.now());
//…
DdRum.stopView('<view-key>', { custom: 42 }, Date.now());
You can manually track RUM actions:
DdRum.addAction(RumActionType.TAP, 'action name', {}, Date.now());
To track a continuous action:
DdRum.startAction(RumActionType.TAP, 'action name', {}, Date.now());
//...
DdRum.stopAction({}, Date.now());
You can manually track RUM errors:
DdRum.addError('<message>', ErrorSource.SOURCE, '<stacktrace>', {}, Date.now());
You can manually track RUM resources:
DdRum.startResource('<res-key>', 'GET', 'http://www.example.com/api/v1/test', {}, Date.now());
//...
DdRum.stopResource('<res-key>', 200, 'xhr', (size = 1337), {}, Date.now());
You can add custom timings:
DdRum.addTiming('<timing-name>');
You can send spans manually:
const spanId = await DdTrace.startSpan('foo', { custom: 42 }, Date.now());
//...
DdTrace.finishSpan(spanId, { custom: 21 }, Date.now());
You can attach user information to all RUM events to get more detailed information from your RUM sessions.
For user-specific information, use the following code wherever you want in your app (after the SDK has been initialized). The id
, name
, and email
attributes are built into Datadog, and you can add other attributes that makes sense for your app.
DdSdkReactNative.setUser({
id: '1337',
name: 'John Smith',
email: 'john@example.com',
type: 'premium'
});
If you want to add or update user information, you can use the following code to modify the existing user’s details.
DdSdkReactNative.addUserExtraInfo({
hasPaid: 'true'
});
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({});
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.
DdSdkReactNative.setAttributes({
profile_mode: 'wall',
chat_enabled: true,
campaign_origin: 'example_ad_network'
});
Use clearAllData
to clear all data that has not been sent to Datadog.
DdSdkReactNative.clearAllData();
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:
const config = new DdSdkReactNativeConfiguration(
'<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
:
config.errorEventMapper = (event) => {
event.message = redacted(event.message);
return event;
};
Returning null
from the error, resource, or action mapper drops the event entirely; the event is not sent to Datadog.
Depending on the event type, only some specific properties can be modified:
Event Type | Attribute key | Description |
---|---|---|
LogEvent | logEvent.message | Message of the log. |
logEvent.context | Custom attributes of the log. | |
ActionEvent | actionEvent.context | Custom attributes of the action. |
ErrorEvent | errorEvent.message | Error message. |
errorEvent.source | Source of the error. | |
errorEvent.stacktrace | Stacktrace of the error. | |
errorEvent.context | Custom attributes of the error. | |
errorEvent.timestampMs | Timestamp of the error. | |
ResourceEvent | resourceEvent.context | Custom attributes of the resource. |
Events include additional context:
Event Type | Context attribute key | Description |
---|---|---|
LogEvent | logEvent.additionalInformation.userInfo | Contains the global user info set by DdSdkReactNative.setUser . |
logEvent.additionalInformation.attributes | Contains the global attributes set by DdSdkReactNative.setAttributes . | |
ActionEvent | actionEvent.actionContext | GestureResponderEvent corresponding to the action or undefined . |
actionEvent.additionalInformation.userInfo | 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 . |
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:
fun getCurrentSessionId(promise: Promise) {
datadog.getRumMonitor().getCurrentSessionId {
promise.resolve(it)
}
}
Resource tracking provides the following timings:
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.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:
import { DatadogProvider, DatadogProviderConfiguration, InitializationMode } from '@datadog/mobile-react-native';
const datadogConfiguration = new DatadogProviderConfiguration(
'<CLIENT_TOKEN>',
'<ENVIRONMENT_NAME>',
'<RUM_APPLICATION_ID>',
true,
true,
true
);
datadogConfiguration.initializationMode = InitializationMode.ASYNC;
export default function App() {
return (
<DatadogProvider configuration={datadogConfiguration}>
<Navigation />
</DatadogProvider>
);
}
This uses React Native’s InteractionManager.runAfterInteractions to delay the animations.
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.
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';
const datadogAutoInstrumentation = {
trackErrors: true,
trackInteractions: true,
trackResources: true,
firstPartyHosts: [''],
resourceTracingSamplingRate: 100
};
const initializeApp = async () => {
const configuration = await fetchDatadogConfiguration(); // Fetches the configuration from one of your servers
await DatadogProvider.initialize(configuration);
};
export default function App() {
useEffect(() => initializeApp(), []);
return (
<DatadogProvider configuration={datadogAutoInstrumentation}>
<Navigation />
</DatadogProvider>
);
}
Where your configuration has the following keys:
import { ProxyConfig, SdkVerbosity, TrackingConsent } from '@datadog/mobile-react-native';
const configuration = {
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: new ProxyConfig() // Optional: send requests through a proxy. Default = undefined
};
See Monitor hybrid React Native applications.