Skip to content

Unity Application Integration


Prerequisites

Note: If you have enabled the RUM Headless service, the prerequisites have already been configured for you, and you can proceed directly to integrating the application.

Application Integration

  1. Go to User Access Monitoring > Create Application > Android/iOS;
  2. Create two applications for Unity Android and Unity iOS respectively to receive RUM data from the Android and iOS platforms;
  3. Enter the corresponding application name and application ID for each platform's application;
  4. Choose the application integration method:
    • Public DataWay: Directly receive RUM data without installing the DataKit collector.
    • Local Environment Deployment: Receive RUM data after meeting the prerequisites.

Installation

Source Code: https://github.com/GuanceCloud/datakit-unity

Demo: https://github.com/GuanceCloud/datakit-unity/blob/dev/Assets/Scenes

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
├── iOS
│   ├── FTMobileSDK.xcframework             // iOS SDK
│   ├── FTUnityBridge.mm                    // iOS bridge
├── FTSDK.cs                                // FTSDK.prefab Binding Script
├── FTSDK.prefab                            // SDK Initialization Prefab
├── FTUnityBridge.cs                        // Unity Bridge for iOS, Android, etc.
├── FTViewObserver.cs                       // FTViewObserver.prefab Binding Script
├── FTViewObserver.prefab                   // View Page Monitoring Prefab
├── UnityMainThreadDispatcher.cs            // UnityMainThreadDispatcher.prefab Binding Script
├── UnityMainThreadDispatcher.prefab        // Main Thread Queue Consumer Prefab
  • Asserts -> Import Package -> Custom Package... Import ft-sdk-unity.unitypackage
  • Add the JSON parsing third-party library "com.unity.nuget.newtonsoft-json", which can be added via Pakcage Manager -> Add Package by name ...
  • Drag FTSDK.prefab to the first scene page and initialize the SDK in the _InitSDK method in FTSDK.cs. If the native Android and iOS projects have already integrated the native SDK, comment out the _InitSDK method to avoid duplicate settings.
  • Drag FTViewObserver.prefab to other scene pages to achieve View lifecycle monitoring, including application sleep and wake-up.
  • Monitor and convert Unity crash data and regular log data via Application.logMessageReceived, see FTSDK.cs OnEnable OnDisable methods.

Note: If the native SDK Android gson-2.8.5.jar, ft-sdk-release.aar, and iOS FTMobileSDK.framework are already integrated, they can be removed from the project. Additionally, Android Okhttp requests and startup time functions require ft-plugin. For detailed configuration, 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, e.g., http://10.0.0.1:9529, default port 9529. The device installing the SDK must be able to access this address. Note: Choose either datakitUrl or datawayUrl
datawayUrl string Yes Public Dataway reporting URL, obtained from the [User Access Monitoring] application, e.g., https://open.dataway.url. The device installing the SDK must be able to access this address. Note: Choose either datakitUrl or datawayUrl
clientToken string Yes Authentication token, required when using datawayUrl
debug boolean No Set whether to allow Debug log printing, default false
env string No Environment, default prod, any character, recommended to use a single word, e.g., test
serviceName string No Set the name of the business or service, default: df_rum_ios, df_rum_android
globalContext object No Add custom tags
autoSync boolean No Whether to automatically sync data to the server after collection. Default YES. When NO, use the flushSyncData method to manage data synchronization manually
syncPageSize number No Set the number of entries for sync requests. Range [5,). Note: The larger the number of entries, the more computational resources the data synchronization will consume, default is 10
syncSleepTime number No Set the sync interval time. Range [0,5000], default not set
enableDataIntegerCompatible boolean No Recommended to enable when coexisting with web data. This configuration handles web data type storage compatibility issues. Enabled by default in SDK 1.1.0 and later
compressIntakeRequests boolean No Compress the uploaded sync data with deflate, default off, supported in SDK 1.1.0 and later
enableLimitWithDbSize boolean No Enable DB size limit for data, default 100MB, unit Byte. The larger the database, the greater the disk pressure, default off.
Note: When enabled, Log configuration logCacheLimitCount and RUM configuration rumCacheLimitCount will be invalid. Supported in SDK 1.1.0 and later
dbCacheLimit number No DB cache limit size. Range [30MB,), default 100MB, unit byte, supported in SDK 1.1.0 and later
dbDiscardStrategy string No Set the data discard rule in the database.
Discard strategy: discard discard new data (default), discardOldest discard old data. Supported in SDK 1.1.0 and later
dataModifier object No Modify a single field. Supported in SDK 1.1.0 and later, see here for usage examples
lineDataModifier object No Modify a single line of data. Supported in SDK 1.1.0 and later, see here for usage examples

RUM Configuration

FTUnityBridge.InitRUMConfig(new RUMConfig()
            {
                androidAppId = "androidAppId",
                iOSAppId = "iOSAppId",
                sampleRate = 0.8f,
            });
