Skip to content

RUM Configuration

RUM Initialization Configuration

await FTRUMManager().setConfig(
  androidAppId: appAndroidId,
  iOSAppId: appIOSId,
);
Field Type Required Description
androidAppId String Required for Android app_id for Android platform, apply in the RUM console; only read on Android runtime
iOSAppId String Required for iOS app_id for iOS platform, apply in the RUM console; only read on iOS runtime
sampleRate double No Sampling rate, range [0,1], 0 means no collection, 1 means full collection, default value is 1. Scope is all View, Action, LongTask, Error data under the same session_id
sessionOnErrorSampleRate double No Error collection rate. When a session is not sampled by sampleRate, if an error occurs during the session, data within 1 minute before the error can be collected, range [0,1], default value is 0
enableUserResource bool No Whether to enable automatic capture of Flutter http Resource, default false. Implemented by modifying HttpOverrides.global, if the project has custom requirements, it needs to inherit FTHttpOverrides
enableNativeUserAction bool No Whether to automatically track native-side Action, including Android/iOS native control clicks and app launch events, default false. Android side needs to configure ft-plugin, to collect launch events also need to customize Application
enableNativeUserView bool No Whether to automatically collect native pages, Android collects Activity, iOS collects UIViewController, default false
enableNativeSwiftUIUserView bool No iOS: whether to enable automatic tracking of native SwiftUI View. Requires enableNativeUserView to be enabled simultaneously
enableNativeUserViewInFragment bool No Whether to automatically collect Android Fragment pages, requires ft-plugin configuration, default false, only supported on Android
enableNativeUserResource bool No Whether to enable automatic collection of native network Resource, Android automatically collects OkHttp requests, iOS automatically collects native network requests, default false. This parameter is independent from enableUserResource which collects Flutter HttpClient requests
enableNativeAppUIBlock bool No Whether to enable automatic detection of native main thread stutter (UI Block/Freeze), default false
nativeUiBlockDurationMS int No Native main thread stutter detection threshold, in milliseconds, only takes effect when enableNativeAppUIBlock is enabled, range [100, ). iOS default is 250ms, Android default is 1000ms
enableLongTask bool No Whether to enable automatic detection of long tasks on Flutter Dart main Isolate, default false
dartLongTaskThreshold double No Flutter Dart long task detection threshold, in seconds, default 0.1
enableTrackNativeAppANR bool No Whether to enable native ANR monitoring, default false. ANR is used to detect continuous unresponsiveness of the application, different from single main thread stutter collected by enableNativeAppUIBlock; iOS detects unresponsiveness through main thread RunLoop
enableTrackNativeCrash bool No Whether to enable native crash monitoring, default false. Android collects Java Crash and Native C/C++ Crash; iOS collects Crash, and can configure monitoring type through iosCrashMonitoringType
errorMonitorType int No Set additional monitoring information attached to RUM Error data, supports ErrorMonitorType.battery, memory, cpu, all, pass the corresponding .value when calling, e.g., ErrorMonitorType.all.value, default is not enabled
deviceMetricsMonitorType int No Set performance monitoring information attached to RUM View data, supports DeviceMetricsMonitorType.battery, memory, cpu, fps, all, pass the corresponding .value when calling, e.g., DeviceMetricsMonitorType.all.value, default is not enabled
detectFrequency enum DetectFrequency No View performance monitoring sampling period: DetectFrequency.normal is 500ms, frequent is 100ms, rare is 1000ms, default normal; only meaningful when deviceMetricsMonitorType is configured
globalContext Map No Custom global parameters. For addition rules, refer to Conflict Field Description
rumCacheDiscard enum No Discard strategy: FTRUMCacheDiscard.discard discards new data (default), FTRUMCacheDiscard.discardOldest discards old data
rumCacheLimitCount int No Local cache maximum RUM entry count limit [10_000, ), default 100_000
isInTakeUrl bool Function(String url) No Flutter http Resource URL filter callback. Return true means filter out, not collect; return false means collect. For usage, refer to Data Collection Custom Rules
enableTraceWebView bool No Whether to enable WebView data collection through native SDK, supports Android/iOS, default true
allowWebViewHost List No Configure the list of Hosts allowed for WebView data collection, needs to be used with enableTraceWebView, supports Android/iOS; if not set or null, all Hosts are allowed to be collected
enableResourceHostIP bool No Whether to collect the Host IP of native Resource requests, default false. Only affects native network automatic collection of enableNativeUserResource, does not affect Flutter HttpClient Resource collected by enableUserResource; iOS requires 13 or higher
iosCrashMonitoringType enum IOSCrashMonitoringType No iOS crash monitoring type, only effective on iOS, requires enableTrackNativeCrash to be enabled. Options: machException, signal, cppException, nsException, system, applicationState, all, highCompatibility, default IOSCrashMonitoringType.highCompatibility

