Методы API Ключ-АСТРОМ OpenKit

Материал из Документация Ключ-АСТРОМ
Версия от 21:57, 19 января 2026; IKuznetsov (обсуждение | вклад) (Новая страница: «Ключ-АСТРОМ '''OpenKit''' предлагает ряд '''API'''-методов, позволяющих интегрировать '''OpenKit''' в ва...»)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)

Ключ-АСТРОМ OpenKit предлагает ряд API-методов, позволяющих интегрировать OpenKit в ваше приложение. В разделах ниже описано, как использовать каждый из этих методов OpenKit.

Получение экземпляра OpenKit

Для получения нового экземпляра OpenKit используйте команду astromkeyOpenKitBuilder.

Java .NET
String applicationID = "application-id";

long deviceID = Util.getDeviceID();

String endpointURL = "https://tenantid.beaconurl.com/mbeacon";

OpenKit openKit = new astromkeyOpenKitBuilder(endpointURL, applicationID, deviceID).build();

string applicationID = "application-id";

long deviceID = Util.GetDeviceID();

string endpointURL = "https://tenantid.beaconurl.com/mbeacon";

IOpenKit openKit = new astromkeyOpenKitBuilder(endpointURL, applicationID, deviceID).Build();

C++ C
const char* applicationID = "application-id";

int64_t deviceID = Util::GetDeviceID();

const char* endpointURL = "https://tenantid.beaconurl.com/mbeacon";

std::shared_pointer<openkit::IOpenKit> openKit =

    openkit::astromkeyOpenKitBuilder(endpointURL, applicationID, deviceID).build();

const char* applicationID = "application-id";

int64_t deviceID = GetDeviceID();

const char* endpointURL = "https://tenantid.beaconurl.com/mbeacon";

struct OpenKitConfigurationHandle* configurationHandle = createOpenKitConfiguration(endpointURL, applicationID, deviceID);

struct OpenKitHandle* openKitHandle = createastromkeyOpenKit(configurationHandle);

destroyOpenKitConfiguration(configurationHandle);

JavaScript
const applicationID: string = 'application-id';

const deviceID: number = Util.getDeviceID();

const endpointURL: string = 'https://tenantid.beaconurl.com/mbeacon';

const openkit = new OpenKitBuilder(endpointURL, applicationID, deviceID).build();

  • endpointURL - это конечная точка Ключ-АСТРОМ, с которой взаимодействует OpenKit. URL-адрес конечной точки можно найти в настройках вашего пользовательского приложения. Дополнительную информацию см. в разделе Инструментирование приложения с помощью Ключ-АСТРОМ OpenKit.
  • applicationID - это уникальный идентификатор приложения. Идентификатор приложения можно найти в пользовательских настройках приложения. Дополнительную информацию см. в разделе Инструментирование приложения с помощью Ключ-АСТРОМ OpenKit.
  • deviceID - это уникальный идентификатор, который можно использовать для однозначной идентификации устройства.

В дополнение к обязательным параметрам, описанным выше, конструктор предоставляет дополнительные методы для дальнейшей настройки OpenKit. К ним относится информация, специфичная для устройства, такая как операционная система, производитель или идентификатор модели.

