Unity Application Access¶
Prerequisites¶
Note: If you have activated the RUM Headless service, the prerequisites are automatically configured for you, and you can directly access the application.
- Install DataKit;
- Configure the RUM collector;
- Configure DataKit to be accessible via the public network and install the IP geolocation database.
Application Access¶
- Go to RUM > Create Application > Android/iOS;
- Create two separate applications for Unity Android and Unity iOS to receive RUM data from the Android and iOS platforms respectively;
- Enter the corresponding application name and application ID for each platform's application;
- Choose the application access method:
- Public Network DataWay: Directly receives RUM data without installing the DataKit collector.
- Local Environment Deployment: Receives RUM data after meeting the prerequisites.
Installation¶
Source Code Repository: https://github.com/GuanceCloud/datakit-unity
Demo Repository: https://github.com/GuanceCloud/datakit-unity/blob/dev/Assets/Scenes
- Download the latest ft-sdk-unity.unitypackage
Assets/Plugins
├── Android
│ ├── FTUnityBridge.java // Android bridge
│ ├── InnerClassProxy.java // Android Inner Setting Proxy
│ ├── ft-sdk-release.aar // Android SDK
│ ├── gson-2.8.5.jar // Android SDK dependency third-party library
├── iOS
│ ├── FTMobileSDK.xcframework // iOS SDK
│ ├── FTUnityBridge.mm // iOS bridge
├── FTSDK.cs // FTSDK.prefab bound script
├── FTSDK.prefab // SDK initialization prefab
├── FTUnityBridge.cs // Unity bridge bridging iOS Android and other platform methods
├── FTViewObserver.cs // FTViewObserver.prefab bound script
├── FTViewObserver.prefab // View page monitoring prefab
├── UnityMainThreadDispatcher.cs // UnityMainThreadDispatcher.prefab bound script
├── UnityMainThreadDispatcher.prefab // Main thread consumption queue prefab
Asserts->Import Package->Custom Package...Importft-sdk-unity.unitypackage- Add the json parsing third-party library
"com.unity.nuget.newtonsoft-json", which can be added viaPakcage Manager->Add Package by name ... - Drag the
FTSDK.prefabto the first scene page, and initialize the SDK in the_InitSDKmethod inFTSDK.cs. If the native Android and iOS projects have already integrated the native SDK, you need to comment out the_InitSDKmethod to avoid duplicate settings. - Drag the
FTViewObserver.prefabto other scene pages to achieve pageViewlifecycle monitoring, including application sleep and wake. - Monitor and convert Unity crash data and ordinary log data through
Application.logMessageReceived, see theOnEnableandOnDisablemethods inFTSDK.cs.
Note: If the native SDK Android gson-2.8.5.jar, ft-sdk-release.aar, iOS FTMobileSDK.framework have been integrated, they can be removed from the project. In addition, the Android Okhttp request and startup time-consuming functions need to be used in conjunction with the ft-plugin. For detailed configuration, please see Android SDK
Initialization¶
FTUnityBridge.Install(new SDKConfig
{
datakitUrl = "http://10.0.0.1:9529",
env = "prod",
debug = true,
});
| Field | Type | Required | Description |
|---|---|---|---|
| datakitUrl | string | Yes | Local environment deployment (Datakit) reporting URL address, example: http://10.0.0.1:9529, port defaults to 9529, the device installing the SDK must be able to access this address. Note: Configure either datakitUrl or datawayUrl, choose one |
| datawayUrl | string | Yes | Public network Dataway reporting URL address, obtained from the [RUM] application, example: https://open.dataway.url, the device installing the SDK must be able to access this address. Note: Configure either datakitUrl or datawayUrl, choose one |
| clientToken | string | Yes | Authentication token, needs to be used together with datawayUrl |
| debug | boolean | No | Sets whether to allow printing Debug logs, default false |
| env | string | No | Environment, default prod, any characters, it is recommended to use a single word, such as test, etc. |
| serviceName | string | No | Sets the name of the business or service it belongs to. Default: df_rum_ios, df_rum_android |
| globalContext | object | No | Add custom tags |
| autoSync | boolean | No | Whether to automatically synchronize data to the server after collection. Default YES. When NO, use the flushSyncData method to manage data synchronization manually |
| syncPageSize | number | No | Sets the number of entries for synchronization requests. Range [5,). Note: A larger number of request entries means data synchronization consumes more computing resources. Default is 10 |
| syncSleepTime | number | No | Sets the synchronization interval time. Range [0,5000], default is not set |
| enableDataIntegerCompatible | boolean | No | It is recommended to enable this when coexistence with web data is needed. This configuration is used to handle web data type storage compatibility issues. Enabled by default in SDK version 1.1.0 and later |
| compressIntakeRequests | boolean | No | Compresses the uploaded synchronization data using deflate. Disabled by default. Supported in SDK version 1.1.0 and above |
| enableLimitWithDbSize | boolean | No | Enables limiting data size using the database, default 100MB, unit Byte. A larger database means greater disk pressure. Disabled by default. Note: After enabling, the Log configuration logCacheLimitCount and RUM configuration rumCacheLimitCount will become invalid. Supported in SDK version 1.1.0 and above |
| dbCacheLimit | number | No | DB cache size limit. Range [30MB,), default 100MB, unit byte. Supported in SDK version 1.1.0 and above |
| dbDiscardStrategy | string | No | Sets the data discard rule in the database. Discard strategy: discard discard new data (default), discardOldest discard old data. Supported in SDK version 1.1.0 and above |
| dataModifier | object | No | Modifies a single field. Supported in SDK version 1.1.0 and above. See example usage here |
| lineDataModifier | object | No | Modifies a single piece of data. Supported in SDK version 1.1.0 and above. See example usage here |
RUM Configuration¶
FTUnityBridge.InitRUMConfig(new RUMConfig()
{
androidAppId = "androidAppId",
iOSAppId = "iOSAppId",
sampleRate = 0.8f,
});
| Field | Type | Required | Description |
|---|---|---|---|
| androidAppId | string | Yes | Corresponds to setting the RUM appid, which will enable the RUM collection function. Method to obtain appid |
| iOSAppId | string | Yes | Corresponds to setting the RUM appid, which will enable the RUM collection function. Method to obtain appid |
| sampleRate | float | No | Sampling rate, value 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 | float | No | Sets the error collection rate. When a session is not sampled by sampleRate, if an error occurs during the session, data from the 1 minute before the error can be collected. Value range [0,1], 0 means no collection, 1 means full collection, default value is 0. Scope is all View, Action, LongTask, Error data under the same session_id |
| enableNativeUserAction | boolean | No | Whether to perform Native Action tracking, Button click events. It is recommended to disable for pure uni-app applications, default is false. Not supported for Android cloud packaging. |
| enableNativeUserResource | boolean | No | Whether to perform Native Resource automatic tracking, default is false. Not supported for Android cloud packaging. Since uniapp network requests on iOS are implemented using system APIs, after enabling, all iOS resource data can be collected together. Please shield manual collection on the iOS side at this time to prevent duplicate data collection. |
| enableNativeUserView | boolean | No | Whether to perform Native View automatic tracking. It is recommended to disable for pure uni-app applications, default is false |
| errorMonitorType | string/array | No | Error monitoring supplementary types: all, battery, memory, cpu. Not set by default. |
| deviceMonitorType | string/array | No | Page monitoring supplementary types: all, battery (only supported on Android), memory, cpu, fps. Not set by default. |
| detectFrequency | string | No | Page monitoring frequency: normal (default), frequent, rare |
| globalContext | object | No | Custom global parameters, special key: track_id (used for tracking function) |
| enableResourceHostIP | boolean | No | Whether to collect the IP address of the requested target domain name. Scope: Only affects the default collection when enableNativeUserResource is true. iOS: Supported on >= iOS 13. Android: A single Okhttp has an IP caching mechanism for the same domain name. For the same OkhttpClient, the IP will only be generated once if the server IP connected to does not change. |
| enableTrackNativeCrash | boolean | No | Whether to enable monitoring of Android Java Crash and OC/C/C++ crashes, default is false |
| enableTrackNativeAppANR | boolean | No | Whether to enable Native ANR monitoring, default is false |
| enableTrackNativeFreeze | boolean | No | Whether to perform Native Freeze automatic tracking, default is false |
| nativeFreezeDurationMs | number | No | Sets the threshold for collecting Native Freeze stalls, value range [100,), unit milliseconds. iOS default 250ms, Android default 1000ms |
| rumDiscardStrategy | string | No | Discard strategy: discard discard new data (default), discardOldest discard old data |
| rumCacheLimitCount | number | No | Local cache maximum RUM entry count limit [10_000,), default 100_000 |
Log Configuration¶
FTUnityBridge.InitLogConfig(new LogConfig
{
sampleRate = 0.9f,
enableCustomLog = true,
enableLinkRumData = true,
});
| Field | Type | Required | Description |
|---|---|---|---|
| sampleRate | float | No | Sampling rate, value range [0,1], 0 means no collection, 1 means full collection, default value is 1. |
| enableLinkRumData | boolean | No | Whether to associate with RUM |
| enableCustomLog | boolean | No | Whether to enable custom logs |
| discardStrategy | string | No | Log discard strategy: discard discard new data (default), discardOldest discard old data |
| logLevelFilters | array |
No | Log level filtering, the array needs to fill in log levels: info, warning, error, critical, ok (recovery) |
| globalContext | object | No | Custom global parameters |
| logCacheLimitCount | number | No | Local cache maximum log entry count limit [1000,). Larger logs mean greater disk cache pressure. Default 5000 |
Trace Configuration¶
FTUnityBridge.InitTraceConfig(new TraceConfig
{
sampleRate = 0.9f,
traceType = TraceType.DDTrace,
enableNativeAutoTrace = true,
enableLinkRumData = true
});
| Field | Type | Required | Description |
|---|---|---|---|
| sampleRate | float | No | Sampling rate, value range [0,1], 0 means no collection, 1 means full collection, default value is 1. |
| traceType | string | No | Trace type: ddTrace (default), zipkinMultiHeader, zipkinSingleHeader, traceparent, skywalking, jaeger |
| enableLinkRUMData | boolean | No | Whether to associate with RUM data, default false |
| enableNativeAutoTrace | boolean | No | Whether to enable native network automatic tracing for iOS NSURLSession, Android OKhttp, default false. Not supported for Android cloud packaging. Since uniapp network requests on iOS are implemented using system APIs, after enabling, network requests initiated by uniapp on iOS can be automatically traced. Please shield manual trace on the iOS side at this time to prevent incorrect association between traces and RUM data. |
RUM User Data Tracking¶
Currently, RUM data transmission can only be achieved by manually calling methods.
Action¶
Usage¶
/// <summary>
/// Add Action
/// </summary>
/// <param name="actionName"> action name</param>
/// <param name="actionType"> action type</param>
public static void StartAction(string actionName, string actionType)
/// <summary>
/// Add Action
/// </summary>
/// <param name="actionName">action name</param>
/// <param name="actionType">action type</param>
/// <param name="property">Additional attribute parameters</param>
public static void StartAction(string actionName, string actionType, Dictionary<string, object> property)
/// <summary>
/// Add Action
/// </summary>
/// <param name="actionName">action name</param>
/// <param name="actionType">action type</param>
public static void AddAction(string actionName, string actionType)
/// <summary>
/// Add Action
/// </summary>
/// <param name="actionName">action name</param>
/// <param name="actionType">action type</param>
/// <param name="property">Additional attribute parameters</param>
public static void AddAction(string actionName, string actionType, Dictionary<string, object> property)
Code Example¶
View¶
Usage¶
/// <summary>
/// View start
/// </summary>
/// <param name="viewName">Current page name</param>
public static void StartView(string viewName)
/// <summary>
/// View start
/// </summary>
/// <param name="viewName">Current page name</param>
/// <param name="property">Additional attribute parameters</param>
public static void StartView(string viewName, Dictionary<string, object> property)
/// <summary>
/// View end
/// </summary>
public static void StopView()
/// <summary>
/// View end
/// </summary>
/// <param name="property">Additional attribute parameters</param>
public static void StopView(Dictionary<string, object> property)
Code Example¶
Resource¶
Usage¶
/// <summary>
/// resource start
/// </summary>
/// <param name="resourceId">Resource Id</param>
/// <returns></returns>
public static async Task StartResource(string resourceId)
/// <summary>
/// resource start
/// </summary>
/// <param name="resourceId">Resource Id</param>
/// <param name="property">Additional attribute parameters</param>
/// <returns></returns>
public static async Task StartResource(string resourceId, Dictionary<string, object> property)
/// <summary>
/// resource end
/// </summary>
/// <param name="resourceId">Resource Id</param>
/// <returns></returns>
public static async Task StopResource(string resourceId)
/// <summary>
/// resource end
/// </summary>
/// <param name="resourceId">Resource Id</param>
/// <param name="property">Additional attribute parameters</param>
public static async Task StopResource(string resourceId, Dictionary<string, object> property)
/// <summary>
/// Add network transmission content and metrics
/// </summary>
/// <param name="resourceId">Resource Id</param>
/// <param name="resourceParams">Data transmission content</param>
/// <param name="netStatus">Network metric data</param>
public static async Task AddResource(string resourceId, ResourceParams resourceParams)
ResourceParams¶
| Method Name | Type | Required | Description |
|---|---|---|---|
| url | string | Yes | url address |
| requestHeader | string | No | Request header parameters, no format restrictions |
| responseHeader | string | No | Response header parameters, no format restrictions |
| responseConnection | string | No | Response connection |
| responseContentType | string | No | Response ContentType |
| responseContentEncoding | string | No | Response ContentEncoding |
| resourceMethod | string | No | Request method GET,POST, etc. |
| responseBody | string | No | Response body content |
Code Example¶
FTUnityBridge.StartResource(resourceId);
FTUnityBridge.StopResource(resourceId);
ResourceParams resourceParams = new ResourceParams();
resourceParams.url = url;
resourceParams.requestHeader = client.DefaultRequestHeaders.ToDictionary(header => header.Key, header => string.Join(",", header.Value));
resourceParams.responseHeader = response.Headers.ToDictionary(header => header.Key, header => string.Join(",", header.Value));
resourceParams.resourceStatus = (int)response.StatusCode;
resourceParams.responseBody = responseData;
resourceParams.resourceMethod = "GET";
FTUnityBridge.AddResource(resourceId, resourceParams);
Error¶
Usage¶
/// <summary>
/// Add error information
/// </summary>
/// <param name="log">Log</param>
/// <param name="message">Message</param>
/// <param name="errorType">Error type</param>
/// <param name="state">Program running state</param>
/// <returns></returns>
public static async Task AddError(string log, string message)
/// <summary>
/// Add error information
/// </summary>
/// <param name="log">Log</param>
/// <param name="message">Message</param>
/// <param name="errorType">Error type</param>
/// <param name="state">Program running state</param>
/// <param name="property">Additional attribute parameters</param>
/// <returns></returns>
public static async Task AddError(string log, string message,
Dictionary<string, object> property)
Code Example¶
void OnEnable()
{
Application.logMessageReceived += LogCallBack;
}
void OnDisable()
{
Application.logMessageReceived -= LogCallBack;
}
void LogCallBack(string condition, string stackTrace, LogType type)
{
if (type == LogType.Exception)
{
FTUnityBridge.AddError(stackTrace, condition);
}
}
LongTask¶
Usage¶
/// <summary>
/// Add long-running task
/// </summary>
/// <param name="log">Log content</param>
/// <param name="duration">Duration, nanoseconds</param>
/// <returns></returns>
public static async Task AddLongTask(string log, long duration)
/// <summary>
/// Add long-running task
/// </summary>
/// <param name="log">Log content</param>
/// <param name="duration">Duration, nanoseconds</param>
/// <param name="property">Additional attribute parameters</param>
/// <returns></returns>
public static async Task AddLongTask(string log, long duration, Dictionary<string, object> property)
Code Example¶
Log Printing¶
The log content is currently limited to 30 KB. Characters exceeding this limit will be truncated.
Usage¶
/// <summary>
/// Add log
/// </summary>
/// <param name="log">Log content</param>
/// <param name="level">Log level info, warning, error, critical, ok</param>
/// <returns></returns>
public static async Task AddLog(string log, LogLevel level)
/// <summary>
/// Add log
/// </summary>
/// <param name="log">Log content</param>
/// <param name="level">Log level info, warning, error, critical, ok</param>
/// <param name="property">Additional attribute parameters</param>
/// <returns></returns>
public static async Task AddLog(string log, LogLevel level, Dictionary<string, object> property)
LogLevel¶
| Method Name | Meaning |
|---|---|
| info | Info |
| warning | Warning |
| error | Error |
| critical | Critical |
| ok | Ok (Recovery) |
Code Example¶
Tracer Network Trace¶
Trace is implemented by generating Trace Headers and then adding these Headers to the http request headers.
Usage¶
/// <summary>
/// Get trace Id
/// </summary>
/// <param name="url">url address</param>
/// <returns>json string</returns>
public static async Task<string> GetTraceHeaderWithUrl(string url)
/// <summary>
/// Get trace
/// </summary>
/// <param name="resourceId">Resource Id</param>
/// <param name="url">url address</param>
/// <returns>json string</returns>
public static async Task<string> GetTraceHeader(string resourceId, string url)
Code Example¶
string headData = FTUnityBridge.GetTraceHeader(resourceId, FAKE_URL);
string headData = FTUnityBridge.GetTraceHeader(FAKE_URL);
Clear SDK Cache Data¶
Use FTUnityBridge to clear unsynchronized cache data
/**
* Clears all data that has not yet been uploaded to the server.
*/
FTUnityBridge.clearAllData();
Active Data Synchronization¶
When SDKConfig.autoSync is configured as true, no additional operations are needed; the SDK will perform automatic synchronization.
When SDKConfig.autoSync is configured as false, you need to actively trigger the data synchronization method to synchronize data.
/**
* Actively synchronizes data. When `FTMobileConfig.autoSync=false` is configured, this method needs to be actively triggered to synchronize data.
* @returns a Promise.
*/
FTUnityBridge.flushSyncData();
Add Custom Tags¶
/// <summary>
/// Add custom global parameters. Applies to RUM, Log data.
/// </summary>
public static void AppendGlobalContext(Dictionary<string, object> property)
/// <summary>
/// Add custom RUM global parameters. Applies to RUM data.
/// </summary>
public static void AppendRUMGlobalContext(Dictionary<string, object> property)
/// <summary>
/// Add custom RUM, Log global parameters. Applies to Log data.
/// </summary>
public static void AppendLogGlobalContext(Dictionary<string, object> property)
User Information Binding and Unbinding¶
Usage¶
/// <summary>
/// Bind RUM user information
/// </summary>
/// <param name="userId">User unique id</param>
public static async Task BindUserData(string userId)
/// <summary>
/// Bind RUM user information
/// </summary>
/// <param name="userData"></param>
public static async Task BindUserData(UserData userData)
| Method Name | Type | Required | Description |
|---|---|---|---|
| userId | string | Yes | User id |
| userName | string | No | Username |
| userEmail | string | No | User email |
| extra | dictionary | No | Assign values in KV format. For addition rules, please refer to here |
Code Example¶
FTUnityBridge.BindUserData(new UserData
{
userId = "userid",
userName = "userName",
userEmail = "someone@email.com",
extra = new Dictionary<string, string>{
{"custom_data","custom data"}
}
});
FTUnityBridge.UnBindUserdata()
Close SDK¶
Data Masking¶
If you want to fully mask a field, it is recommended to use SDKConfig.dataModifier, which performs better. If you need detailed rule replacement, SDKConfig.lineDataModifier is recommended.
Single Field Modification (dataModifier)
- Function: Modifies the value of a single field in the data.
- Parameter format:
{key: newValue} - Example:
{"device_uuid": "xxx"}will replace thedevice_uuidfield value in the target data with "xxx".
Single Data Modification (lineDataModifier)
- Function: Modifies the specified field value in a certain type of data.
- Parameter format:
{measurement: {key: newValue}} - Example:
{"view": {"view_url": "xxx"}}will modify theview_urlfield value of allviewtype data to "xxx". measurementdata type list:- RUM data:
view,resource,action,long_task,error - Log data:
log
- RUM data:
FTUnityBridge.Install(new SDKConfig
{
//...
dataModifier = new Dictionary<string, object>{
{"device_uuid","xxx"}
},
lineDataModifier = new Dictionary<string, Dictionary<string, object>>
{
{"view",new Dictionary<string, object>{
{"view_url","xxx"}
}
}
}
});
Native and Unity Hybrid Development¶
If your project is developed natively, and some pages or business processes are implemented using Unity, the SDK installation and initialization configuration methods are as follows:
-
Installation: The installation method remains the same.
-
Initialization: Please refer to iOS SDK Initialization Configuration, Android SDK Initialization Configuration for initialization configuration within the native project.
- Cancel the original initialization part in the
Unity SDK'sFTSDK.csto avoid duplicate initialization.
// FTSDK.cs
IEnumerator _LoadPrefabs()
{
yield return Instantiate(MainThreadDispatch);
//_InitSDK(); // Cancel initialization
yield return Instantiate(ViewObserver);
}
Publish Package Related Configuration¶
Android¶
iOS¶
Frequently Asked Questions¶
Add Prefix to Variables to Avoid Conflict Fields¶
To avoid conflicts between custom fields and SDK data, it is recommended to add a project abbreviation prefix to tag names, such as df_tag_name. The key values used in the project can be queried from the source code. When the same variable appears in the SDK global variables and RUM/Log, the RUM/Log variable will override the SDK global variable.