Skip to content

RUM Configuration

This document describes the Cocos Creator RUM initialization parameters, automatic collection scope, and Native monitoring configuration.

RUM Initialization

Note

In the code examples on this page, ... indicates that the basic sdk configuration (for example, datakitUrl) has been omitted. Complete the common configuration by referring to SDK Initialization first; this page only shows RUM-related configuration.

truewatchSdk.start({
  ...,
  rum: {
    androidAppId: 'android-rum-app-id',
    iosAppId: 'ios-rum-app-id',
    sampleRate: 1,
    sessionOnErrorSampleRate: 0,
    enableNativeCrash: true,
    enableNativeAnr: true,
    globalContext: {
      game_mode: 'ranked',
    },
  },
});
Field Type Required Description
androidAppId string Required for Android Android RUM application ID
iosAppId string Required for iOS iOS RUM application ID
sampleRate number No Session sampling rate, range 0–1
sessionOnErrorSampleRate number No Supplemental sampling rate for error sessions not selected by normal sampling, range 0–1
enableNativeUserAction boolean No Whether to collect Native UI Actions
enableNativeUserView boolean No Whether to collect Native Views
enableNativeUserResource boolean No Whether to automatically collect Native network Resources
enableNativeCrash boolean No Whether to collect Native crashes
enableNativeAnr boolean No Whether to collect Native ANR
enableNativeUiBlock boolean No Whether to collect Native UI jank or Freeze
nativeUiBlockDurationMs number No Native UI jank threshold, in milliseconds; effective only when enableNativeUiBlock is enabled
errorMonitorType number No Native SDK bitmask for additional monitoring items attached to error events
deviceMetricsMonitorType number No Native SDK bitmask for View device metrics monitoring items
detectFrequency normal / frequent / rare No Device metrics detection frequency
globalContext Record<string, string> No Static global tags added to RUM data

The Android runtime requires androidAppId, and the iOS runtime requires iosAppId. A single cross-platform TypeScript configuration can provide both values.

errorMonitorType and deviceMetricsMonitorType pass through numeric bitmasks directly and must remain consistent with the definitions of the current Native SDK version. For specific combinations, refer to Android RUM Configuration and iOS RUM Configuration.

Cocos Automatic Collection

Automatic collection is enabled through the autoTrack configuration of truewatchSdk.start(). All options are disabled by default:

truewatchSdk.start({
  ...,
  rum: {
    androidAppId: 'android-rum-app-id',
    iosAppId: 'ios-rum-app-id',
  },
  logger: {
    enableCustomLog: true,
  },
  trace: {
    traceType: 'ddTrace',
  },
  autoTrack: {
    scenes: true,
    actions: true,
    errors: true,
    console: false,
    network: true,
  },
});
Field Collection behavior Dependency
scenes Closes the previous View when a scene starts and starts a new View with the scene name RUM
actions Converts global TOUCH_END events into Actions; prefers the event target node name and appends touch coordinates RUM
errors Listens for uncaught JavaScript Errors and Promise rejections RUM; the runtime must also provide globalThis.addEventListener and globalThis.removeEventListener
console Wraps console.log/info/warn/error and converts them into custom logs Log; see Log Configuration
network Wraps fetch and XMLHttpRequest, collects Resources, and injects Trace headers RUM; Trace headers also require Trace to be initialized

Calling truewatchSdk.shutdown() restores the Console, Fetch, XHR, and scene/touch listeners.

Runtime prerequisites for automatic JavaScript Error collection

When autoTrack.errors is enabled, the SDK collects uncaught JavaScript exceptions and unhandled Promise rejections through the global error and unhandledrejection events. The SDK registers these two listeners only when the current Cocos JavaScript runtime provides both globalThis.addEventListener and globalThis.removeEventListener.

If the runtime does not provide these APIs, errors: true does not install error listeners and does not throw an initialization error. Exceptions already caught by business code do not trigger global events; you need to report them manually by calling truewatchSdk.rum.addError().

Avoid duplicate collection

autoTrack.actions and enableNativeUserAction, as well as autoTrack.network and enableNativeUserResource, may cover the same interaction or request. Choose either the Cocos layer or the Native layer for automatic collection based on the actual request stack, and check in a test environment whether duplicate data is produced.

Manual RUM Instrumentation

When automatic collection cannot cover scenarios such as custom pages, business operations, caught exceptions, and custom network stacks, you can report data manually through truewatchSdk.rum. In standalone mode, initialize rum first in truewatchSdk.start(); in native host Hybrid mode, the native side must initialize RUM first.

Attribute Types

The attributes parameter in the following methods is optional and supports JSON-serializable strings, numbers, booleans, null, arrays, and objects.

Action

Add an immediate Action:

truewatchSdk.rum.addAction('Use Skill', 'click', {
  skill_id: 'fireball',
});

Start an Action whose associated lifecycle is managed by the Native SDK:

truewatchSdk.rum.startAction('Matchmaking', 'custom', {
  queue: 'ranked',
});

Method signatures:

truewatchSdk.rum.addAction(
  name: string,
  type?: string,
  attributes?: FTAttributes,
): void

truewatchSdk.rum.startAction(
  name: string,
  type?: string,
  attributes?: FTAttributes,
): void

name and type cannot be empty; the default value of type is click.

When autoTrack.actions is enabled, global touch-end events automatically generate Actions. Do not call the manual Action API for the same touch.

View

Start a View:

truewatchSdk.rum.startView('Battle', {
  map_id: 'map-001',
});

Stop the current View:

truewatchSdk.rum.stopView({
  battle_result: 'victory',
});