Java
Название метода Описание Значение по умолчанию Доступно с версии
withApplicationVersion Устанавливает версию приложения. OpenKit version 1.0.1
withOperatingSystem Задает название операционной системы. OpenKit <OpenKit version> 1.0.1
withManufacturer Устанавливает производителя astromkey 1.0.1
withModelID Устанавливает идентификатор модели. OpenKitDevice 1.0.1
withBeaconCacheMaxRecordAge Устанавливает максимальный срок хранения записей в кэше в миллисекундах. 1 h 45 min 1.0.1
withBeaconCacheLowerMemoryBoundary Устанавливает нижнюю границу памяти кэша в байтах. 80 MB 1.0.1
withBeaconCacheUpperMemoryBoundary Устанавливает верхнюю границу памяти кэша в байтах. 100 MB 1.0.1
withLogger Устанавливает пользовательский вариант Logger, заменяя текущий. DefaultLogger 1.0.1
withTrustManager Устанавливает пользовательский вариант SSLTrustManager, заменяя текущий. SSLStrictTrustManager 1.0.1
withDataCollectionLevel Устанавливает уровень сбора данных. DataCollectionLevel.USER_BEHAVIOR 1.1.0
withCrashReportingLevel Устанавливает уровень сообщения о сбоях. CrashReportingLevel.OPT_IN_CRASHES 1.1.0
withLogLevel Устанавливает уровень логирования по умолчанию при использовании встроенного регистратора. LogLevel.WARN 2.0.0
withHttpRequestInterceptor Устанавливает перехватчик для запросов к бэкэндам Ключ-АСТРОМ. NullHttpRequestInterceptor 2.2.0
withHttpResponseInterceptor Устанавливает перехватчик для ответов, полученных от бэкэндов Ключ-АСТРОМ. NullHttpResponseInterceptor 2.2.0
.NET
Название метода Описание Значение по умолчанию Доступно с версии
WithApplicationVersion Устанавливает версию приложения. OpenKit version 1.0.1
WithOperatingSystem Задает название операционной системы. OpenKit <OpenKit version> 1.0.1
WithManufacturer Устанавливает производителя astromkey 1.0.1
WithModelID Устанавливает идентификатор модели. OpenKitDevice 1.0.1
WithBeaconCacheMaxRecordAge Устанавливает максимальный срок хранения записей в кэше в миллисекундах. 1 h 45 min 1.0.1
WithBeaconCacheLowerMemoryBoundary Устанавливает нижнюю границу памяти кэша в байтах. 80 MB 1.0.1
WithBeaconCacheUpperMemoryBoundary Устанавливает верхнюю границу памяти кэша в байтах. 100 MB 1.0.1
WithLogger Устанавливает пользовательский вариант ILogger, заменяя текущий. DefaultLogger 1.0.1
WithTrustManager Устанавливает пользовательский вариант ISSLTrustManager, заменяя текущий. SSLStrictTrustManager 1.0.1
WithDataCollectionLevel Устанавливает уровень сбора данных. DataCollectionLevel.USER_BEHAVIOR 1.1.0
WithCrashReportingLevel Устанавливает уровень сообщения о сбоях. CrashReportingLevel.OPT_IN_CRASHES 1.1.0
WithLogLevel Устанавливает уровень логирования по умолчанию при использовании встроенного регистратора. LogLevel.WARN 2.0.0
WithHttpRequestInterceptor Устанавливает перехватчик для запросов к бэкэндам Ключ-АСТРОМ. NullHttpRequestInterceptor 2.2.0
WithHttpResponseInterceptor Устанавливает перехватчик для ответов, полученных от бэкэндов Ключ-АСТРОМ. NullHttpResponseInterceptor 2.2.0
C++
Название метода Описание Значение по умолчанию Доступно с версии
withApplicationVersion Устанавливает версию приложения. OpenKit version 1.0.0
withOperatingSystem Задает название операционной системы. OpenKit <OpenKit version> 1.0.0
withManufacturer Устанавливает производителя astromkey 1.0.0
withModelID Устанавливает идентификатор модели. OpenKitDevice 1.0.0
withBeaconCacheMaxRecordAge Устанавливает максимальный срок хранения записей в кэше в миллисекундах. 1 h 45 min 1.0.0
withBeaconCacheLowerMemoryBoundary Устанавливает нижнюю границу памяти кэша в байтах. 80 MB 1.0.0
withBeaconCacheUpperMemoryBoundary Устанавливает верхнюю границу памяти кэша маяков в байтах. 100 MB 1.0.0
withLogger Устанавливает пользовательский вариант ILogger, заменяя текущий. DefaultLogger 1.0.0
withTrustManager Устанавливает пользовательский вариант ISSLTrustManager, заменяя текущий. SSLStrictTrustManager 1.0.0
withDataCollectionLevel Устанавливает уровень сбора данных. DataCollectionLevel::USER_BEHAVIOR 1.0.0
withCrashReportingLevel Устанавливает уровень сообщения о сбоях. CrashReportingLevel::OPT_IN_CRASHES 1.0.0
withLogLevel Устанавливает уровень логирования по умолчанию при использовании встроенного регистратора. LogLevel.WARN 2.0.0
withHttpRequestInterceptor Устанавливает перехватчик для запросов к бэкэндам Ключ-АСТРОМ. NullHttpRequestInterceptor 2.2.0
withHttpResponseInterceptor Устанавливает перехватчик для ответов, полученных от бэкэндов Ключ-АСТРОМ. NullHttpResponseInterceptor 2.2.0
C
Название метода Описание Значение по умолчанию Доступно с версии
useApplicationVersionForConfiguration Устанавливает версию приложения. OpenKit version 1.0.0
useOperatingSystemForConfiguration Задает название операционной системы. OpenKit <OpenKit version> 1.0.0
useManufacturerForConfiguration Устанавливает производителя astromkey 1.0.0
useModelIDForConfiguration Устанавливает идентификатор модели. OpenKitDevice 1.0.0
useBeaconCacheBehaviorForConfiguration Задает режим кэширования для кэша. Время хранения: 1 ч 45 мин, нижний предел памяти: 80 МБ, верхний предел памяти: 100 МБ. 1.0.0
useLoggerForConfiguration Устанавливает пользовательский вариант ILogger, заменяя текущий. В качестве резервного варианта используется логгер по умолчанию, который ведет ведение логов в stdout. 1.0.0
useTrustModeForConfiguration Устанавливает пользовательский вариант ISSLTrustManager, заменяя текущий. STRICT_TRUST 1.0.0
useDataCollectionLevelForConfiguration Устанавливает уровень сбора данных. DATA_COLLECTION_LEVEL_USER_BEHAVIOR 1.0.0
useCrashReportingLevelForConfiguration Устанавливает уровень сообщения о сбоях. CRASH_REPORTING_LEVEL_OPT_IN_CRASHES 1.0.0
useDefaultLogLevelForConfiguration Устанавливает уровень логирования по умолчанию при использовании встроенного регистратора. LogLevel.WARN 2.0.0
useHttpRequestInterceptorForConfiguration Устанавливает перехватчик для запросов к бэкэндам Ключ-АСТРОМ. NullHttpRequestInterceptor 2.2.0
useHttpResponseInterceptorForConfiguration Устанавливает перехватчик для ответов, полученных от бэкэндов Ключ-АСТРОМ. NullHttpResponseInterceptor 2.2.0
JavaScript
Название метода Описание Значение по умолчанию Доступно с версии
withApplicationVersion Устанавливает версию приложения. OpenKit version 1.0.0
withOperatingSystem Задает название операционной системы. OpenKit <OpenKit version> 1.0.0
withManufacturer Устанавливает производителя astromkey 1.0.0
withModelID Устанавливает идентификатор модели. OpenKitDevice 1.0.0
withUserLanguage Устанавливает язык пользователя 1.0.0
withScreenResolution Устанавливает разрешение экрана. 1.0.0
withScreenOrientation Задает ориентацию экрана. 1.0.0
withCommunicationChannel Устанавливает канал связи HttpCommunicationChannel 1.0.0
withRandomNumberProvider Задает провайдера случайных чисел DefaultRandomNumberProvider 1.0.0
withLoggerFactory Задает параметры логгера. ConsoleLoggerFactory 1.0.0
withDataCollectionLevel Устанавливает уровень сбора данных. 2 (User Behavior) 1.0.0
withCrashReportingLevel Устанавливает уровень сообщения о сбоях. 2 (OptIn) 1.0.0
withLogLevel Устанавливает уровень логирования по умолчанию при использовании встроенного регистратора. LogLevel.Info 1.0.0

Безопасность SSL/TLS

Вся связь OpenKit с бэкэндом осуществляется по протоколу HTTPS. По умолчанию OpenKit ожидает наличия действительных серверных сертификатов. Однако при необходимости проверку сертификатов можно обойти. Для этого можно настроить собственный менеджер доверия с помощью конструктора.

Мы не рекомендуем обходить проверку сертификатов TLS/SSL-сервера, поскольку это позволяет осуществлять атаки типа «man-in-the-middle».
Java .NET
class MyCustomTrustManager implements SSLTrustManager {

    // implement interface methods

}

SSLTrustManager trustManager = new MyCustomTrustManager()

OpenKit openKit = new astromkeyOpenKitBuilder(endpointURL, applicationID, deviceID)

    .withTrustManager(trustManager)

    .build();

class MyCustomTrustManager : ISSLTrustManager

{

    // implement interface methods

}

ISSLTrustManager trustManager = new MyCustomTrustManager()

OpenKit openKit = new astromkeyOpenKitBuilder(endpointURL, applicationID, deviceID)

    .WithTrustManager(trustManager)

    .Build();

C++ C
class MyCustomTrustManager : public openkit::ISSLTrustManager

{

    // implement interface methods

};

