Unity Application Integration¶
Prerequisites¶
Note: If you have enabled the RUM Headless service, the prerequisites have been automatically configured for you, and you can directly integrate the application.
- Install DataKit.
- Configure the RUM Collector.
- Configure DataKit to be accessible over the public network and install the IP Geolocation Database.
Application Integration¶
- Go to User Access Monitoring > Create Application > Android/iOS.
- Create two applications for Unity Android and Unity iOS respectively to receive RUM data from Android and iOS platforms.
- Enter the corresponding application name and application ID for each platform's application.
- 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
- 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 binding script
├── FTSDK.prefab // SDK initialization prefab
├── FTUnityBridge.cs // Unity bridge for connecting iOS, Android, and other platform methods
├── FTViewObserver.cs // FTViewObserver.prefab binding script
├── FTViewObserver.prefab // View page monitoring prefab
├── UnityMainThreadDispatcher.cs // UnityMainThreadDispatcher.prefab binding script
├── UnityMainThreadDispatcher.prefab // Main thread consumption queue prefab
Asserts
->Import Package
->Custom Package...
to 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
FTSDK.prefab
to the first scene page, and initialize the SDK in the_InitSDK
method inFTSDK.cs
. If the native Android and iOS projects have already integrated the native SDK, you need to comment out the_InitSDK
method to avoid duplicate settings. - Drag
FTViewObserver.prefab
to other scene pages to achieve pageView
lifecycle monitoring, including application sleep and wake-up. - Use
Application.logMessageReceived
to monitor and convert Unity crash data and regular log data, seeFTSDK.cs
OnEnable
OnDisable
methods.
Note: If you have already integrated the native SDK Android gson-2.8.5.jar, ft-sdk-release.aar, iOS FTMobileSDK.framework, you can remove them from the project. In addition, Android Okhttp requests and startup time-consuming functions require the use of ft-plugin. For detailed configuration, please refer to 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, the default port is 9529, the device installing the SDK needs to be able to access this address. Note: Only one of datakitUrl and datawayUrl can be configured |
datawayUrl | string | Yes | Public Dataway reporting URL address, obtained from the [User Access Monitoring] application, example: https://open.dataway.url, the device installing the SDK needs to be able to access this address. Note: Only one of datakitUrl and datawayUrl can be configured |
clientToken | string | Yes | Authentication token, needs to be used together with datawayUrl |
debug | boolean | No | Set whether to allow printing Debug logs, default false |
env | string | No | Environment, default prod , any character, it is recommended to use a single word, such as test etc. |
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 synchronize 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 synchronization requests. Range [5,). Note: The larger the number of request entries, the more computing resources are used for data synchronization, default is 10 |
syncSleepTime | number | No | Set the synchronization interval time. Range [0,5000], default is not set |
enableDataIntegerCompatible | boolean | No | It is recommended to enable this when coexisting with web data. This configuration is used to handle web data type storage compatibility issues. Enabled by default in SDK 1.1.0 and later versions |
compressIntakeRequests | boolean | No | Compress the uploaded synchronization data with deflate, default is off, supported in SDK 1.1.0 and later versions |
enableLimitWithDbSize | boolean | No | Enable using db to limit data size, default is 100MB, unit is Byte, the larger the database, the greater the disk pressure, default is off. Note: After enabling, the Log configuration logCacheLimitCount and RUM configuration rumCacheLimitCount will be invalid. Supported in SDK 1.1.0 and later versions |
dbCacheLimit | number | No | DB cache limit size. Range [30MB,), default is 100MB, unit is byte, supported in SDK 1.1.0 and later versions |
dbDiscardStrategy | string | No | Set the data discard rules in the database. Discard strategy: discard discard new data (default), discardOldest discard old data. Supported in SDK 1.1.0 and later versions |
dataModifier | object | No | Modify a single field. Supported in SDK 1.1.0 and later, see example here |
lineDataModifier | object | No | Modify a single piece of data. Supported in SDK 1.1.0 and later, see example here |
RUM Configuration¶
FTUnityBridge.InitRUMConfig(new RUMConfig()
{
androidAppId = "androidAppId",
iOSAppId = "iOSAppId",
sampleRate = 0.8f,
});
Field | Type | Required | Description |
---|---|---|---|
androidAppId | string | Yes | Corresponding RUM appid , only then will the RUM collection function be enabled, get appid method |
iOSAppId | string | Yes | Corresponding RUM appid , only then will the RUM collection function be enabled, get appid method |
sampleRate | float | No | Sampling rate, range [0,1], 0 means no collection, 1 means full collection, default is 1. Scope is all View, Action, LongTask, Error data under the same session_id |
sessionOnErrorSampleRate | float | No | Set the error collection rate, when the 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 is 0. Scope is 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 is false , Android cloud packaging is not supported |
enableNativeUserResource | boolean | No | Whether to automatically track Native Resource , default is false , Android cloud packaging is not supported. Since uniapp network requests on iOS are implemented using system API, all resource data on iOS can be collected after enabling, please disable manual collection on iOS to prevent duplicate data collection. |
enableNativeUserView | boolean | No | Whether to automatically track Native View , pure uni-app applications are recommended to turn off, default is false |
errorMonitorType | string/array | No | Error monitoring supplement types: all , battery , memory , cpu , default is not set |
deviceMonitorType | string/array | No | Page monitoring supplement types: all , battery (only supported on Android), memory , cpu , fps , default is not set |
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. Scope: only affects the default collection when enableNativeUserResource is true. iOS: supported on >= iOS 13 . Android: single Okhttp has an IP caching mechanism for the same domain, the same OkhttpClient , under the condition that the server IP does not change, will only generate once. |
enableTrackNativeCrash | boolean | No | Whether to enable Android Java Crash and OC/C/C++ crash monitoring, default is `false |
enableTrackNativeAppANR | boolean | No | Whether to enable Native ANR monitoring, default is false |
enableTrackNativeFreeze | boolean | No | Whether to automatically track Native Freeze , default is false |
nativeFreezeDurationMs | number | No | Set the threshold for collecting Native Freeze lag, range [100,), unit is milliseconds. iOS default is 250ms, Android default is 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 is 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 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 be filled with log levels: info prompt, warning warning, error error, critical , ok recovery |
globalContext | object | No | Custom global parameters |
logCacheLimitCount | number | No | Local cache maximum log entry count limit [1000,), the larger the log, the greater the disk cache pressure, default is 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 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 auto-tracing iOS NSURLSession , Android OKhttp , default false , Android cloud packaging is not supported. Since uniapp network requests on iOS are implemented using system API, uniapp initiated network requests on iOS can be automatically traced after enabling, please disable manual trace on iOS to prevent trace and RUM data association errors. |
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¶
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¶
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">data 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 | return 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¶
Log Logging¶
Currently, the log content is limited to 30 KB, and any 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 | prompt |
warning | warning |
error | error |
critical | critical |
ok | recovery |
Code Example¶
Tracer Network Trace¶
Trace is achieved by generating Trace Header and then adding the Header to the http request header.
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
Active Data Synchronization¶
When configuring SDKConfig.autoSync
to true
, no additional operations are required, the SDK will automatically synchronize.
When configuring SDKConfig.autoSync
to false
, you need to actively trigger the data synchronization method to synchronize data.
/**
* Actively synchronize data, when configuring `FTMobileConfig.autoSync=false`, you need to actively trigger this method 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 | user name |
userEmail | string | No | user email |
extra | dictionary | No | KV assignment, add 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()
Shut Down 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, it is recommended to use SDKConfig.lineDataModifier
.
Single Field Modification (dataModifier)
- Function: Modify a single field value in the data
- Parameter format:
{key: newValue}
- Example:
{"device_uuid": "xxx"}
will replace thedevice_uuid
field value in the target data with "xxx"
Single Data Data Change (lineDataModifier)
- Function: Modify a specified field value in a certain type of data
- Parameter format:
{measurement: {key: newValue}}
- Example:
{"view": {"view_url": "xxx"}}
will modify theview_url
field value in allview
type data to "xxx" measurement
data 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 native development, and some pages or business processes use Unity, the SDK installation and initialization configuration methods are as follows:
-
Installation: Installation method remains unchanged
-
Initialization: Please refer to iOS SDK Initialization Configuration, Android SDK Initialization Configuration for initialization configuration in the native project
- Cancel the original initialization part in
Unity SDK
FTSDK.cs
to 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 Local Variables to Avoid Conflict Fields¶
To avoid conflicts between custom fields and SDK data, it is recommended to add project abbreviation prefixes to tag names, such as 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 variable and RUM, Log, RUM, Log will overwrite the global variable in the SDK.