Field Type Required Description
androidAppId string Yes Corresponding RUM appid, required to enable RUM collection, get appid method
iOSAppId string Yes Corresponding RUM appid, required to enable RUM collection, get appid method
sampleRate float No Sampling rate, range [0,1], 0 means no collection, 1 means full collection, default 1. Scope: all View, Action, LongTask, Error data under the same session_id
sessionOnErrorSampleRate float No Set 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. Range [0,1], 0 means no collection, 1 means full collection, default 0. Scope: all View, Action, LongTask, Error data under the same session_id
enableNativeUserAction boolean No Whether to track Native Action, Button click events. Pure uni-app applications are recommended to turn off, default false, Android cloud packaging not supported
enableNativeUserResource boolean No Whether to track Native Resource automatically, default false, Android cloud packaging not supported. Since uniapp network requests are implemented using system APIs on iOS, enabling this will allow all resource data on iOS to be collected. Please disable manual collection on iOS to avoid duplicate data collection.
enableNativeUserView boolean No Whether to track Native View automatically. Pure uni-app applications are recommended to turn off, default false
errorMonitorType string/array No Error monitoring supplement types: all, battery, memory, cpu, default not set
deviceMonitorType string/array No Page monitoring supplement types: all, battery (Android only), memory, cpu, fps, default not set
detectFrequency string No Page monitoring frequency: normal (default), frequent, rare
globalContext object No Custom global parameters, special key: track_id (for tracking)
enableResourceHostIP boolean No Whether to collect the IP address of the request target domain. Scope: Only affects default collection when enableNativeUserResource is true. iOS: >= iOS 13 supported. Android: Single Okhttp has an IP caching mechanism for the same domain. The same OkhttpClient will only generate once if the server IP does not change.
enableTrackNativeCrash boolean No Whether to enable Android Java Crash and OC/C/C++ crash monitoring, default `false
enableTrackNativeAppANR boolean No Whether to enable Native ANR monitoring, default false
enableTrackNativeFreeze boolean No Whether to track Native Freeze automatically, default false
nativeFreezeDurationMs number No Set the threshold for collecting Native Freeze stalls, range [100,), unit ms. 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 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, range [0,1], 0 means no collection, 1 means full collection, default 1.
enableLinkRumData boolean No Whether to link 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 filters, array must contain log levels: info, warning, error, critical, ok
globalContext object No Custom global parameters
logCacheLimitCount number No Local cache maximum log entry 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, range [0,1], 0 means no collection, 1 means full collection, default 1.
traceType string No Trace type: ddTrace (default), zipkinMultiHeader, zipkinSingleHeader, traceparent, skywalking, jaeger
enableLinkRUMData boolean No Whether to link with RUM data, default false
enableNativeAutoTrace boolean No Whether to enable native network auto-tracing for iOS NSURLSession, Android OKhttp, default false, Android cloud packaging not supported. Since uniapp network requests are implemented using system APIs on iOS, enabling this will allow automatic tracing of network requests initiated by uniapp on iOS. Please disable manual tracing on iOS to avoid incorrect linkage with RUM data.

RUM User Data Tracking

Currently, RUM data transmission can only be achieved through manual method calls.

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 property parameters</param>
public static void StartAction(string actionName, string actionType, Dictionary<string, object> property)

Code Example

 FTUnityBridge.StartAction("click", "test");

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 property 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 property parameters</param>
public static void StopView(Dictionary<string, object> property)

Code Example

FTUnityBridge.StartView("TEST_VIEW_ONE");

FTUnityBridge.StopView();

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 property 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 property 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">transmission content</param>
/// <param name="netStatus">network metrics 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 property 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 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 task
/// </summary>
/// <param name="log">log content</param>
/// <param name="duration">duration, nanoseconds</param>
/// <param name="property">additional property parameters</param>
/// <returns></returns>
public static async Task AddLongTask(string log, long duration, Dictionary<string, object> property)

Code Example

FTUnityBridge.AddLongTask("long task test", 100002);

Log Printing

Currently, log content is limited to 30 KB, and excess characters 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 property 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

Code Example

FTUnityBridge.AddLog("test log", "test message");

Tracer Network Tracing

Tracing is achieved by generating Trace Headers and adding them 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 unuploaded cache data

/**
 * Clear all data that has not been uploaded to the server.
*/
FTUnityBridge.clearAllData();

Manual Data Sync

When SDKConfig.autoSync is set to true, no additional action is required, and the SDK will sync automatically.

When SDKConfig.autoSync is set to false, you need to manually trigger the data sync method to sync data.

/**
 * Manually sync data. When `FTMobileConfig.autoSync=false`, you need to manually trigger this method to sync 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 Data Binding and Unbinding

Usage

/// <summary>
/// Bind RUM user data
/// </summary>
/// <param name="userId">user unique id</param>
public static async Task BindUserData(string userId)

/// <summary>
/// Bind RUM user data
/// </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 KV assignment, add rules see here

Code Example

FTUnityBridge.BindUserData(new UserData
            {
                userId = "userid",
                userName = "userName",
                userEmail = "[email protected]",
                extra = new Dictionary<string, string>{
                    {"custom_data","custom data"}
                }
            });

FTUnityBridge.UnBindUserdata()

Shutdown SDK

/// <summary>
/// SDK release
/// </summary>

FTUnityBridge.DeInit()

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: Modify a single field value in the data
  • Parameter format: {key: newValue}
  • Example: {"device_uuid": "xxx"} will replace the device_uuid field value in the target data with "xxx"

Single Line Data Modification (lineDataModifier)

  • Function: Modify specified field values in a certain type of data
  • Parameter format: {measurement: {key: newValue}}
  • Example: {"view": {"view_url": "xxx"}} will modify the view_url field value in all view type data to "xxx"
  • measurement data type list:
    • RUM data: view, resource, action, long_task, error
    • Log data: log
  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 natively developed, with some pages or business processes implemented using Unity, the SDK installation and initialization configuration methods are as follows:

// FTSDK.cs
IEnumerator _LoadPrefabs()
{
    yield return Instantiate(MainThreadDispatch);
    //_InitSDK();                                 // Cancel initialization
    yield return Instantiate(ViewObserver);
}

Android

iOS

Frequently Asked Questions

Add Local Variables to Avoid Conflict Fields

To avoid conflicts between custom fields and SDK data, it is recommended to prefix tag names with project abbreviations, e.g., df_tag_name. The key value used in the project can be queried from the source code. When the same variable appears in the SDK global variables and RUM, Log, RUM, Log will overwrite the SDK global variables.

Others