• 1 Unity C# Integration
  • 2 Unity Integration in System Native Layer (Android&iOS)
  • 3 C# interfaces

Unity SDK Integration


This document applies to the latest version, Xbox, PS4, PS5, Switch and Linux platforms can refer to this document to integrate. Android, iOS and Windows platforms is recommended to refer to the stable version of Unity SDK Integration Document

1 Unity C# Integration

1.1 Download and Import Unity Plugin to Unity Project

After creating a project on the platform, the SDK that matches the platform and engine of the project can be downloaded from the "Tutorial" in the sidebar, as shown in the figure below:

1.2 Initialize CrashSight

Choose the first scene or the main scene, and call the following code in a script loaded as early as possible to initialize:

// Debug switch. In the debugging mode, more logs will be printed to locate issues.

#if DEBUG
        CrashSightAgent.ConfigDebugMode (true);
#endif
        CrashSightAgent.ConfigDebugMode (false);

//  Set the target domain name to report to. Please fill in according to project requirements. (required)
        CrashSightAgent.ConfigCrashServerUrl(CrashSightUploadUrl);
// Set the target APP ID for reporting and initialize. You can find the APP ID from More->Product Settings->Product Info of the management console.
        CrashSightAgent.InitWithAppId(CrashSightAppID);

Domain name for reporting

Domestic public cloud:

  • Android: https://android.crashsight.qq.com/pb/async
  • iOS: https://ios.crashsight.qq.com/pb/sync
  • Windows: pc.crashsight.qq.com

Overseas public cloud

  • Android: https://android.crashsight.wetest.net/pb/async
  • iOS: https://ios.crashsight.wetest.net/pb/sync
  • Windows: pc.crashsight.wetest.net

1.3 Integration Configurations for iOS

  • 1)Change the project's preferences in Unity (Build Settings) a. Press Ctrl+Shift+B to open the Build Settings panel. Click Player Settings and switch to the Setting for iOS tab. Choose the Other Settings bar, and change the Script Call Optimization of Optimization to Slow and Safe.
  • 2)Change the compilation configuration of the exported Xcode project. Switch to the Build Phases tab, and add the following dependencies under Link Binary With Libraries:
    • i. libz.dylib is for compressing reported data
    • ii. Security.framework is for storing keychain
    • iii. SystemConfiguratiom.framework is for reading system info in case of an exception
    • iiii. MetricKit.framework for obtaining app diagnostic information provided by apple

Note:

  • i. If these dependencies have been added to the project, no need to add them again.
  • ii. If XUPorter is used to integrate, there's no need to add configuration items in Xcode.

1.4 Unity Integration Demo

  • 1)Double-click the CrashSightPlugin.unitypackage package in the downloaded plugin. The following screen will appear in Unity. Import the plugin.
  • 2) Initialize.
private const string CrashSightAppIDForiOS = "685a68759e";
private const string CrashSightAppIDForAndroid = "e6af377f84";
private const string CrashSightUploadUrliOS = "https://ios.crashsight.qq.com/pb/sync";
private const string CrashSightUploadUrlAndroid = "https://android.crashsight.qq.com/pb/async";

CrashSightAgent.ConfigDebugMode (true);
#if UNITY_IPHONE || UNITY_IOS
        CrashSightAgent.ConfigCrashServerUrl(CrashSightUploadUrliOS);
        CrashSightAgent.InitWithAppId(CrashSightAppIDForiOS);
#elif UNITY_ANDROID
        CrashSightAgent.ConfigCrashServerUrl(CrashSightUploadUrlAndroid);
        CrashSightAgent.InitWithAppId(CrashSightAppIDForAndroid);
#endif
  • 3) Integration for iOS is similar to that of Android, but the project must be packed as an Xcode project and configurations should be done in the Xcode project.

1.5 Integration Result Testing

CrashSight Test Interface

Test Java crash (Android)

static void TestJavaCrash();

Test Object-C crash (iOS)

static void TestOcCrash();

Test Native crash(Android & iOS, will support all platforms in the future)

static void TestNativeCrash();

Test OOM crash (Android、iOS)

static void TestOomCrash();

Test ANR (Android)

static void TestANR();

Test for using memory after release, only effective when GWP_Asan or MTE function is enabled (Android)

static void TestUseAfterFree();

Force Unity to crash (available on all platforms)

UnityEngine.Diagnostics.Utils.ForceCrash(ForcedCrashCategory.AccessViolation);

