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 sdk base configuration (for example, datakitUrl) is omitted. Complete the generic configuration following SDK Initialization first; this page only covers 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 on Android Android RUM application ID
iosAppId string Required on iOS iOS RUM application ID
sampleRate number No Session sample rate, range 0–1
sessionOnErrorSampleRate number No Sampling rate for error sessions not selected by the regular sample rate, range 0–1
enableNativeUserAction boolean No Whether to collect Native UI Actions
enableNativeUserView boolean No Whether to collect Native page 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 ANRs
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 device metrics monitoring items attached to Views
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 pass both values at the same time.

errorMonitorType and deviceMetricsMonitorType pass through numeric bitmasks directly and must match the definitions in the current Native SDK version. For specific combinations, see 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 When a scene starts, close the previous View and start a new View named after the scene RUM
actions Convert the global TOUCH_END event into an Action; prefer the event target node name and attach touch coordinates RUM
errors Listen for uncaught JavaScript Errors and Promise rejections RUM; the runtime must also provide both globalThis.addEventListener and globalThis.removeEventListener
console Wrap console.log/info/warn/error and convert them into custom logs Log; see Log Configuration
network Wrap fetch and XMLHttpRequest to collect Resources and inject 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; 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. Based on the actual request stack, choose either the Cocos layer or the Native layer for automatic collection, and check the test environment for duplicate data.

Manual RUM Instrumentation

When automatic collection cannot cover scenarios such as custom pages, business operations, caught exceptions, and custom network stacks, report data manually through truewatchSdk.rum. In standalone mode, initialize rum in truewatchSdk.start() first; 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

Differences Between startAction and addAction
  • startAction automatically calculates the Action duration internally. During the calculation, it associates with nearby Resource, LongTask, and Error data as much as possible, and has 100 ms protection against frequent triggering. It is recommended for user action data.
  • If you need to call it frequently, use addAction. Actions reported through addAction do not conflict with startAction and are not associated with the current Resource, LongTask, or Error data.

Add an instant 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, and 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 APIs 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 old View before starting a new one.

When autoTrack.scenes is enabled, the SDK automatically manages scene Views. Do not call the View APIs 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 Value Description
message None Error message
stack None Error stack trace
type cocos_error Business error type
state run Stage of occurrence: running, startup, or unknown
attributes None Additional attributes attached to the current error

When autoTrack.errors is enabled, uncaught JavaScript Errors and Promise rejections are reported automatically. Exceptions already caught and reported manually 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; business code must call this API after a known long-running task completes.

Resource

A complete Resource consists of three phases:

  1. startResource(): start timing;
  2. stopResource(): stop timing;
  3. addResource(): add the 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 The full 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 consistent across the three RUM methods and truewatchSdk.trace.getHeaders().

Choose Automatic or Manual Collection

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

Upload Behavior

The current Cocos API does not expose manual Flush. After events are written to the Native SDK, the Native SDK sends them based on its own caching and upload strategies. Do not rely on truewatchSdk.shutdown() to force an upload before the application closes.

Cocos and Native Data Boundaries

  • scenes, actions, errors, and network collect behavior at the Cocos JavaScript layer.
  • The enableNative* options collect behavior from the Android/iOS native containers.
  • Native Crashes, ANRs, UI Blocks, and device metrics are generated by the underlying Android/iOS SDK.
  • Cocos Long Tasks are not collected automatically; use the manual APIs.
  • Automatic network collection only covers the fetch and XMLHttpRequest actually provided by the current runtime.

When a native App uses Cocos only on some pages, complete initialization as required by the native SDK, and use enterCocos() and leaveCocos() to switch the View lifecycle while Cocos pages are visible. For the complete configuration, see Native and Cocos Hybrid Development.

Sampling

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