std::shared_ptr<openkit::ISSLTrustManager> trustManager = std::make_shared<MyCustomTrustManager>()

OpenKit openKit = new astromkeyOpenKitBuilder(endpointURL, applicationID, deviceID)

    .withTrustManager(trustManager)

    .build();

void applySslOptions(CURL* curl)

{

    // set CURL options accordingly

}

struct TrustManagerHandle* trustManager = createCustomTrustManager(&applySslOptions);

// create OpenKit configuration and assign custom trust manager

struct OpenKitConfigurationHandle* configurationHandle = createOpenKitConfiguration(endpointURL, applicationID, deviceID);

useTrustModeForConfiguration(configurationHandle, CUSTOM_TRUST, trustManager);

// create OpenKit instance

struct OpenKitHandle* openKitHandle = createastromkeyOpenKit(configurationHandle);

JavaScript
class MyCustomTrustCommunicationChannel implements CommunicationChannel {

    // implement interface methods

}

const trustCommunicationChannel = new MyCustomTrustCommunicationChannel();

const openkit = new OpenKitBuilder(endpointURL, applicationID, deviceID)

    .withCommunicationChannel(trustCommunicationChannel)

    .build();

Включение подробного логирования

По умолчанию OpenKit использует реализацию логгера, которая записывает логи в файл stdout. Если используется стандартный логгер, вы можете включить подробное логирование с помощью команды astromkeyOpenKitBuilder. В режиме подробного логирования записываются информационные и отладочные сообщения.

Вы также можете настроить собственный регистратор событий. Подробнее см. раздел Регистрация событий в Ключ-АСТРОМ OpenKit.

Инициализация OpenKit

При получении экземпляра OpenKit от сборщика запускается этап автоматической инициализации. По умолчанию инициализация выполняется асинхронно.

Могут возникнуть ситуации, когда необходимо убедиться в завершении инициализации перед продолжением выполнения программной логики, например, в случае кратковременных приложений, где корректная инициализация и завершение работы не могут быть гарантированы. Для таких приложений OpenKit позволяет ожидать завершения инициализации двумя способами:

  • С таймаутом : вызывающие потоки ожидают заданное время инициализации OpenKit. Метод возвращает значение false, если таймаут истек или за это время было выполнено завершение работы, а также true указывает на успешную инициализацию.
  • Без таймаута : Вызывающий поток блокируется до инициализации OpenKit. В случае неправильной конфигурации это может привести к бесконечной блокировке вызывающего потока. Возвращаемое значение указывает, был ли инициализирован экземпляр OpenKit или же было выполнено завершение работы.
Java .NET
// wait until the OpenKit instance is fully initialized

boolean success = openKit.waitForInitCompletion();

// wait up to 10 seconds for OpenKit to complete initialization

long timeoutInMilliseconds = 10 * 1000;

boolean success = openKit.waitForInitCompletion(timeoutInMilliseconds);

// wait until the OpenKit instance is fully initialized

bool success = openKit.WaitForInitCompletion();

// wait up to 10 seconds for OpenKit to complete initialization

int timeoutInMilliseconds = 10 * 1000;

bool success = openKit.WaitForInitCompletion(timeoutInMilliseconds);

C++ C
// wait until the OpenKit instance is fully initialized

bool success = openKit->waitForInitCompletion();

// wait up to 10 seconds for OpenKit to complete initialization

int64_t timeoutInMilliseconds = 10 * 1000;

bool success = openKit->waitForInitCompletion(timeoutInMilliseconds);

// wait until the OpenKit instance is fully initialized

bool success = waitForInitCompletion(openKit);

// wait up to 10 seconds for OpenKit to complete initialization

int64_t timeoutInMilliseconds = 10 * 1000;

bool success = waitForInitCompletionWithTimeout(openKit, timeoutInMilliseconds);

JavaScript
// wait until the OpenKit instance is fully initialized

openKit.waitForInit((initializedSuccessfully) => {});

// wait up to 10 seconds for OpenKit to complete initialization

const timeoutInMilliseconds = 10 * 1000;

openKit.waitForInit(() => {}, timeoutInMilliseconds);


Кроме того, OpenKit позволяет проверить, была ли она инициализирована.

Java .NET
boolean isInitialized = openKit.isInitialized();

if (isInitialized) {

    System.out.println("OpenKit is initialized");

} else {

    System.out.println("OpenKit is not yet initialized");

}

bool isInitialized = openKit.IsInitialized;

if (isInitialized)

{

    Console.WriteLine("OpenKit is initialized");

}

else

{

    Console.WriteLine("OpenKit is not yet initialized");

}

C++ C
bool isInitialized = openKit->isInitialized();

if (isInitialized)

{

    std::cout << "OpenKit is initialized" << std::endl;

}

else

{

    std::cout << "OpenKit is not yet initialized" << std::endl;

}

bool isInitialized = isInitialized(openKit);

if (isInitialized)

{

    printf("OpenKit is initialized\n");

}

else

{

    printf("OpenKit is not yet initialized\n");

}

JavaScript
const isInitialized = openKit.isInitialized();

if (isInitialized) {

    console.log('OpenKit is initialized');

} else {

    console.log('OpenKit is not yet initialized');

}

Создание сессии

Вы можете создать новую сессию, используя экземпляр OpenKit, полученный из конструктора. При создании новой сессии вы также можете указать IP-адрес.

  • Если указан действительный IPv4 или IPv6 адрес, он назначается сессии.
  • Если IP-адрес не указан или указан недействительный IP-адрес, IP-адрес сессии определяется автоматически и назначается на стороне сервера.
Java .NET
// create a session and pass an IP address

String clientIPAddress = "12.34.56.78";

Session sessionWithArgument = openKit.createSession(clientIPAddress);

// create a session and let the IP be assigned on the server side

// this overloaded method is available since OpenKit Java 1.4.0

Session sessionWithoutArgument = openKit.createSession();

// create a session and pass an IP address

string clientIPAddress = "12.34.56.78";

ISession sessionWithArgument = openKit.CreateSession(clientIPAddress);

// create a session and let the IP be assigned on the server side

// this overloaded method is available since OpenKit .NET 1.4.0

ISession sessionWithoutArgument = openKit.CreateSession();

C++ C
// create a session and pass an IP address

const char* clientIPAddress = "12.34.56.78";

std::shared_ptr<openkit::ISession> sessionWithArgument = openKit->createSession(clientIPAddress);

// create a session and let the IP be assigned on the server side

// this overloaded method is available since OpenKit Native 1.1.0