1.5.1 Testing Method for iOS

  • a. Enable Debug mode. Initialize CrashSight and assign suitable config parameters
  • b. Network and report: Check if "begin to upload <CSAnalyticsLogic" or "cmd: 641" is printed in the test device log
  • c. Crash detection: Check if "Handle the crash scene in callback" is printed in the test device log
  • d. Report exceptions: Check if "begin to upload <CSCrashLogic" or "cmd: 631" is printed in the test device log

1.5.2 Testing Method for Android

  • a. Enable Debug mode. Initialize CrashSight and assign suitable config parameters
  • b. Network and report: Check if "[Upload] Run upload task with cmd: 840" is printed in the logcat log.
  • c. Crash detection: Check if "HandleSignal start" is printed in the logcat log
  • d. Report exception: Check if "[Upload] Run upload task with cmd: 830" is printed in the logcat log.

1.5.3 Testing Method for Windows

  • a.Verify if CrashSight can connect to the internet and report normally. The verification process is:

    1. Initialize CrashSight;
    2. Wait 5 minutes and go to Exception Overview --> Crash Tendency --> Number of Devices Connected in the management console. The stats should be equal to or higher than 1.
  • b.Verify if a crash can be reported normally. The verification process is:

    1. Initialize CrashSight;
    2. You can trigger a crash in the game using the following code. (You can also use other bad memory access methods)
    int* a = 0;
    a[10000] = 5;
    
  • c.See if there is a generated dmp file under TQM64/dump. The crash is not successfully captured if you are unable to find the file. In this case, please contact CrashSight developer.

  • d.Go to "Crash Analysis" in the management console and see if there is a report with the corresponding time stamp. If you see the dmp file in step 3 but are unable to find the report in step 4, the crash was not successfully reported. Please check APPID config (Both config files need to be correct) and the APP KEY config if they correspond to each other and are the same in the application config. If it still fails to report using the correct config, please contact CrashSight developers.

  • e.Check if the version number and the user name of the crash report is the same as the configuration.

  • f.Check if the version number and the user name of the error report is the same as the configuration.

1.6 Upload Symbol Table

The above is an introduction to SDK Integration, crash reporting and verifying, but to see readable restored stacks on the page, you need to upload the corresponding symbol table. Please seeSymbol Table Uploading Tools Guide

2 Unity Integration in System Native Layer (Android&iOS)

2.1 Download and Import Unity Plugin to Unity Project

Download Plugin open in new windowopen in new window(Download is unavailable due to an ongoing internal review. To download it, please contact crashsight@tencent.com), double-click the .unitypackage file in the plugin bundle, import files related to Plugins to the Unity project. (If a plugin bundle of an earlier version is in use, make sure to delete its files.)

2.2 SDK Initialization

Initialize CrashSight in the native layer. The initialization reference code is as follows:
Android:

import com.uqm.crashsight.core.api.crash.UQMCrash;

...
//Fill in the configuration information first, this is only an example
System.loadLibrary("CrashSight");
UQMCrash.configDebugModeBeforeInit(true);//Enable debug
UQMCrash.setUserId("testUserId");//Set user ID
UQMCrash.setAppVersion("testVersion");//Set app version


//Then initialize CrashSight
UQMCrash.configCrashServerUrlBeforeInit("https://android.crashsight.wetest.net/pb/async");
UQMCrash.initWithAppId("******");

iOS:

#include "CrashSight/CrashSightCore.framework/Headers/CrashSightAgent.h"

...
//Fill in the configuration information first, this is only an example, specific configuration interfaces can be found in CrashSightAgent.h
GCloud::CrashSight::CrashSightAgent::ConfigDebugMode(true);//Enable debug
GCloud::CrashSight::CrashSightAgent::SetUserId("testUserId");//Set user ID
GCloud::CrashSight::CrashSightAgent::SetAppVersion("testVersion");//Set app version


//Then initialize CrashSight
GCloud::CrashSight::CrashSightAgent::ConfigCrashServerUrl("https://ios.crashsight.wetest.net/pb/sync");
GCloud::CrashSight::CrashSightAgent::InitWithAppId("******");

2.3 Re-registration for Android

Due to compatibility issues of Unity 5 and later versions, after initializing in the native layer, a re-registration using C# is required for Android. iOS doesn't require it at present. Re-registration function: CrashSightAgent.ReRegistAllMonitors(); Execute this function as early as possible in the C# layer script.

2.4 Report Unity Log Error (Optional)

If the project wants to report Unity Log Error to CrashSight as an error, the feature can be enabled by calling CrashSightAgent.EnableExceptionHandler(); note that the triggering frequency of Unity Log Error in the project should be kept low after enabling the feature.

2.5 Callback in Case of a Crash/an Error (Optional)

