RUM Configuration¶
RUM Initialization Configuration¶
await FTRUMManager().setConfig(
androidAppId: appAndroidId,
iOSAppId: appIOSId,
sessionSamplingRate: 100.0,
);
| Field | Type | Required | Description |
|---|---|---|---|
| androidAppId | String | Required for Android | The Android platform app_id, applied for in the Application Access Monitoring console; read only at Android runtime |
| iOSAppId | String | Required for iOS | The iOS platform app_id, applied for in the Application Access Monitoring console; read only at iOS runtime |
| sessionSamplingRate | double | No | RUM session sampling rate, range [0,100], decimals supported, default 100. 0.1 means 0.1%, 1 means 1%. Applies to RUM data under the same Session. Supported since SDK 0.5.8. |
| sampleRate | double | No | Legacy probability configuration, retained for compatibility. RUM session sampling rate, range [0,1], default 1. 0.1 means 10%, 1 means 100%. We recommend using sessionSamplingRate instead. |
| sessionOnErrorSamplingRate | double | No | Error supplementary sampling percentage when normal session sampling is not hit, range [0,100], decimals supported, default 0. When an error occurs, RUM data from the 1 minute before the error can be supplementarily sampled, applying to the same Session. Supported since SDK 0.5.8. |
| sessionOnErrorSampleRate | double | No | Legacy probability configuration, retained for compatibility. Error supplementary sampling probability, range [0,1], default 0. We recommend using sessionOnErrorSamplingRate instead. |
| enableUserResource | bool | No | Whether to enable automatic capture of Flutter http Resource, default false. Implemented by modifying HttpOverrides.global; if your project has customization requirements, you need to inherit FTHttpOverrides |
| enableWebSocketResource | bool | No | Whether to collect Dart WebSocket connection handshakes, default false; enableUserResource must be enabled at the same time. Only handshakes are collected, not message frames or connection duration. Supported since SDK 0.5.8; see WebSocket Handshake Collection |
| enableNativeUserAction | bool | No | Whether to automatically track native-side Action, including Android/iOS native control taps and app launch events, default false. On Android, ft-plugin must be configured; collecting launch events also requires a custom Application |
| enableNativeUserView | bool | No | Whether to automatically collect native pages: Activity on Android and UIViewController on iOS, default false |
| enableNativeUserViewLoadingTime | bool | No | Switch for automatic loading time collection of iOS native UIKit / SwiftUI Views, default true, requires enableNativeUserView; disabling it does not affect View tracking. Ignored on Android and does not affect Flutter route duration. Supported since SDK 0.5.8; see iOS Native View Loading Time |
| nativeViewLoadingTimeClassNameExcludes | List<String> |
No | iOS native View loading time exclusion list, empty by default; matched exactly and case-sensitively by the controller's full runtime class name. Ignored on Android. Supported since SDK 0.5.8 |
| launchPrewarmInterval | int | No | iOS launch prewarm duration inference threshold in milliseconds, default 0, which means duration inference is disabled; a positive value sets the threshold; negative values and values greater than 9223372036854 are ignored by the native SDK. Requires enableNativeUserAction; ignored on Android. Supported since SDK 0.5.8; see iOS Launch Prewarm |
| enableNativeSwiftUIUserView | bool | No | iOS: whether to enable automatic tracking of native SwiftUI Views. Requires enableNativeUserView to be enabled at the same time |
| enableNativeUserViewInFragment | bool | No | Whether to automatically collect Android Fragment pages, requires ft-plugin configuration, default false, Android only |
| enableNativeUserResource | bool | No | Whether to enable automatic collection of native network Resources; Android automatically collects OkHttp requests, iOS automatically collects native network requests, default false. Since SDK 0.5.8, WebSocket connection handshakes monitorable by the native SDK are also supported; this parameter does not collect Dart WebSocket. This parameter and enableUserResource, which collects Flutter HttpClient requests, are two independent capabilities |
| enableNativeAppUIBlock | bool | No | Whether to enable automatic detection of native main thread blocks (UI Block/Freeze), default false |
| nativeUiBlockDurationMS | int | No | Native main thread block detection threshold in milliseconds, effective only when enableNativeAppUIBlock is enabled, value range [100, ). Default 250 ms on iOS and 1000 ms on Android |
| enableLongTask | bool | No | Whether to enable automatic detection of long tasks on the 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 detects that the app remains unresponsive, which differs from the single main thread block collected by enableNativeAppUIBlock; iOS detects unresponsiveness through the 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 the monitoring type can be configured via iosCrashMonitoringType |
| errorMonitorType | int | No | Sets auxiliary monitoring information attached to RUM Error data, supports ErrorMonitorType.battery, memory, cpu, all; pass the corresponding .value when calling, e.g. ErrorMonitorType.all.value, disabled by default |
| deviceMetricsMonitorType | int | No | Sets 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, disabled by default |
| detectFrequency | enum DetectFrequency | No | View performance monitoring sampling interval: DetectFrequency.normal is 500 ms, frequent is 100 ms, rare is 1000 ms, default normal; meaningful only when deviceMetricsMonitorType is configured |
| globalContext | Map | No | Custom global parameters. For adding rules, see Conflicting Fields |
| rumCacheDiscard | enum | No | Discard policy: 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. Returning true filters out (does not collect), returning false collects. For usage, see Custom Data Collection Rules |
| enableTraceWebView | bool | No | Whether to enable collecting WebView data through the native SDK, supporting Android/iOS, default true |
| allowWebViewHost | List<String> |
No | Compatible with legacy RUM Host configuration. Since SDK 0.5.8, it is recommended to set it uniformly in FTMobileFlutter.sdkConfig(allowWebViewHost: ...) so that RUM and Log share it; remote configuration takes precedence over the basic configuration, and the basic configuration takes precedence over this entry |
| enableResourceHostIP | bool | No | Whether to collect the Host IP of native Resource requests, default false. Only affects the native network auto collection of enableNativeUserResource and does not apply to Flutter HttpClient Resource collected by enableUserResource; iOS requires 13 or later |
| iosCrashMonitoringType | enum IOSCrashMonitoringType | No | iOS crash monitoring type, effective only on iOS, requires enableTrackNativeCrash. Options: machException, signal, cppException, nsException, system, applicationState, all, highCompatibility, default IOSCrashMonitoringType.highCompatibility |
Percentage Sampling Configuration¶
Supported since SDK 0.5.8.
Sampling rate parameter naming
Since SDK 0.5.8, sessionSamplingRate and sessionOnErrorSamplingRate are recommended; their values are percentages in 0~100, decimals supported; 0 means no sampling, 100 means full sampling. Invalid values such as out-of-range, NaN, or infinity throw an ArgumentError.
The legacy sampleRate and sessionOnErrorSampleRate remain for compatibility, with values as probabilities in 0~1. For example, 0.1 in the legacy fields means 10%, while 0.1 in the new fields means 0.1%. When both the new and legacy fields are set for the same item, the new percentage field takes precedence, including an explicit 0.
For the units and precedence of remote sampling fields, see Flutter Remote Configuration Fields.
For example, to migrate 12.5% RUM sampling:
await FTRUMManager().setConfig(
androidAppId: appAndroidId,
iOSAppId: appIOSId,
- sampleRate: 0.125,
- sessionOnErrorSampleRate: 0.0,
+ sessionSamplingRate: 12.5,
+ sessionOnErrorSamplingRate: 0.0,
);
Log, Trace, and Session Replay also provide corresponding percentage parameters.
iOS Native View Loading Time¶
Supported since SDK 0.5.8.
Configure it on the first call to FTRUMManager().setConfig(). enableNativeUserViewLoadingTime only controls automatic loading time collection for native UIKit / SwiftUI Views and requires enableNativeUserView to be enabled at the same time; native SwiftUI Views also require enableNativeSwiftUIUserView. These configurations do not calculate the loading time of Flutter routes; Flutter pages can report it themselves using Update Current View Loading Time.
await FTRUMManager().setConfig(
androidAppId: appAndroidId,
iOSAppId: appIOSId,
enableNativeUserView: true,
enableNativeUserViewLoadingTime: true,
nativeViewLoadingTimeClassNameExcludes: [
'MyApp.ContainerViewController',
],
);
If the two loading time parameters are not passed, the native default values are used: collection enabled and the exclusion list empty. The exclusion list uses the controller's full runtime class name; Swift class names usually include the module name prefix; matching is exact and case-sensitive, and does not match parent classes, regular expressions, or custom view_name. Globally disabling or excluding loading time collection for a controller does not disable View tracking for that page. Android ignores these two parameters.
iOS Launch Prewarm¶
Supported since SDK 0.5.8.
launchPrewarmInterval sets the duration inference threshold for iOS native launch prewarm, in milliseconds, and requires native automatic Action collection to be enabled. Set it during RUM initialization, for example:
await FTRUMManager().setConfig(
androidAppId: appAndroidId,
iOSAppId: appIOSId,
enableNativeUserAction: true,
launchPrewarmInterval: 1500,
);
If it is not passed or passed as 0, duration inference is disabled, but the native SDK's handling of the system prewarm flag is retained. A positive value sets the inference threshold; a longer duration does not necessarily mean the system has performed prewarm; negative values and values greater than 9223372036854 are ignored by the native SDK. Android ignores this parameter. The two early prewarm detection methods still need to be called at the iOS native launch entry point; Flutter does not provide corresponding Dart methods; see iOS Launch Prewarm Configuration.
RUM User Data Tracking¶
Action¶
Difference between startAction and addAction usage
startActionautomatically calculates the Action duration internally; during calculation it associates as much as possible with nearbyResource,LongTask, andErrordata, and has a 100 ms frequent-trigger protection; recommended for user operation type data.- If you need to call it frequently, use
addAction. Actions reported viaaddActiondo not conflict withstartActionand are not associated with currentResource,LongTask, orErrordata.
Usage¶
/// Add an action
/// [actionName] action name
/// [actionType] action type
/// [property] additional property parameters (optional)
Future<void> startAction(String actionName, String actionType,
{Map<String, Object?>? property})
/// Add actions at high frequency, without associating with current Resource, LongTask, or 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¶
Auto Collection¶
After adding FTRouteObserver to MaterialApp.navigatorObservers, the SDK can automatically collect Flutter page switches. The page name (view_name) can be configured in the following ways.
Method 1: Collect via routes¶
Set the pages to navigate to 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: Collect via FTMaterialPageRoute¶
The page name is resolved from the widget's runtimeType through a 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 an example, see here.
Method 3: Collect via RouteSettings.name¶
Customize RouteSettings.name in a Route type page; FTRouteObserver obtains this value first. This method also applies 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 three methods above can be mixed within one project.
Sleep and Wake Event Collection¶
Before version 0.5.1-pre.1, if you need to collect app sleep and wake behavior, add the following code:
class _HomeState extends State<HomeRoute> {
@override
void initState() {
FTLifeRecycleHandler().initObserver();
}
@override
void dispose() {
FTLifeRecycleHandler().removeObserver();
}
}
For auto collection filter rules, see Custom Data Collection Rules.
Custom View¶
Usage¶
/// Create a view; this method needs to be called before [starView]
/// [viewName] view name
/// [duration] page loading duration
Future<void> createView(String viewName, int duration)
/// Start a view
/// [viewName] view name
/// [viewReferer] previous view name
/// [property] additional property parameters (optional)
Future<void> starView(String viewName, {Map<String, String>? property})
/// Stop a 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 rules on automatic page collection, route filtering, and sleep/wake listening, see Custom Data Collection Rules.
Update Current View Loading Time¶
Supported since SDK 0.5.8.
Call FTRUMManager().updateViewLoadingTime(int duration) when the current View has started and has not yet ended; it returns Future<void>. duration is the page loading duration measured by your business logic, in nanoseconds, and must be greater than or equal to 0; a negative value throws an ArgumentError. The SDK does not use this method to automatically determine when business loading is complete.
final loadingWatch = Stopwatch()..start();
await FTRUMManager().starView('ProductDetail');
// Wait for the business data or content required by the current page to finish loading
await loadProductDetail();
loadingWatch.stop();
await FTRUMManager().updateViewLoadingTime(
loadingWatch.elapsedMicroseconds * 1000,
);
// Stop the current View when leaving the page
await FTRUMManager().stopView();
Flutter auto route collection records page dwell time and does not automatically measure business loading duration. When using auto route collection, make sure the View corresponding to the current route has started before updating, and do not call starView repeatedly for the same page. The existing createView can still be used before a manual starView, and its duration is also in nanoseconds.
Error¶
Auto Collection¶
void main() async {
runZonedGuarded(() async {
WidgetsFlutterBinding.ensureInitialized();
await FTMobileFlutter.sdkConfig(
datakitUrl: serverUrl,
debug: true,
);
await FTRUMManager().setConfig(
androidAppId: appAndroidId,
iOSAppId: appIOSId,
);
// Flutter exception capture
FlutterError.onError = FTRUMManager().addFlutterError;
runApp(MyApp());
}, (Object error, StackTrace stack) {
// Add Error data
FTRUMManager().addError(error, stack);
});
}
Custom Error¶
Usage¶
/// Add a 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¶
LongTask¶
Auto Collection¶
After enabling enableLongTask via FTRUMManager().setConfig, the SDK detects whether blocking tasks exceeding the threshold occur on the Flutter Dart main Isolate and generates LongTask data. The default threshold is 0.1 seconds and can be adjusted via dartLongTaskThreshold.
await FTRUMManager().setConfig(
androidAppId: appAndroidId,
iOSAppId: appIOSId,
enableLongTask: true,
dartLongTaskThreshold: 0.1,
);
Custom LongTask¶
Usage¶
/// Report a LongTask; duration is 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"},
);
Automatically detected LongTasks are used to identify event loop latency on the Dart main Isolate. What is collected is the blocking duration, which does not guarantee that the business code stack causing the block can be obtained.
Resource¶
Auto Collection¶
Enable it via FTRUMManager().setConfig with enableUserResource.
WebSocket Handshake Collection¶
Supported since SDK 0.5.8.
await FTRUMManager().setConfig(
androidAppId: appAndroidId,
iOSAppId: appIOSId,
enableUserResource: true,
enableWebSocketResource: true,
);
final socket = await FTWebSocket.connect('wss://example.com/socket');
FTWebSocket can be imported from package:ft_mobile_agent_flutter/ft_mobile_agent_flutter.dart. connect returns Future<WebSocket>, and its parameters correspond to Dart WebSocket.connect: the required String url, plus optional Iterable<String>? protocols, Map<String, dynamic>? headers, CompressionOptions compression (default CompressionOptions.compressionDefault), and HttpClient? customClient.
For automatic collection of the standard WebSocket.connect, the above configuration must be enabled before the first connection; when using a self-created HttpClient, make sure requests go through SDK collection. If you need to cover handshake failure scenarios such as subprotocol or compression validation, use FTWebSocket.connect. The SDK only collects connection handshake results, not subsequent message frames, message content, or connection duration; URL filtering still follows isInTakeUrl.
Custom Resource¶
Usage¶
/// Start a resource request
/// [key] unique id
/// [property] additional property parameters (optional)
Future<void> startResource(String key, {Map<String, String>? property})
/// Stop a 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,
bool webSocketHandshake = false,
String? webSocketHandshakeState,
String? errorMessage,
String? errorStack,
bool forceNetworkError = false,
FTRUMResourceMetrics? metrics,
})
| Field | Type | Description |
|---|---|---|
| resourceSize | int | Response body size, in bytes |
| resourceType | String | Resource type, e.g. native, image, media, font, css, js |
| webSocketHandshake | bool | Whether this is a WebSocket connection handshake, default false. Supported since SDK 0.5.8 |
| webSocketHandshakeState | String | Handshake result: success, rejected, or failed; used together with webSocketHandshake: true. Supported since SDK 0.5.8 |
| errorMessage | String | Resource error description. Supported since SDK 0.5.8 |
| errorStack | String | Resource error stack. Supported since SDK 0.5.8 |
| forceNetworkError | bool | Whether to report as a network error, default false. Supported since SDK 0.5.8 |
| 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
enableUserResourceauto collection is enabled, the SDK automatically supplements fields such asresourceType,requestSize,resourceHttpProtocol, andreusedConnectionbased on the request method, response headers, and connection state.
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 usage of the
httpanddiolibraries, see example.