RUM User Data Tracking

Action

Usage

/// Add action
/// [actionName] action name
/// [actionType] action type
/// [property] additional property parameters (optional)
Future<void> startAction(String actionName, String actionType,
  {Map<String, Object?>? property})

/// High-frequency add action, not associated with current Resource, LongTask, Error events
Future<void> addAction(String actionName, String actionType,
  {Map<String, Object?>? property})

Code Example

FTRUMManager().startAction("action name", "action type");

FTRUMManager().addAction("action name", "action type");

View

Automatic Collection

After adding FTRouteObserver to MaterialApp.navigatorObservers, the SDK can automatically collect Flutter page transitions. The page name (view_name) can be configured through the following methods.

Method 1: Collection via routes

Set the pages to navigate in MaterialApp.routes, the key in routes is the page name (view_name).

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomeRoute(),
      navigatorObservers: [
        FTRouteObserver(),
      ],
      routes: <String, WidgetBuilder>{
        'logging': (BuildContext context) => Logging(),
        'rum': (BuildContext context) => RUM(),
        'tracing_custom': (BuildContext context) => CustomTracing(),
        'tracing_auto': (BuildContext context) => AutoTracing(),
      },
    );
  }
}

Navigator.pushNamed(context, "logging");
Method 2: Collection via FTMaterialPageRoute

Parse the page name from the runtimeType of the widget through custom FTMaterialPageRoute, where the widget class name is the page name (view_name).

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomeRoute(),
      navigatorObservers: [
        FTRouteObserver(),
      ],
    );
  }
}

Navigator.of(context).push(
  FTMaterialPageRoute(builder: (context) => new NoRouteNamePage()),
);

For examples, refer to here.

Method 3: Collection via RouteSettings.name

Customize RouteSettings.name in Route type pages, FTRouteObserver will prioritize this value. This method is also applicable to Dialog type pages, such as showDialog(), showTimePicker(), etc.

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomeRoute(),
      navigatorObservers: [
        FTRouteObserver(),
      ],
    );
  }
}

Navigator.of(context).push(
  MaterialPageRoute(
    builder: (context) => new NoRouteNamePage(),
    settings: RouteSettings(name: "RouteSettingName"),
  ),
);

The above three methods can be mixed in one project.

Sleep and Wakeup Event Collection

For versions below 0.5.1-pre.1, if you need to collect app sleep and wakeup behavior, add the following code:

class _HomeState extends State<HomeRoute> {
  @override
  void initState() {
    FTLifeRecycleHandler().initObserver();
  }

  @override
  void dispose() {
    FTLifeRecycleHandler().removeObserver();
  }
}

For automatic collection filter rules, refer to Data Collection Custom Rules.

Custom View

Usage
/// Create view, this method should be called before [starView]
/// [viewName] view name
/// [duration] page load duration
Future<void> createView(String viewName, int duration)

/// Start view
/// [viewName] view name
/// [viewReferer] previous view name
/// [property] additional property parameters (optional)
Future<void> starView(String viewName, {Map<String, String>? property})

/// Stop view
/// [property] additional property parameters (optional)
Future<void> stopView({Map<String, String>? property})
Code Example
FTRUMManager().createView("Current Page Name", 100000000);

FTRUMManager().starView("Current Page Name");

FTRUMManager().stopView();

For automatic page collection, route filtering, sleep/wakeup monitoring rules, etc., refer to Data Collection Custom Rules.

Error

Automatic Collection