If the project wants some content to be added into the report in case of a crash/an error, it can be added by processing callbacks. Note that:

    1. Keep the thread safe during callbacks so that there won't be a second crash. If a second crash happens, the current crash won't be reported this time. If conditions permit, it will be reported the next time the project is activated, but the callback won't be included in the report.
    1. Callback info must comply with compliance requirements.

3 C# interfaces

3.1 Platform-wide interfaces

3.1.1 Initialization

public static void InitWithAppId(string appId);

Note: Execute initialization. Initialize as early as possible to enable crash detection and reporting features. The appid is CrashSight's unique identifier for the item, and can be viewed in Product Settings -> Product Information.
Not available for Win, Xbox, Linux at this time

ParameterTypeNote
appIdstringAPP ID of registered projects

3.1.2 Reporting errors

public static void ReportException(System.Exception e, string message);

Note: Active C# exception reporting

ParameterTypeNote
eSystem.ExceptionCaught exception
messagestringException message
public static void ReportException(string name, string message, string stackTrace);

Note: Proactively report error messages. Can be called manually when an error is caught or needs to be reported, multi-threaded calls are supported. name, message and stackTrace cannot be null.

ParameterTypeNote
namestringException Name
messagestringException message
stackTracestringStack
public static void ReportException(int type, string exceptionName, string exceptionMsg, string exceptionStack, Dictionary<string, string> extInfo, int dumpNativeType = 0, string errorAttachmentPath = "");

Note: Proactively report error messages. Can be called manually when an error is caught or needs to be reported, multi-threaded calls are supported. exceptionName, exceptionMsg and exceptionStack cannot be null.

ParameterTypeNote
typeintException Type, C#: 4, js: 5, lua: 6
exceptionNamestringException Name
exceptionMsgstringException Info
exceptionStackstringStack
extInfoDictionary<string, string>Other Info
dump_native_typeint0: close, 1: call system interface dump, 3: minidump (valid for mobile only)
errorAttachmentPathstringasynchronous (valid for Win, Xbox)

View page:

paramsJson: Crash Details->Download Attachments->extraMessage.txt

Native stack: Crash Details->Download Attachments->trace.zip

Other: time used to report the error

AndroidiOS
Attachment sizeDump stackDo not dump stackDump stackDo not dump stack
100K[0.498881]s[0.003127]s[0.117762]s[0.001172]s
10K[0.464859]s[0.000730]s[0.115362]s[0.000445]s
1K[0.477934]s[0.000189]s[0.117078]s[0.000293]s

3.1.3 Setting user ID

public static void SetUserId(string userId);

Note: Setting user ID. The user id defaults to unknown.

ParameterTypeNote
userIdstringUser ID

3.1.4 Adding custom data

public static void AddSceneData(string key, string value);

Note: Set the Key-Value data customized by the user. It will be reported together with exception info when sending the crash. Each key shouldn't exceed 100 characters, each value shouldn't exceed 1000 characters, and the total length (all keys+all values) shouldn't exceed 64KB for Android, 128KB for iOS.

View page: Crash Details->Download Attachments->valueMapOthers.txt

ParameterTypeNote
keystringKey
valuestringValue

3.1.5 Setting the application version

public static void SetAppVersion(string appVersion);

Note: Set app version number

For Android, the versionName property of AndroidManifest.xml file is used by default

For iOS, configure Info.plist, {CFBundleShortVersionString}.{CFBundleVersion} into the app version number.

Not available for Win, Xbox now

Note: Call it before the InitWithAppId interface.

ParameterTypeNote
appVersionstringVersion Number

3.1.6 Reporting domain name settings

public static void ConfigCrashServerUrl(string crashServerUrl);

Note: Set domain name for reporting.

Not available for Win, Xbox now

Note: Call it before the InitWithAppId interface. The domain name of domestic public environment is as follows:

  • Android: https://android.crashsight.qq.com/pb/async
  • iOS: https://ios.crashsight.qq.com/pb/sync

A direct CrashSight domain name Integration is different from an indirect one using MSDK. Make sure you follow the above domain name to reconfigure. For other environment domain name, please consult the Integration contact.

ParameterTypeNote
crashServerUrlstringTarget domain name of reporting

3.1.7 Set upload log path

public static void SetLogPath(string logPath);

Note: Set an upload path for log after a crash. Read permission is required. On Android and iOS, this interface has a lower priority than logpath callback
Not available for Switch

ParameterTypeNote
logPathstringLog absolute path

3.1.8 Enable Debug

public static void ConfigDebugMode(bool enable);

Note: Whether to enable debugging mode. Off by default. After enabling, some logs will be printed, but it can help locate issues during tests.
Not available for Win、Xbox、Linux

