Custom Data Collection Rules¶
View¶
Activity¶
- Must first be enabled via
FTRUMConfig.setEnableTraceUserView(true)
FTSdk.initRUMWithConfig(new FTRUMConfig()
.setViewActivityTrackingHandler(new FTViewActivityTrackingHandler() {
@Override
public HandlerView resolveHandlerView(Activity activity) {
String activityName = activity.getClass().getSimpleName();
// Customize the view name based on the Activity name
if (activityName.startsWith("Main")) {
return new HandlerView("自定义主页面");
} else if (activityName.startsWith("Detail")) {
HashMap<String, Object> properties = new HashMap<>();
properties.put("extra_key", "extra_value");
return new HandlerView("自定义详情页面", properties);
}
// Return null to skip tracking
return null;
}
})
);
FTSdk.initRUMWithConfig(
FTRUMConfig()
.setViewActivityTrackingHandler(object : FTViewActivityTrackingHandler {
override fun resolveHandlerView(activity: Activity): HandlerView? {
val activityName = activity.javaClass.simpleName
return when {
activityName.startsWith("Main") ->
HandlerView("自定义主页面")
activityName.startsWith("Detail") -> {
val properties = hashMapOf<String, Any>("extra_key" to "extra_value")
HandlerView("自定义详情页面", properties)
}
else -> null // Skip tracking
}
}
})
)
Fragment¶
- Both
FTRUMConfig.setEnableTraceUserView(true)andFTRUMConfig.setEnableTraceUserViewInFragment(true)must be enabled
FTSdk.initRUMWithConfig(new FTRUMConfig()
.setViewFragmentTrackingHandler(new FTViewFragmentTrackingHandler() {
@Override
public HandlerView resolveHandlerView(FragmentWrapper fragment) {
String fragmentName = fragment.getSimpleClassName();
// Customize the view name based on the Fragment name
if (fragmentName.equals("HomeFragment")) {
return new HandlerView("自定义首页片段");
} else if (fragmentName.startsWith("Detail")) {
HashMap<String, Object> properties = new HashMap<>();
properties.put("extra_key", "extra_value");
return new HandlerView("自定义详情片段", properties);
}
// Return null to skip tracking
return null;
}
})
);
FTSdk.initRUMWithConfig(
FTRUMConfig()
.setViewFragmentTrackingHandler(object : FTViewFragmentTrackingHandler {
override fun resolveHandlerView(fragment: FragmentWrapper): HandlerView? {
val fragmentName = fragment.simpleClassName
return when {
fragmentName == "HomeFragment" ->
HandlerView("自定义首页片段")
fragmentName.startsWith("Detail") -> {
val properties = hashMapOf<String, Any>("extra_key" to "extra_value")
HandlerView("自定义详情片段", properties)
}
else -> null // Skip tracking
}
}
})
)
Custom Rules for View Timing Metrics¶
Use FTRUMConfig.setInitialResourceIdentifier and setLastInteractionIdentifier to customize the evaluation rules for network_settled_time and interaction_to_next_view_time of native Views. For metric meanings, units, and default rules, see View Timing Metrics.
Adjust the Time Window¶
Set the policy in the configuration passed to FTSdk.initRUMWithConfig. The following example adjusts the initial Resource window to 500 ms and the interaction_to_next_view_time upper limit to 5000 ms; the constructor parameter is in milliseconds, must be greater than 0, and the upper bound of the window is exclusive.
FTSdk.initRUMWithConfig(
new FTRUMConfig()
.setRumAppId(RUM_APP_ID)
.setEnableTraceUserView(true)
.setEnableTraceUserAction(true)
.setEnableTraceUserResource(true)
.setInitialResourceIdentifier(new FTTimeBasedInitialResourceIdentifier(500))
.setLastInteractionIdentifier(new FTTimeBasedInteractionIdentifier(5000))
);
FTSdk.initRUMWithConfig(
FTRUMConfig()
.setRumAppId(RUM_APP_ID)
.setEnableTraceUserView(true)
.setEnableTraceUserAction(true)
.setEnableTraceUserResource(true)
.setInitialResourceIdentifier(FTTimeBasedInitialResourceIdentifier(500))
.setLastInteractionIdentifier(FTTimeBasedInteractionIdentifier(5000))
)
Setting a policy does not automatically enable View, Action, or Resource collection. Automatic collection still requires enabling the corresponding configuration and meeting existing integration requirements. You can also use it together with the RUM manual instrumentation API.
Custom Evaluation Rules¶
Both policy interfaces provide a validate(context) method: returning true means the custom filter passes, and returning false means the item does not participate in the corresponding metric calculation. Passing the filter does not guarantee that a metric is generated; the metric generation constraints below must also be met. The evaluation conditions can use information provided by the context or external state maintained by the business side.
Custom rules replace the corresponding default time checks and no longer additionally apply the 100 ms or 3000 ms limits; the basic requirement that the time difference for interaction_to_next_view_time must be greater than 0 still applies.
Before RUM initialization, assign rules to the configured config. The following example includes only Resources registered during the business initial loading phase in network metrics and accepts only the last click interaction with an interval of less than 5 seconds.
import java.util.concurrent.atomic.AtomicBoolean;
// Maintained by the business; call initialLoading.set(false) when the initial loading phase ends.
AtomicBoolean initialLoading = new AtomicBoolean(true);
FTLastInteractionIdentifier navigationWindow = new FTTimeBasedInteractionIdentifier(5000);
config.setInitialResourceIdentifier(context -> initialLoading.get())
.setLastInteractionIdentifier(context ->
"click".equals(context.getActionType()) && navigationWindow.validate(context));
import java.util.concurrent.atomic.AtomicBoolean
// Maintained by the business; call initialLoading.set(false) when the initial loading phase ends.
val initialLoading = AtomicBoolean(true)
val navigationWindow = FTTimeBasedInteractionIdentifier(5000)
config.setInitialResourceIdentifier { context -> initialLoading.get() }
.setLastInteractionIdentifier { context ->
context.actionType == "click" && navigationWindow.validate(context)
}
Java can also use anonymous inner classes to implement FTInitialResourceIdentifier or FTLastInteractionIdentifier without using lambdas.
The contexts of both callbacks are immutable objects that expose the following methods. Time values use the same in-process monotonic clock as System.nanoTime(), in nanoseconds; they are not Unix timestamps and cannot be directly compared with System.currentTimeMillis().
| Context | Method | Meaning |
|---|---|---|
FTNetworkSettledResourceContext |
getResourceId() |
The Resource ID used for this SDK registration |
FTNetworkSettledResourceContext |
getResourceStartTimeNanos() |
The original Resource timing start recorded by the SDK |
FTNetworkSettledResourceContext |
getViewStartTimeNanos() |
The start time of the View to which it belongs |
FTPreviousViewLastInteractionContext |
getActionType() |
The type of the last candidate interaction of the previous View |
FTPreviousViewLastInteractionContext |
getInteractionTimeNanos() |
The interaction start time recorded by the SDK; for explicitly stopped waiting-type Actions, the stop time is used |
FTPreviousViewLastInteractionContext |
getNextViewStartTimeNanos() |
The start time of the next View |
The network context does not include the URL, request method, request headers, status code, or custom properties, so you cannot filter by reading the endpoint address directly from the context; the interaction_to_next_view_time context does not include the Action name or business properties.
Callback Usage Notes¶
- Set rules before initialization. Policies modified in
FTRUMConfigafter initialization do not take effect; callbacks can still read external state maintained by the business side. - Return quickly and ensure thread safety. Do not perform blocking operations such as network requests or file I/O in callbacks. Network rules may be called on the main thread or multiple collection threads;
interaction_to_next_view_timerules are called on the SDK event queue. - Business state is evaluated at callback execution time. Network rules are called synchronously when the SDK registers a Resource, and the evaluation occurs only once per registration. Registration may occur later than the request initiation time; when filtering by time, use the original start time in the context.
initialLoadingin the example uses the value at callback execution time; subsequent state changes do not cause the request to be re-evaluated. - Excluding metrics does not affect event collection. Returning
falseor throwing an ordinary exception only excludes the contribution of the current request or interaction to the metric; the original Resource or Action event is not discarded as a result.
Metric Generation Constraints¶
network_settled_time:
- Only after all selected requests are processed can the SDK calculate the duration from the requests that were successfully recorded. If there are no valid requests, the field is not generated; a missing field does not mean the duration is 0.
- The result is fixed when the View ends. If selected requests have not finished at that point, or their local cache writes have not completed, the field remains missing; it is not calculated later after those requests complete.
interaction_to_next_view_time:
- Only Actions of type
clickare accepted. Automatically collected back key operations also use theclicktype with the nameback; custom rules cannot cause other Action types to participate in the calculation. - Only the last successfully recorded candidate interaction of the previous View is evaluated. If the rule rejects that interaction, no result is generated for the current calculation, and earlier interactions are not searched.
Detailed Rules for Data Writes and Callback Timing
- Whether a request is valid: A selected request is included in
network_settled_timeonly when at least one of its Resource or corresponding Network Error records is successfully written to the local cache. If all related records are filtered out, discarded, or fail to be written, the SDK stops waiting for that request but does not include its duration. Valid 0-nanosecond results are retained. - Interaction order: The “last” interaction is determined by the order in which the SDK receives successful Action write results, not by re-sorting by interaction timestamp.
- When interaction rules are called: After both the candidate interaction of the previous View and the next View are determined, the SDK calls the
interaction_to_next_view_timerule; the same combination is evaluated only once. A new candidate interaction triggers re-evaluation. Ordinary View updates, retries, uploads, and cache restoration do not call these two rules again. - When interaction results are updated: When the SDK still retains the association information between the previous View and the next View, a delayed Action write result from the previous page can update the next View's
interaction_to_next_view_time. An already calculated result is not cleared because historical records of the previous View are removed.
Disable Metrics¶
setInitialResourceIdentifier does not accept null. Both configurations above must be set before FTSdk.initRUMWithConfig(config) and do not disable existing View, Action, or Resource event collection.
Action¶
- Requires
FTRUMConfig.setEnableTraceUserAction(true)to be enabled - Purpose: customize Action names and properties, or filter Action collection based on a specific View
FTSdk.initRUMWithConfig(new FTRUMConfig()
.setActionTrackingHandler(new FTActionTrackingHandler() {
@Override
public HandlerAction resolveHandlerAction(ActionEventWrapper actionEventWrapper) {
// Get the operation type
ActionSourceType actionType = actionEventWrapper.getSourceType();
Object source = actionEventWrapper.getSource();
// Filter Actions from the specified View
if (source instanceof View) {
View view = (View) source;
if (view.getId() == R.id.ignore_action_view) {
return null;
}
}
// Customize tracking based on the operation type
if (actionType == ActionSourceType.CLICK_VIEW) {
HashMap<String, Object> properties = new HashMap<>();
properties.put("extra_key", "extra_value");
return new HandlerAction("自定义按钮点击", properties);
} else if (actionType == ActionSourceType.CLICK_LIST_ITEM) {
return new HandlerAction("自定义列表项点击");
}
// Return null to skip tracking
return null;
}
})
);
FTSdk.initRUMWithConfig(
FTRUMConfig()
.setActionTrackingHandler(object : FTActionTrackingHandler {
override fun resolveHandlerAction(actionEventWrapper: ActionEventWrapper): HandlerAction? {
val source = actionEventWrapper.source
// Filter Actions from the specified View
if (source is View && source.id == R.id.ignore_action_view) {
return null
}
return when (actionEventWrapper.sourceType) {
ActionSourceType.CLICK_VIEW -> {
val properties = hashMapOf<String, Any>("extra_key" to "extra_value")
HandlerAction("自定义按钮点击", properties)
}
ActionSourceType.CLICK_LIST_ITEM ->
HandlerAction("自定义列表项点击")
else -> null // Skip tracking
}
}
})
)
Note
You can use ActionEventWrapper.getSource() to obtain the source object of the current operation. For Actions triggered by a View, such as normal clicks, list item clicks, and Tab clicks, source is usually the corresponding View. After setActionTrackingHandler is set, the SDK uses the handler's return result as the basis for Action collection. Actions for which null is returned are skipped; Actions that need to continue to be collected should return a HandlerAction.
Resource¶
- Requires
FTRUMConfig.setEnableTraceUserResource(true)to be enabled
Filter Collection by URL¶
Add Custom Properties¶
You can use FTRUMConfig.setOkHttpResourceContentHandler(FTResourceInterceptor.ContentHandlerHelperEx).
new FTResourceInterceptor.ContentHandlerHelperEx() {
@Override
public void onRequest(Request request, HashMap<String, Object> extraData) {
extraData.put("df_custom_key","custom_value");
}
@Override
public void onResponse(Response response, HashMap<String, Object> extraData) throws IOException {
extraData.put("df_custom_key","custom_value");
}
@Override
public boolean onExceptionWithFilter(Exception e, HashMap<String, Object> extraData) {
extraData.put("df_custom_key","custom_value");
return false;
}
}
object : FTResourceInterceptor.ContentHandlerHelperEx() {
override fun onRequest(
request: Request,
extraData: HashMap<String, Any>
) {
extraData["df_custom_key"] = "custom_value"
}
override fun onResponse(
response: Response,
extraData: HashMap<String, Any>
) {
extraData["df_custom_key"] = "custom_value"
}
override fun onExceptionWithFilter(
e: Exception,
extraData: HashMap<String, Any>
): Boolean {
extraData["df_custom_key"] = "custom_value"
return false
}
}
Filter Network Errors¶
You can filter local network IOException errors. You can configure this through FTRUMConfig.setOkHttpResourceContentHandler(FTResourceInterceptor.ContentHandlerHelperEx) or by customizing Resource.
new FTResourceInterceptor.ContentHandlerHelperEx() {
//...
/**
* Returns exceptions that occur during the network connection process
*
* @param e IOException data that occurred during the request
* @param extraData Additional data
* @return Whether to filter local network errors of type network_error. true means filter and do not collect
*/
@Override
public boolean onExceptionWithFilter(Exception e, HashMap<String, Object> extraData) {
if (e instanceof SocketTimeoutException) { // Network timeout
return true;
}
return super.onExceptionWithFilter(e, extraData);
}
}
object : FTResourceInterceptor.ContentHandlerHelperEx() {
//...
/**
* Returns exceptions that occur during the network connection process
*
* @param e IOException data that occurred during the request
* @param extraData Additional data
* @return Whether to filter local network errors of type network_error. true means override and do not collect
*/
override fun onExceptionWithFilter(e: Exception, extraData: HashMap<String, Any>): Boolean {
return if (e is SocketTimeoutException) {
true
} else {
super.onExceptionWithFilter(e, extraData)
}
}
}
Error¶
Custom Fields for Crash/ANR¶
With ft-sdk >= 1.7.5, you can use FTRUMConfig.setIssueDataProvider(FTIssueDataProvider) to add custom fields to automatically collected Crash and ANR RUM Errors.
FTRUMConfig config = new FTRUMConfig()
.setEnableTrackAppCrash(true)
.setEnableTrackAppANR(true)
.setIssueDataProvider(issue -> {
Map<String, Object> fields = new HashMap<>();
fields.put("business_scene", sceneStore.current());
fields.put("historical_issue", issue.isHistorical());
return fields;
});
FTIssueDataProvider.provideAdditionalFields(FTIssueInfo) is called synchronously when an Error is constructed and may be executed concurrently. Implementations should be thread-safe, avoid I/O, and return within 10 ms. Setting a Provider does not automatically enable Crash or ANR collection; you still need to enable the corresponding collection items.
- Only automatically collected Java/Native Crashes and watchdog, native, and
ApplicationExitInfoANRs trigger the Provider; manual Errors, Network Errors, and WebView Errors do not trigger it. - For data recovered from a Native dump or
ApplicationExitInfo,FTIssueInfo.isHistorical()returnstrue. - The return value supports strings, booleans, and finite numeric values, and at most 50 entries are checked; keys can be up to 100 UTF-8 bytes, string values up to 4096 UTF-8 bytes, and all fields combined must not exceed 25 KiB.
- Invalid keys, keys that exceed limits, SDK reserved fields, and keys starting with
error.orerror_are ignored. The business side is responsible for ensuring that field content meets privacy and compliance requirements.
Custom TraceHeader¶
You can configure this through FTTraceConfig.setOkHttpTraceHeaderHandler(FTTraceInterceptor.HeaderHandler) or by customizing Trace. The following uses w3c-traceContext as an example.
new FTTraceInterceptor.HeaderHandler() {
private String[] splits;
@Override
public HashMap<String, String> getTraceHeader(Request request) {
HashMap<String, String> map = new HashMap<>();
// Get the custom trace_id from the header
String replaceTrace = request.header(CUSTOM_TRACE_HEADER);
String headerString = FTTraceManager.get().
getTraceHeader(request.url().toString())
// Get the propagation header from the headers
.get(FTTraceHandler.W3C_TRACEPARENT_KEY);
splits = headerString.split("-");
String originTraceId = splits[1];
splits[1] = replaceTrace;
map.put(FTTraceHandler.W3C_TRACEPARENT_KEY, headerString.replace(originTraceId, replaceTrace));
return map;
}
@Override
public String getSpanID() {
if (splits != null) {
return splits[2];
}
return null;
}
@Override
public String getTraceID() {
if (splits != null) {
return splits[1];
}
return null;
}
};
object : FTTraceInterceptor.HeaderHandler() {
private var splits: List<String>? = null
override fun getTraceHeader(request: Request): HashMap<String, String> {
val map = HashMap<String, String>()
// Get the custom trace_id from the header
val replaceTrace = request.header(CUSTOM_TRACE_HEADER)
val headerString = FTTraceManager.get()
.getTraceHeader(request.url().toString())
.get(FTTraceHandler.W3C_TRACEPARENT_KEY)
splits = headerString?.split("-")
val originTraceId = splits?.getOrNull(1)
if (headerString != null && originTraceId != null && replaceTrace != null) {
map[FTTraceHandler.W3C_TRACEPARENT_KEY] =
headerString.replace(originTraceId, replaceTrace)
}
return map
}
override fun getSpanID(): String? {
return splits?.getOrNull(2)
}
override fun getTraceID(): String? {
return splits?.getOrNull(1)
}
}
Use a Custom trace_id to Associate RUM Resources¶
If the application already has a custom trace_id, for example, when the request header key is custom_trace_id, you can update the trace_id based on the traceparent generated by the SDK, and use TraceContext.Simple to specify the trace_id used for RUM Resource association.
new FTTraceInterceptor.HeaderHandler() {
@Override
public TraceContext getTraceContext(Request request) {
HashMap<String, String> headers = FTTraceManager.get()
.getTraceHeader(request.url().toString());
// Get the custom trace_id from the request header, for example custom_trace_id
String customTraceId = request.header(CUSTOM_TRACE_HEADER);
TraceContext.Simple sdkContext = TraceContext.Simple.fromTraceType(headers);
if (customTraceId == null
|| customTraceId.length() == 0
|| sdkContext == null
|| sdkContext.getTraceId() == null) {
return sdkContext;
}
String traceparent = headers.get(FTTraceHandler.W3C_TRACEPARENT_KEY);
if (traceparent == null) {
return sdkContext;
}
String newTraceparent = traceparent.replace(
sdkContext.getTraceId(),
customTraceId
);
// Update the W3C trace header injected into the request
headers.put(FTTraceHandler.W3C_TRACEPARENT_KEY, newTraceparent);
// Optional: retain the custom business header
headers.put(CUSTOM_TRACE_HEADER, customTraceId);
// RUM Resource association uses customTraceId; spanId continues to use the spanId generated by the SDK
return new TraceContext.Simple(headers, customTraceId, sdkContext.getSpanId());
}
};
object : FTTraceInterceptor.HeaderHandler() {
override fun getTraceContext(request: Request): TraceContext? {
val headers = FTTraceManager.get()
.getTraceHeader(request.url().toString())
// Get the custom trace_id from the request header
val customTraceId = request.header(CUSTOM_TRACE_HEADER)
val sdkContext = TraceContext.Simple.fromTraceType(headers)
val sdkTraceId = sdkContext?.traceId
val sdkSpanId = sdkContext?.spanId
if (customTraceId.isNullOrEmpty() || sdkTraceId.isNullOrEmpty()) {
return sdkContext
}
val traceparent = headers[FTTraceHandler.W3C_TRACEPARENT_KEY] ?: return sdkContext
val newTraceparent = traceparent.replace(sdkTraceId, customTraceId)
// Update the W3C trace header injected into the request
headers[FTTraceHandler.W3C_TRACEPARENT_KEY] = newTraceparent
// Optional: retain the custom business header
headers[CUSTOM_TRACE_HEADER] = customTraceId
// RUM Resource association uses customTraceId; spanId continues to use the spanId generated by the SDK
return TraceContext.Simple(headers, customTraceId, sdkSpanId)
}
}
Note: A W3C trace_id must be a 32-character hexadecimal string and must not consist entirely of 0.