void main() async {
  runZonedGuarded(() async {
    WidgetsFlutterBinding.ensureInitialized();
    await FTMobileFlutter.sdkConfig(
      datakitUrl: serverUrl,
      debug: true,
    );
    await FTRUMManager().setConfig(
      androidAppId: appAndroidId,
      iOSAppId: appIOSId,
    );

    // Flutter error capture
    FlutterError.onError = FTRUMManager().addFlutterError;
    runApp(MyApp());
  }, (Object error, StackTrace stack) {
    // Add Error data
    FTRUMManager().addError(error, stack);
  });
}

Custom Error

Usage
/// Add custom error
/// [stack] stack trace
/// [message] error message
/// [appState] app state
/// [errorType] custom errorType
/// [property] additional property parameters (optional)
Future<void> addCustomError(String stack, String message,
  {Map<String, String>? property, String? errorType})
Code Example
FTRUMManager().addCustomError("error stack", "error message");

LongTask

Automatic Collection

After enabling enableLongTask via FTRUMManager().setConfig, the SDK will detect if there are blocking tasks on the Flutter Dart main Isolate that exceed the threshold, and generate LongTask data. The default threshold is 0.1 seconds, adjustable via dartLongTaskThreshold.

await FTRUMManager().setConfig(
  androidAppId: appAndroidId,
  iOSAppId: appIOSId,
  enableLongTask: true,
  dartLongTaskThreshold: 0.1,
);

Custom LongTask

Usage
/// Report LongTask, duration in nanoseconds
Future<void> addLongTask(String stack, int duration,
  {Map<String, String>? property})
Code Example
FTRUMManager().addLongTask(
  "flutter_manual_long_task",
  250000000,
  property: {"long_task_source": "manual_report"},
);

The automatically detected LongTask is used to identify delays in the Dart main Isolate event loop. What is collected is the blocking duration, which does not necessarily represent the ability to obtain the business code stack that caused the blocking.

Resource

Automatic Collection

Achieved by enabling enableUserResource via FTRUMManager().setConfig.

Custom Resource

Usage
/// Start resource request
/// [key] unique id
/// [property] additional property parameters (optional)
Future<void> startResource(String key, {Map<String, String>? property})

/// Stop resource request
/// [key] unique id
/// [property] additional property parameters (optional)
Future<void> stopResource(String key, {Map<String, String>? property})

/// Send resource data metrics
Future<void> addResource({
  required String key,
  required String url,
  required String httpMethod,
  required Map<String, dynamic> requestHeader,
  Map<String, dynamic>? responseHeader,
  String? responseBody = "",
  int? resourceStatus,
  int? resourceSize,
  String? resourceType,
  FTRUMResourceMetrics? metrics,
})
Field Type Description
resourceSize int Response body size, in bytes
resourceType String Resource type, e.g., native, image, media, font, css, js
metrics.requestSize num Request size, including request headers and body, in bytes
metrics.resourceHttpProtocol String HTTP protocol used by the Resource, e.g., http/1.1
metrics.reusedConnection bool Whether the connection is reused

When automatic collection via enableUserResource is enabled, the SDK will automatically supplement fields such as resourceType, requestSize, resourceHttpProtocol, reusedConnection based on the request method, response headers, and connection status.

Code Example
void httpClientGetHttp(String url) async {
  var httpClient = HttpClient();
  String key = Uuid().v4();
  HttpClientResponse? response;
  HttpClientRequest? request;
  try {
    request = await httpClient
        .getUrl(Uri.parse(url))
        .timeout(Duration(seconds: 10));
    FTRUMManager().startResource(key);
    response = await request.close();
  } finally {
    Map<String, dynamic> requestHeader = {};
    Map<String, dynamic> responseHeader = {};

    request!.headers.forEach((name, values) {
      requestHeader[name] = values;
    });
    var responseBody = "";
    if (response != null) {
      response.headers.forEach((name, values) {
        responseHeader[name] = values;
      });
      responseBody = await response.transform(Utf8Decoder()).join();
    }
    FTRUMManager().stopResource(key);
    FTRUMManager().addResource(
      key: key,
      url: request.uri.toString(),
      requestHeader: requestHeader,
      httpMethod: request.method,
      responseHeader: responseHeader,
      resourceStatus: response?.statusCode,
      responseBody: responseBody,
    );
  }
}

For using the http library and dio library, refer to example.