std::shared_ptr<openkit::ISession> sessionWithoutArgument = openKit->createSession();

// create a session and pass an IP address

const char* clientIPAddress = "12.34.56.78";

SessionHandle* sessionWithArgument = createSession(openKit, clientIPAddress);

// create a session and let the IP be assigned on the server side

// this function is available since OpenKit Native 1.1.0

SessionHandle* sessionWithoutArgument = createSessionWithAutoIpDetermination(openKit);

JavaScript
// create a session and pass an IP address

const clientIPAddress = "12.34.56.78";

const sessionWithArgument = openKit.createSession(clientIpAddress);

// create a session and let the IP be assigned on the server side

const sessionWithoutArgument = openKit.createSession();

Отметка конкретных пользователей

Вы можете пометить пользователя, назначенного на сессию. Это позволяет искать и фильтровать сессии конкретных пользователей, а также анализировать индивидуальное поведение пользователей с течением времени в административной панели.

Java session.identifyUser("jane.doe@example.com");
.NET session.IdentifyUser("jane.doe@example.com");
C++ session->identifyUser("jane.doe@example.com");
C identifyUser(session, "jane.doe@example.com");
JavaScript session.identifyUser("jane.doe@example.com");

Завершение сессии

Когда сессия больше не нужна, её следует завершить. Хотя все открытые сессии автоматически завершаются при выключении OpenKit, настоятельно рекомендуется завершать сессии, которые больше не используются, вручную.

Java session.end();

session = null; // not needed, just used to indicate that the session is no longer valid.

.NET session.End();

session = null; // not needed, just used to indicate that the session is no longer valid.

C++ session->end();

session = nullptr; // not needed, just used to indicate that the session is no longer valid.

C endSession(session);

session = NULL; // good pratice, as the allocated memory is freed in endSession

JavaScript session.end();

Сообщить о сбоях

Вы можете сообщать о неожиданных сбоях приложения в рамках сессии. Подробная информация о сбое отправляется сразу после того, как вы сообщите о нем.

Java .NET
private static int div(int numerator, int denominator) {

    return numerator / denominator;

}

public static void divWithCrash() {

    int numerator = 5;

    int denominator = 0;

    try {

        System.out.println("Got: " + div(numerator, denominator));

    } catch (Exception e) {

        String errorName = e.getClass().getName();

        String reason = e.getMessage();

        String stackTrace = getStackTraceAsString(e); // get the stacktrace as string, similar as e.printStackTrace()

        // and now report the application crash via the session

        session.reportCrash(errorName, reason, stackTrace);

    }

}

private static int Div(int numerator, int denominator)

{

    return numerator / denominator;

}

public static void DivWithCrash()

{

    int numerator = 5;

    int denominator = 0;

    try

    {

        Console.WriteLine("Got: " + Div(numerator, denominator));

    }

    catch (Exception e)

    {

        string errorName = e.GetType().ToString();

        string reason = e.Message;

        string stackTrace = e.StackTrace;

        // and now report the application crash via the session

        session.ReportCrash(errorName, reason, stackTrace);

    }

}

C++ C
static int32_t div(int32_t numerator, int32_t denominator)

{

    if (denominator == 0)

    {

        throw std::logic_error("Division by zero");

    }

    return numerator / denominator;

}

static void divWithCrash()

{

    int32_t numerator = 5;

    int32_t denominator = 0;

    try

    {

        int32_t result = div(numerator, denominator);

        std::cout << "Got: " << result << std::endl;

    }

    catch (std::logic_error& e)

    {

        const char* errorName = "std::logic_error"; // if RTTI is enabled, typeid could be used

        const char* reason = e.what();

        const char* stackTrace = nullptr; // use a valid const char* if a stack trace can be generated

        // and now report the application crash via the session

        session->reportCrash(errorName, reason, stackTrace);

    }

}

const char* errorName = "application crash";

const char* reason = "some reason indicator";

const char* stackTrace = NULL; // use a valid const char* if a stack trace can be generated

// and now report the application crash via the session

reportCrash(session, errorName, reason, stackTrace);

JavaScript
const error = new Error('Some error');

// and now report the application crash via the session

session.reportCrash(e.name, e.message, e.stack);

Создание пользовательских и дочерних действий

Вы можете определять и сообщать о пользовательских действиях. После создания пользовательского действия вы можете добавить к нему дочернее действие или дополнить действие дополнительной информацией, прежде чем окончательно его закрыть. Пользовательские действия следует создавать из сессии, а дочерние действия — из пользовательского действия.

Java String rootActionName = "rootActionName";

String childActionName = "childActionName";

// create a custom action for a session

RootAction rootAction = session.enterAction(rootActionName);

// create a child action for the custom action

Action childAction = rootAction.enterAction(childActionName);

.NET string rootActionName = "rootActionName";

string childActionName = "childActionName";

// create a custom action for a session

IRootAction rootAction = session.EnterAction(rootActionName);

// create a child action for the custom action

IAction childAction = rootAction.EnterAction(childActionName);

C++ const char* rootActionName = "rootActionName";

const char* childActionName = "childActionName";

// create a custom action for a session

std::shared_ptr<openkit::IRootAction> rootAction = session->enterAction(rootActionName);

// create a child action for the custom action

std::shared_ptr<openkit::IAction> childAction = rootAction->enterAction(childActionName);

C const char* rootActionName = "rootActionName";

const char* childActionName = "childActionName";

// create a custom action for a session

RootActionHandle* rootAction = enterRootAction(session, rootActionName);

// create a child action for the custom action

ActionHandle* childAction = enterAction(rootAction, childActionName);

JavaScript const rootActionName = "rootActionName";

const childActionName = "childActionName";

// create a custom action for a session

const rootAction = session.enterAction(rootActionName);

// create a child action for the custom action

const childAction = rootAction.enterAction(childActionName);

Количество дочерних действий, прикрепленных к пользовательскому действию, не ограничено. Однако обратите внимание, что может быть только один уровень дочерних действий — нельзя создать дочернее действие для другого дочернего действия (дочерние действия не могут иметь свои собственные дочерние действия). Также обратитесь к разделу Структура пользовательской сессии для отдельного пользователя.

Дочерние действия не отображаются на странице сведений о пользовательской сессии, но вы можете просмотреть их на странице анализа каскадной модели для пользовательского действия, к которому эти дочерние действия привязаны.

Завершение действия

Для точной записи информации о времени выполнения действий следует прерывать выполнение действий после их завершения.

Java Action parentAction = action.leaveAction(); // returns the appropriate custom action

Action parent = parentAction.leaveAction(); // will always return null

.NET IAction parentAction = action.LeaveAction(); // returns the appropriate custom action

IAction parent = parentAction.LeaveAction(); // will always return null

C++ std::shared_ptr<openkit::IRootAction> parentAction = action->leaveAction(); // returns the appropriate custom action

parentAction->leaveAction(); // return type is void

C leaveAction(action); // return type is void

leaveRootAction(rootAction); // return type is void

JavaScript const parentAction = action.leaveAction(); // returns the appropriate custom action

const parent = parentAction.leaveAction(); // will always return null

Отмена действия

Отмена действия аналогична оставлению действия, за исключением того, что действие отменяется и не отправляется в Ключ-АСТРОМ. Открытые дочерние объекты, такие как дочерние действия и трассировки веб-запросов, также отменяются. Дочерние объекты, которые были закрыты ранее, отправляются в бэкэнд и могут быть обработаны в зависимости от типа события.

Java Action parentAction = action.cancelAction(); // returns the appropriate custom action

Action parent = parentAction.cancelAction(); // will always return null

.NET IAction parentAction = action.CancelAction(); // returns the appropriate custom action

IAction parent = parentAction.CancelAction(); // will always return null

C++ std::shared_ptr<openkit::IRootAction> parentAction = action->cancelAction(); // returns the appropriate custom action

parentAction->cancelAction(); // return type is void

C cancelAction(action); // return type is void

cancelRootAction(rootAction); // return type is void

Сообщение о ошибке

Вы можете отправлять отчеты о именованных событиях, связанных с действиями.

Java .NET
String eventName = "eventName";

action.reportEvent(eventName);

// also report on the RootAction

rootAction.reportEvent(eventName);

string eventName = "eventName";

action.ReportEvent(eventName);

// also report on the RootAction

rootAction.ReportEvent(eventName);

C++ C
const char* eventName = "eventName";

action->reportEvent(eventName);

// also report on the RootAction

rootAction->reportEvent(eventName);

const char* eventName = "eventName";

reportEventOnAction(action, eventName);

// also report on the RootAction

reportEventOnRootAction(rootAction, eventName);

JavaScript
const eventName = "eventName";

action.reportEvent(eventName);

// also report on the RootAction

rootAction.reportEvent(eventName);

Сообщение значения

Метод reportValue позволяет передавать пары «ключ-значение» метаданных, которые впоследствии можно просмотреть в веб-интерфейсе Ключ-АСТРОМ и преобразовать в свойства действий пользователя и пользовательских сессий. Передаваемые значения должны быть частью действия пользователя.

Вы можете выводить значения следующих типов данных:

  • 32-bit integer
  • 64-bit integer
  • Double
  • String
Java .NET
// first report a 32-bit int value

String keyIntType = "intType";

int valueInt = 42;

action.reportValue(keyIntType, valueInt);

// then let's report a 64-bit long value

String keyLongType = "longType";

long valueLong = Long.MIN_VALUE;

action.reportValue(keyLongType, valueLong);

// then let's report a double value

String keyDoubleType = "doubleType";

double valueDouble = 3.141592653589793;

action.reportValue(keyDoubleType, valueDouble);

// and also a string value

String keyStringType = "stringType";

String valueString = "The quick brown fox jumps over the lazy dog";

action.reportValue(keyStringType, valueString);

// first report a 32-bit int value

string keyIntType = "intType";

int valueInt = 42;

action.ReportValue(keyIntType, valueInt);

// then let's report a 64-bit long value

string keyLongType = "longType";

long valueLong = long.MinValue;

action.ReportValue(keyLongType, valueLong);

// then let's report a double value

string keyDoubleType = "doubleType";

double valueDouble = 3.141592653589793;

action.ReportValue(keyDoubleType, valueDouble);

// and also a string value

string keyStringType = "stringType";

string valueString = "The quick brown fox jumps over the lazy dog";

action.ReportValue(keyStringType, valueString);

C++ C
// first report a 32-bit integer value

const char* keyIntType = "intType";

int32_t valueInt = 42;

action->reportValue(keyIntType, valueInt);

// then let's report a 64-bit integer value

const char* keyLongType = "longType";

int64_t valueLong = LLONG_MIN;

action->reportValue(keyLongType, valueLong);

// then let's report a double value

const char* keyDoubleType = "doubleType";

double valueDouble = 3.141592653589793;

action->reportValue(keyDoubleType, valueDouble);

// and also a string value

const char* keyStringType = "stringType";

const char* valueString = "The quick brown fox jumps over the lazy dog";

action->reportValue(keyStringType, valueString);

// first report a 32-bit integer value

const char* keyIntType = "intType";

int32_t valueInt = 42;

reportIntValueOnAction(action, keyIntType, valueInt);

// then let's report a 64-bit integer value

const char* keyLongType = "longType";

int64_t valueLong = LLONG_MIN;

reportInt64ValueOnAction(keyLongType, valueLong);

// then let's report a double value

const char* keyDoubleType = "doubleType";

double valueDouble = 3.141592653589793;

reportDoubleValueOnAction(action, keyDoubleType, valueDouble);

// and also a string value

const char* keyStringType = "stringType";

const char* valueString = "The quick brown fox jumps over the lazy dog";

reportStringValueOnAction(action, keyStringType, valueString);

JavaScript
// first report a numeric value

const keyNumberName = 'My reported numeric value';

const numericValue = 42;

action.reportValue(keyNumberName, numericValue);

// and also a string value

const keyStringName = 'My reported string value';

const stringValue = 'The quick brown fox jumps over the lazy dog';

action.reportValue(keyStringName, stringValue);

Чтобы просмотреть отображаемые значения в Ключ-АСТРОМ, перейдите к подробной информации о действии пользователя, которое должно содержать эти метаданные, и прокрутите вниз до раздела Отображаемые значения.


Сообщение об ошибке

Вы можете сообщить об ошибке, указав её название (errorName) и код ошибки (errorCode).

Java String errorName = "Unknown Error";

int errorCode = 42;

action.reportError(errorName, errorCode);

.NET string errorName = "Unknown Error";

int errorCode = 42;

action.ReportError(errorName, errorCode);

C++ const char* errorName = "Unknown Error";

int32_t errorCode = 42;

action->reportError(errorName, errorCode);

C const char* errorName = "Unknown Error";

int32_t errorCode = 42;

// report error on a child action

reportErrorOnAction(action, errorName, errorCode);

// report error on a custom action

reportErrorOnRootAction(rootAction, errorName, errorCode);