Note: Call it before the InitWithAppId interface.

ParameterTypeNote
enableboolEnabling switch for debugging

3.1.9 Set device id

public static void SetDeviceId(string deviceId);

Note: Set the device ID, by default uuid is used as the device ID
Not available for Win、Xbox、PS4、PS5、Switch

Note: Call it before the InitWithAppId interface.

ParameterTypeNote
deviceIdstringDevice ID

3.1.10 Set custom log reporting level

public static void ConfigCrashReporter(int logLevel);

Note: Set custom log reporting level. Off=0, Error=1, Warn=2, Info=3, Debug=4, default is Warn.
Not available for Win、Xbox、PS4、PS5、Switch、Linux

Note: Call it before the InitWithAppId interface.

ParameterTypeNote
logLevelintLog level

3.1.11 Customize logging

public static void PrintLog(CSLogSeverity level, string format, params object[] args);

Note: The custom log shouldn't exceed 30KB.

ParameterTypeNote
levelCSLogSeverityLog level
formatstringLog format
argsparams object[]variable arguments

Custom log view:
Android, iOS, PS4, PS5, Switch: issue details->tracking log->custom log
Windows, Xbox, Linux: issue details -> custom log (from interface)

3.1.12 Set Callback

public static void RegisterCrashCallback(CrashSightCallback callback);

Note: called in case of a crash. The returned value will be reported along with crash info. Customize the CsCrashCallBack class, inherit CrashSightCallback, and use the OnCrashBaseRetEvent method

public class CsCrashCallBack: CrashSightCallback  {
    // Put you own code to implemente the callback func
    public override string OnCrashBaseRetEvent(int methodId)
    {
        if (methodId == (int)UQMMethodNameID.UQM_CRASH_CALLBACK_EXTRA_MESSAGE)
        {
            //Android, iOS can return extraMessage
            return "this is extra message.";
        }
        else if (methodId == (int)UQMMethodNameID.UQM_CRASH_CALLBACK_NO_RET)
        {
            //Win, Xbox return values are useless, but can perform some actions
        }
        return "";
    }
}

The callback content for Android is on the "Crash Analysis-Trace Data-extraMessage.txt" page. The callback content for iOS is on the "Crash Analysis-Trace Data-crash_attach.log" page.

3.2 Mobile interfaces

3.2.1 Callback switches

public static void ConfigCallbackType(Int32 callbackType);

Note: The callback switches for each type of reporting are currently 5 types of Type, represented by 5 bits. The first bit indicates crash, the second bit indicates anr, the third bit indicates u3d c# error, the fourth bit indicates js, and the fifth bit indicates lua, defaults to full on.

ParameterTypeNote
callbackTypeInt32callback switch

3.2.2 Setting Android phone model

public static void SetDeviceModel(string deviceModel);

Note: Set phone model

Note: Call it before the InitWithAppId interface.

ParameterTypeNote
deviceModelstringPhone model

3.2.3 Reporting lightweight logs

public static void ReportLogInfo(string msgType, string msg);

Note: Reporting lightweight logs

ParameterTypeNote
msgTypestringlog Type
msgstringlog message

3.2.4 Tagging scenes

public static void SetScene(int sceneId);

Note: Set scene id.

ParameterTypeNote
sceneIdintscene ID

3.2.5 Get crash thread ID

public static long GetCrashThreadId();

Note: When a crash occurs, get the crash thread ID and return -1 on failure, can be called in a callback

3.2.6 Set custom device ID

public static void SetCustomizedDeviceID(string deviceId);

Note: Setting a custom device ID

ParameterTypeNote
deviceIdstringcustom device ID

3.2.7 Get SDK-generated device ID

public static string GetSDKDefinedDeviceID();

Note: Get the device ID generated by the SDK

3.2.8 Set custom match ID

public static void SetCustomizedMatchID(string matchId);

Note: Setting a custom match ID. The match id can be used to find crashes and errors in Advanced Search.

ParameterTypeNote
matchIdstringmatch ID

3.2.9 Get SDK-generated session ID

public static string GetSDKSessionID();

Note: Get the session ID generated by the SDK. The session ID is used to uniquely mark a startup and is generally used in callbacks to determine if it is the same startup.

3.2.10 Get crash UUID

public static string GetCrashUuid();

Note: Get the UUID of the current report, the UUID is used to uniquely identify a report, usually used in callbacks.

3.2.11 Set logcat buffer size

public static void SetLogcatBufferSize(int size);

Note: Set logcat buffer size, default 10KB in non-debug mode, 128KB in debug mode