Method signatures:

truewatchSdk.rum.startView(name: string, attributes?: FTAttributes): void
truewatchSdk.rum.stopView(attributes?: FTAttributes): void

name cannot be empty. The application should ensure Views are stopped in pairs; stop the previous View before starting a new one.

When autoTrack.scenes is enabled, the SDK automatically manages scene Views. Do not call the View API manually for the same scene, to avoid duplicate or nested errors.

Error

try {
  startBattle();
} catch (error) {
  const exception = error instanceof Error
    ? error
    : new Error(String(error));

  truewatchSdk.rum.addError(
    exception.message,
    exception.stack || '',
    'game_logic_error',
    'run',
    {
      scene: 'Battle',
    },
  );
}

Method signatures:

truewatchSdk.rum.addError(
  message: string,
  stack: string,
  type?: string,
  state?: 'run' | 'startup' | 'unknown',
  attributes?: FTAttributes,
): void
Parameter Default Description
message None Error message
stack None Error stack
type cocos_error Business error type
state run Phase during which the error occurred: running, startup, or unknown
attributes None Attributes attached to the current error

When autoTrack.errors is enabled, uncaught JavaScript Errors and Promise rejections are reported automatically. Exceptions caught and manually reported by business code are not captured again by the global listeners.

LongTask

truewatchSdk.rum.addLongTask(
  'GenerateWorld',
  850 * 1_000_000,
  {
    map_size: 'large',
  },
);

Method signatures:

truewatchSdk.rum.addLongTask(
  stack: string,
  durationNs: number,
  attributes?: FTAttributes,
): void

durationNs is in nanoseconds. The Cocos JavaScript layer does not currently recognize LongTasks automatically; the business code needs to call this method after a known time-consuming task ends.

Resource

A complete Resource consists of three phases:

  1. startResource(): starts timing;
  2. stopResource(): stops timing;
  3. addResource(): adds request content and optional performance metrics.
export async function requestMatch(): Promise<void> {
  const key = `match-${Date.now()}`;
  const url = 'https://api.example.com/match';
  const started = Date.now() * 1_000_000;

  truewatchSdk.rum.startResource(key, {
    request_source: 'matchmaking',
  });

  try {
    const traceHeaders = truewatchSdk.trace.getHeaders(url, key);
    const response = await fetch(url, {
      headers: traceHeaders,
    });
    const ended = Date.now() * 1_000_000;

    truewatchSdk.rum.stopResource(key);
    truewatchSdk.rum.addResource(
      key,
      {
        url,
        httpMethod: 'GET',
        requestHeaders: traceHeaders,
        statusCode: response.status,
        responseContentType: response.headers.get('content-type') || undefined,
      },
      {
        fetchStartTime: started,
        responseStartTime: ended,
        responseEndTime: ended,
      },
    );
  } catch (error) {
    truewatchSdk.rum.stopResource(key);
    const exception = error instanceof Error
      ? error
      : new Error(String(error));
    truewatchSdk.rum.addError(
      exception.message,
      exception.stack || '',
      'network_error',
    );
  }
}

Method signatures:

truewatchSdk.rum.startResource(
  key: string,
  attributes?: FTAttributes,
): void

truewatchSdk.rum.stopResource(
  key: string,
  attributes?: FTAttributes,
): void

truewatchSdk.rum.addResource(
  key: string,
  content: FTResourceContent,
  metrics?: FTResourceMetrics,
): void

Resource Content

Field Type Required Description
url string Yes Complete request URL
httpMethod string Yes HTTP method
requestHeaders Record<string, string> No Request headers
responseHeaders Record<string, string> No Response headers
responseBody string No Response body; may contain sensitive data, collect with caution
statusCode number No HTTP status code
responseContentType string No Response Content-Type
responseContentEncoding string No Response Content-Encoding

Resource Performance Metrics

All time fields are in nanoseconds:

Field Description
fetchStartTime Request start time
tcpStartTime TCP connection start time
tcpEndTime TCP connection end time
dnsStartTime DNS resolution start time
dnsEndTime DNS resolution end time
responseStartTime Response start time
responseEndTime Response end time
sslStartTime TLS connection start time
sslEndTime TLS connection end time

key must be identical in the three RUM methods and truewatchSdk.trace.getHeaders().

Choose either automatic or manual collection

When autoTrack.network is enabled, fetch and XMLHttpRequest are already collected automatically. Do not run the manual Resource flow above for the same request.

Upload Behavior

The current Cocos API does not expose a manual Flush. After events are written to the Native SDK, they are sent by the Native SDK according to its cache and upload policies. Do not rely on truewatchSdk.shutdown() to force upload before the application closes.

Cocos and Native Data Boundary

  • scenes, actions, errors, and network collect behaviors at the Cocos JavaScript layer.
  • The enableNative* options collect behaviors at the Android/iOS native container layer.
  • Native Crash, ANR, UI Block, and device metrics are generated by the underlying Android/iOS SDK.
  • Cocos Long Tasks are not currently collected automatically; call the manual API instead.
  • Automatic network collection only covers the fetch and XMLHttpRequest actually provided by the current runtime.

When the native app uses Cocos on only some pages, complete initialization according to the native SDK requirements, and use enterCocos() and leaveCocos() to switch the View lifecycle while the Cocos page is visible. For the complete configuration, see Native and Cocos Hybrid Development.

Sampling Notes

sampleRate and sessionOnErrorSampleRate must be finite numbers within 0–1. When out of range, the TypeScript layer throws a RangeError during initialization. When not provided, the default values of the corresponding Native SDK are used.