JavaScript const errorName = 'Unknown error';

const errorCode = 42;

action.reportError(errorName, errorCode);

Вы также можете сообщить следующую дополнительную информацию об ошибке:

  • Необходимо errorName— Удобочитаемое название ошибки.
  • Необязательно causeName— Причина, приведшая к обнаруженной ошибке, например, имя класса исключения.
  • Необязательно causeDescription— Описание причины, приведшей к ошибке, например, описание исключения.
  • Необязательно stackTraceили causeStackTrace— трассировка стека, указывающая на причину ошибки.

Приведённый ниже фрагмент кода показывает, как сообщать об ошибках с предоставлением дополнительной информации.

Java .NET
public void restrictedMethod() {

    if (!isUserAuthorized()) {

        // user is not authorized - report this as an error

        String errorName = "Authorization error";

        String causeName = "User not authorized";

        String causeDescription = "The current user is not authorized to call restrictedMethod.";

        String stackTrace = null; // no stack trace is reported

        action.reportError(errorName, causeName, causeDescription, stackTrace);

        return;

    }

    // ... further processing ...

}

public void RestrictedMethod()

{

    if (!IsUserAuthorized())

    {

        // user is not authorized - report this as an error

        string errorName = "Authorization error";

        string causeName = "User not authorized";

        string causeDescription = "The current user is not authorized to call restrictedMethod.";

        string stackTrace = null; // no stack trace is reported

        action.ReportError(errorName, causeName, causeDescription, stackTrace);

        return;

    }

    // ... further processing ...

}

C++ C
void RestrictedClass::restrictedMethod()

{

    if (!isUserAuthorized())

    {

        const char* errorName = "Authorization error";

        const char* causeName = "User not authorized";

        const char* causeDescription = "The current user is not authorized to call restrictedMethod.";

        const char* causeStackTrace = nullptr; // no stack trace is reported

        // report the error on IAction

        action->reportError(errorName, causeName, causeDescription, causeStackTrace);

        // report the error on IRootAction

        rootAction->reportError(errorName, causeName, causeDescription, causeStackTrace);

        return;

    }

    // ... further processing

}

void restrictedFunction()

{

    if (!isUserAuthorized())

    {

        const char* errorName = "Authorization error";

        const char* causeName = "User not authorized";

        const char* causeDescription = "The current user is not authorized to call restrictedFunction.";

        const char* causeStackTrace = NULL; // no stack trace is reported

        // report error on child action

        reportErrorCauseOnAction(action, errorName, causeName, causeDescription, causeStackTrace);

        // report error on custom action

        reportErrorCauseOnRootAction(rootAction, errorName, causeName, causeDescription, causeStackTrace);

        return;

    }

    // ... further processing

}

OpenKit Java и OpenKit .NET предоставляют удобный API для непосредственного сообщения о перехваченных исключениях, как показано в примере ниже.

Java .NET
try {

    // call a method that is throwing an exception

    callMethodThrowingException();

} catch(Exception caughtException) {

    // report the caught exception as error via OpenKit

    String errorName = "Unknown Error";

    action.reportError(errorName, caughtException);

}

try

{

    // call a method that is throwing an exception

    CallMethodThrowingException();

}

catch(Exception caughtException)

{

    // report the caught exception as error via OpenKit

    string errorName = "Unknown Error";

    action.ReportError(errorName, caughtException);

}

Сообщение о бизнес событии

Ключ-АСТРОМ SaaS версия 1.253+

С помощью функции sendBizEvent вы можете сообщать о бизнес-событиях. Это автономные события, поскольку Ключ-АСТРОМ отправляет их отдельно от действий пользователя или пользовательских сессий.

Бизнес-события регистрируются только для отслеживаемых сессий. Если OpenKit не инициализирован или сессия исключена из мониторинга из-за ограничений по стоимости и трафику, бизнес-события для таких сессий не отображаются. Обратите внимание, что это поведение может измениться в будущем, что потенциально позволит отправлять бизнес-события в Ключ-АСТРОМ независимо от мониторинга сессий.

Java .NET
Map <String, JSONValue> attributes = new HashMap<String, JSONValue>();

attributes.put("event.name", JSONStringValue.fromString("Confirmed Booking"));

attributes.put("screen", JSONStringValue.fromString("booking-confirmation"));

attributes.put("product", JSONStringValue.fromString("Danube Anna Hotel"));

attributes.put("amount", JSONNumberValue.fromDouble(358.35));

attributes.put("currency", JSONStringValue.fromString("USD"));

attributes.put("reviewScore", JSONNumberValue.fromDouble(4.8));

attributes.put("arrivalDate", JSONStringValue.fromString("2022-11-05"));

attributes.put("departureDate", JSONStringValue.fromString("2022-11-15"));

attributes.put("journeyDuration", JSONNumberValue.fromLong(10));

attributes.put("adultTravelers", JSONNumberValue.fromLong(2));

attributes.put("childrenTravelers", JSONNumberValue.fromLong(0));

session.sendBizEvent('com.easytravel.funnel.booking-finished', attributes);

Dictionary<string, JsonValue> attributes = new Dictionary<string, JsonValue>();

attributes.Add("event.name", JsonStringValue.FromString("Confirmed Booking"));

attributes.Add("screen", JsonStringValue.FromString("booking-confirmation"));

attributes.Add("product", JsonStringValue.FromString("Danube Anna Hotel"));

attributes.Add("amount", JsonNumberValue.FromDouble(358.35));

attributes.Add("currency", JsonStringValue.FromString("USD"));

attributes.Add("reviewScore", JsonNumberValue.FromDouble(4.8));

attributes.Add("arrivalDate", JsonStringValue.FromString("2022-11-05"));

attributes.Add("departureDate", JsonStringValue.FromString("2022-11-15"));

attributes.Add("journeyDuration", JsonNumberValue.FromLong(10));

attributes.Add("adultTravelers", JsonNumberValue.FromLong(2));

attributes.Add("childrenTravelers", JsonNumberValue.FromLong(0));

session.SendBizEvent("com.easytravel.funnel.booking-finished", attributes);

C++ C
auto attributes = std::make_shared<openkit::json::JsonObjectValue::JsonObjectMap>(

    std::initializer_list<openkit::json::JsonObjectValue::JsonObjectMap::value_type>{

        { "event.name", openkit::json::JsonStringValue::fromString("Confirmed Booking") },

        { "screen", openkit::json::JsonStringValue::fromString("booking-confirmation") },

        { "product", openkit::json::JsonStringValue::fromString("Danube Anna Hotel") },

        { "amount", openkit::json::JsonNumberValue::fromDouble(358.35) },

        { "currency", openkit::json::JsonStringValue::fromString("USD") },

        { "reviewScore", openkit::json::JsonNumberValue::fromDouble(4.8) },

        { "arrivalDate", openkit::json::JsonStringValue::fromString("2022-11-05") },

        { "departureDate", openkit::json::JsonStringValue::fromString("2022-11-15") },

        { "journeyDuration", openkit::json::JsonNumberValue::fromLong(10) },

        { "adultTravelers", openkit::json::JsonNumberValue::fromLong(2) },

        { "childrenTravelers", openkit::json::JsonNumberValue::fromLong(0) }

    }

);

size_t attributesSize = 11;

OpenKitPair* attributes = malloc(sizeof(OpenKitPair) * attributesSize);

if (attributes == NULL)

{

    fprintf(stderr, "malloc of attributes for sendBizEvent is not working.");

    exit(-1);

}

attributes[0] = (OpenKitPair) { "event.name", "\"Confirmed Booking\"" };

attributes[1] = (OpenKitPair) { "screen", "\"booking-confirmation\"" };

attributes[2] = (OpenKitPair) { "product", "\"Danube Anna Hotel\"" };

attributes[3] = (OpenKitPair) { "amount", "358.35" };

attributes[4] = (OpenKitPair) { "currency", "\"USD\"" };

attributes[5] = (OpenKitPair) { "reviewScore", "4.8" };

attributes[6] = (OpenKitPair) { "arrivalDate", "\"2022-11-05\"" };

attributes[7] = (OpenKitPair) { "departureDate", "\"2022-11-15\"" };

attributes[8] = (OpenKitPair) { "journeyDuration", "10" };

attributes[9] = (OpenKitPair) { "adultTravelers", "2" };

attributes[10] = (OpenKitPair) { "childrenTravelers", "0" };

sendBizEvent(sessionHandle, "Event", attributes, attributesSize);

free(attributes);

JavaScript
session.sendBizEvent('com.easytravel.funnel.booking-finished', {

    'event.name': 'Confirmed Booking',

    screen: 'booking-confirmation',

    product: 'Danube Anna Hotel',

    amount: 358.35,

    currency: 'USD',

    reviewScore: 4.8,

    arrivalDate: '2022-11-05',

    departureDate: '2022-11-15',

    journeyDuration: 10,

    adultTravelers: 2,

    childrenTravelers: 0,

});

Отслеживание веб-запросов

Одна из самых сильных функций OpenKit — трассировка веб-запросов. Когда приложение начинает веб-запрос, например, HTTP GET, к заголовку можно добавить специальный тег. Этот заголовок позволяет Ключ-АСТРОМ сопоставлять действия с распределенной трассировкой на стороне сервера. Пример показан ниже.

Java .NET
// create URL and open URLConnection

URL url = new URL("http://www.my-backend.com/api/v3/users");

URLConnection urlConnection = url.openConnection();

// create the WebRequestTracer

WebRequestTracer webRequestTracer = action.traceWebRequest(urlConnection);

webRequestTracer.start();

// consume data

BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));

String inputLine;

while ((inputLine = in.readLine()) != null) {

    // TODO - do something useful with response

}

in.close();

// stop web request tracing when done

webRequestTracer.stop(200); // would use the HTTP response code normally.

// --------------------------------------------

// alternative solution not using URLConnection

// --------------------------------------------

String url = "http://www.my-backend.com/api/v3/users";

// create the WebRequestTracer

WebRequestTracer webRequestTracer = action.traceWebRequest(url);

// this is the HTTP header name & value which needs to be added to the HTTP request.

String headerName = OpenKitConstants.WEBREQUEST_TAG_HEADER;

String headerValue = webRequestTracer.getTag();

webRequestTracer.start();

// perform the request here & do not forget to add the HTTP header

webRequestTracer.setBytesSent(12345);     // 12345 bytes sent

webRequestTracer.setBytesReceived(67890); // 67890 bytes received

webRequestTracer.stop(200);               // 200 was the response code

string url = "http://www.my-backend.com/api/v3/users";

// create the WebRequestTracer

IWebRequestTracer webRequestTracer = action.TraceWebRequest(url);

// this is the HTTP header name & value which needs to be added to the HTTP request.

string headerName = OpenKitConstants.WEBREQUEST_TAG_HEADER;

string headerValue = webRequestTracer.Tag;

// perform the request here & do not forget to add the HTTP header

using (HttpClient httpClient = new HttpClient()) {

    // start timing

    webRequestTracer.Start();

    // set the tag

    httpClient.DefaultRequestHeaders.Add(headerName, headerValue);

    // ... perform the request and process the response ...

    // set metadata

    webRequestTracer.SetBytesSent(12345);     // 12345 bytes sent

    webRequestTracer.SetBytesReceived(67890); // 67890 bytes received

    webRequestTracer.Stop(200);               // 200 was the response code

}

C++ C
const char* url = "http://www.my-backend.com/api/v3/users";

// create the WebRequestTracer

std::shared_ptr<openkit::IWebRequestTracer> webRequestTracer = action->traceWebRequest(url);

// this is the HTTP header name & value which needs to be added to the HTTP request.

const char* headerName = openkit::WEBREQUEST_TAG_HEADER;

const char* headerValue = webRequestTracer->getTag();

// start timing

webRequestTracer->start();

// set the tag on httpRequest

// Note: how to set this, depends on the HTTP client library in use

httpRequest.addHeader(headerName, headerValue);

// ... perform the request and process the response ...

// set metadata

webRequestTracer->setBytesSent(12345);     // 12345 bytes sent

webRequestTracer->setBytesReceived(67890); // 67890 bytes received

webRequestTracer->stop(200);               // 200 was the response code

const char* url = "http://www.my-backend.com/api/v3/users";

// create the WebRequestTracer on child action

WebRequestTracerHandle* webRequestTracer = traceWebRequestOnRootAction(rootAction, url);

// Alterantively web requests can be created on a child action like below

// WebRequestTracerHandle* webRequestTracer = traceWebRequestOnAction(action, url);

// this is the HTTP header name & value which needs to be added to the HTTP request.

const char* headerName = WEBREQUEST_TAG_HEADER;

const char* headerValue = getTag(webRequestTracer);

// start timing

startWebRequest(webRequestTracer)

// set the tag on httpRequest

// Note: how to set this, depends on the HTTP client library in use

addCustomHeaderToWebRequest(httpRequest, headerName, headerValue);

// ... perform the request and process the response ...

// set metadata

setBytesSent(webRequestTracer, 12345);     // 12345 bytes sent

setBytesReceived(webRequestTracer, 67890); // 67890 bytes received

stopWebRequest(webRequestTracer, 200);     // 200 was the response code

// After calling stopWebRequest the allocated memory is freed and therefore

// webRequestTracer is no longer valid.

webRequestTracer = NULL;

JavaScript
const url = 'http://www.my-backend.com/api/v3/users';

// create the WebRequestTracer

const webRequestTracer = action.traceWebRequest(url);

const headerName = webRequestTagHeader; // webRequestTagHeader can be imported

const headerValue = webRequestTracer.getTag();

webRequestTracer.start();

// perform the request here & do not forget to add the HTTP header

webRequestTracer.setBytesSent(12345);

webRequestTracer.setBytesReceived(67890);

webRequestTracer.stop(200); // stop the web request tracer, with the response code

Настройка конфиденциальности данных

Вы можете динамически настраивать параметры конфиденциальности данных и создавать собственные приложения в соответствии с законами и правилами защиты данных. Методы API конфиденциальности позволяют динамически изменять уровень сбора данных, а также активировать или деактивировать отчеты о сбоях.

Уровни сбора данных

В таблице ниже описаны доступные уровни сбора данных и указано, отображаются ли пользовательские теги, пользовательские действия, события, значения и ошибки для конкретного уровня.

Уровень Описание Пользовательские теги, события и значения Пользовательские действия и ошибки
Выключено

Данные мониторинга не отправляются.

Персональные данные не передаются; все идентификаторы генерируются случайным образом при каждом запуске. 1 нет нет
Производительность

Отправляется только информация о производительности, автоматически собираемая.

Персональные данные не передаются; все идентификаторы генерируются случайным образом при каждом запуске. нет да
Поведение пользователей

Данные о производительности и данные пользователя передаются.

Передаются персональные данные; ЕдиныйАгент распознает и сообщает о пользователях, которые повторно посещают сайт в будущем. 2 да да

1 Для отслеживания количества пользователей, отказавшихся от участия, отправляется одно событие Loading <App>.

2 Если вы не настроили теги пользователей и пользовательскую отчетность по событиям или значениям, уровень «Поведение пользователя» работает аналогично уровню «Производительность».

Уровни регистрации сбоев

Доступны следующие уровни регистрации сбоев.

Уровень Сообщение о сбое Использование кода сбоя
Выключено нет Вам не нужно собирать отчеты о сбоях.
Opt out crashes нет Пользователь вашего приложения запретил сбор отчетов о сбоях.
Opt in crashes

default

да Пользователь вашего приложения разрешил сбор отчетов о сбоях.

Установка уровня сбора данных и отчетности о сбоях

Приведенные ниже примеры кода демонстрируют работу с API:

Java .NET
import com.astromkey.openkit.DataCollectionLevel;

import com.astromkey.openkit.CrashReportingLevel;

OpenKit openKit = new astromkeyOpenKitBuilder(endpointURL, applicationID, deviceID)

// set a data collection level (user allowed you to capture performance and personal data)

        .withDataCollectionLevel(DataCollectionLevel.USER_BEHAVIOR)

// allow crash reporting (user allowed you to collect information on crashes)

        .withCrashReportingLevel(CrashReportingLevel.OPT_IN_CRASHES)

        .build();

using astromkey.OpenKit;

var openKit = new astromkeyOpenKitBuilder(endpointURL, applicationID, deviceID)

// set a data collection level (user allowed you to capture performance and personal data)

     .WithDataCollectionLevel(DataCollectionLevel.USER_BEHAVIOR)

// allow crash reporting (user allowed you to collect information on crashes)

     .WithCrashReportingLevel(CrashReportingLevel.OPT_IN_CRASHES)

     .Build();

C++ C
#include "OpenKit/OpenKit.h"

auto openKit = openkit::astromkeyOpenKitBuilder builder(endpointURL.c_str(), applicationID.c_str(), deviceID);

// set a data collection level (user allowed you to capture performance and personal data)

builder.withDataCollectionLevel(openkit::DataCollectionLevel::USER_BEHAVIOR)

// allow crash reporting (user allowed you to collect information on crashes)

       .withCrashReportingLevel(openkit::CrashReportingLevel::OPT_IN_CRASHES)

       .build();

#include "OpenKit/OpenKit-c.h"

struct OpenKitConfigurationHandle* configurationHandle = createOpenKitConfiguration(endpointURL, applicationID, deviceID);

// set a data collection level (user allowed you to capture performance and personal data)

useDataCollectionLevelForConfiguration(configurationHandle, DATA_COLLECTION_LEVEL_USER_BEHAVIOR);

// allow crash reporting (user allowed you to collect information on crashes)

useCrashReportingLevelForConfiguration(configurationHandle, CRASH_REPORTING_LEVEL_OPT_IN_CRASHES);

struct OpenKitHandle* openKitHandle = createastromkeyOpenKit(configurationHandle);

destroyOpenKitConfiguration(configurationHandle);

JavaScript
import { CrashReportingLevel, DataCollectionLevel, OpenKitBuilder } from '@astromkey/openkit-js';

const openkit = new OpenKitBuilder(endpointURL, applicationID, deviceID)

// set a data collection level (user allowed you to capture performance and personal data)

        .withDataCollectionLevel(DataCollectionLevel.UserBehavior)

// allow crash reporting (user allowed you to collect information on crashes)

        .withCrashReportingLevel(CrashReportingLevel.OptInCrashes)

        .build();


Возможные значения уровня сбора данных:

  • DataCollectionLevel.Off
  • DataCollectionLevel.Performance
  • DataCollectionLevel.UserBehavior

Возможные значения уровня сообщения о сбоях:

  • CrashReportingLevel.Off
  • CrashReportingLevel.OptOutCrashes
  • CrashReportingLevel.OptInCrashes

Завершение работы экземпляра OpenKit

Когда экземпляр OpenKit больше не нужен, например, при завершении работы приложения, использующего OpenKit, вы можете очистить полученный экземпляр, вызвав метод `shutdown`. Вызов `shutdown` блокирует вызывающий поток на срок до 10 секунд, пока OpenKit отправляет данные, которые еще не были переданы на бэкэнд.

Java openKit.shutdown();
.NET openKit.Shutdown();
C++ openKit->shutdown();
C shutdownOpenKit(openKit);
JavaScript openKit.shutdown();