ParameterTypeNote
sizeintlogcat buffer size

3.2.12 Start timed dump

public static void StartDumpRoutine(int dumpMode, int startTimeMode, long startTime, long dumpInterval, int dumpTimes, bool saveLocal, string savePath);

Note: Start a thread to fetch the dump and report it at regular intervals. Depending on the settings of dump interval and number of dumps, there will be some performance overhead, generally used for testing. Please disable this feature before official release.

ParameterTypeNote
dumpModeintdump mode, 1: dump, 2: minidump
startTimeModeintStart time mode, 0: absolute time, 1: relative time, unit: milliseconds
startTimelongstart time
dumpIntervallongDump interval in milliseconds
dumpTimesintNumber of dumps
saveLocalboolWhether to save local
savePathstringLocal Save Path

3.2.13 Get exception type number

public static int getExceptionType(string name);

Note: Get the exception type number based on the string of the exception name, which can be used to fill in the type parameter of the ReportException interface

ParameterTypeNote
namestringException Type name, e.g. "c#", "js", "lua", "custom1", etc.

3.2.14 Restart CrashSight monitoring

public static void ReRegistAllMonitors();

Note: Restart CrashSight monitoring
Valid for Android only

3.2.15 Close CrashSight monitoring

public static void CloseAllMonitors();

Note: Close CrashSight monitoring
Valid for Android only

3.2.16 Set Log Uploading Callback

public static void RegisterCrashLogCallback(CrashSightLogCallback callback);

Note: Called after handling a crash. Customize the CsCrashLogCallback class, inherit CrashSightLogCallback, and use OnSetLogPathEvent and OnLogUploadResultEvent methods

public class CsCrashLogCallBack : CrashSightLogCallback
{
    // Returns the log file's absolute path
    // methodId Method ID. The business can ignore it
    // crashType Crash type, 0: Java/Objective-C crash, 2: native crash
    public override string OnSetLogPathEvent(int methodId, int crashType)
    {
        return "";
    }

    // Shows the result of log file uploading
    // methodId Method ID. The business can ignore it
    // result Result of uploading 0: successful, other: failed
    public override void OnLogUploadResultEvent(int methodId, int crashType, int result)
    {
        
    }
}

The callback content for Android is on the "Crash Analysis-Trace Data-Client Uploading Log" page. The callback content for iOS is on the "Crash Analysis-Trace Data-Client Uploading Log" page.

3.3 PC, Xbox interfaces

3.3.1 Enable Veh exception handling

public static void SetVehEnable(bool enable);

Note: VEH capture switch, on by default. It is recommended to turn off this switch for all Unity projects, otherwise it may generate crash false positives.

ParameterTypeNote
enableboolVeh Exception Handler Switch

3.3.2 Proactive crash reporting

public static void ReportCrash();

Note: Report a Crash. There are generally no usage scenarios, and can be used at your discretion depending on the needs of your project.

3.3.3 Proactive Dump Reporting

public static void ReportDump(string dump_path, bool is_async);

Note: Active Dump reporting. generally no use scenarios, can be used as appropriate according to the needs of the project.

ParameterTypeNote
dump_pathstringdump path
is_asyncboolAsynchronous or not

3.3.4 Enable additional exception catching

public static void SetExtraHandler(bool extra_handle_enable);

Note: Set additional exception handling mechanism, default is off, consistent with old version. When turned on, it can catch crashes caused by illegal arguments thrown by safe functions such as strcpy_s, as well as crashes caused by purecall errors in dummy function calls.

ParameterTypeNote
extra_handle_enableboolAdditional Exception Handler Switch

3.3.5 Upload dump file

public static void UploadGivenPathDump(string dump_dir, bool is_extra_check);

Note: Upload the dump file in the specified path.

ParameterTypeNote
dump_dirstringDump file path
is_extra_checkboolJust fill in false by default

3.4 PS4, PS5, Switch interfaces

3.4.1 Setting the error reporting interval

public static void SetErrorUploadInterval(int interval);

Note: Setting the error reporting interval, the default is 30s.

ParameterTypeNote
intervalintError Reporting Interval

3.4.2 Error Reporting Switch

public static void SetErrorUploadEnable(bool enable);

Note: Whether to enable error reporting, the default is on.

ParameterTypeNote
enableboolError Reporting Switch

3.5 Linux interfaces

3.5.1 Set path to all log files

public static void SetRecordFileDir(string record_dir);

Note: Set the path to all log files, including SDK logs and dump files, defaults to the directory of the current executable.

ParameterTypeNote
record_dirstringRecord file path
Last Updated: