1.1.5 • Published 7 months ago

obsly-sdk-js-full v1.1.5

Weekly downloads
-
License
ISC
Repository
-
Last release
7 months ago

[npm version](https://img.shields.io/npm/v/obsly-sdk-js-full)

🚀 Obsly SDK

Overview

Obsly offers an advanced observability platform for iOS, Android and Web Applications. Gain real-time insights, identify issues, and optimize your code for seamless performance.

Table of Contents


Installation

To use the SDK in a React app, simply install the package and initiate the SDK from the "App". \ This integration facilitates the SDK's core functionality of analyzing user behavior and identifying potential errors within your application.

npm i obsly-sdk-js-full --save

or

yarn add obsly-sdk-js-full

Initialization

The SDK is initialized via the init function. There are two options to initialize the package, depending the context from where are you using the library.

Pure Javascript

Here is an example of how it should be started. This import allows the SDK to be executed right away the page renders. But it needs to extract "main.bundle.js" from the npm package:

index.html

<script defer src="main.bundle.js"></script>
<script>
  window.onload = () => {
    ObslySDK.init({
      ObslyKey: "apiKey",
      instanceURL: "https://api-url",
    });
  };
</script>

React

For initialize the SDK inside a React Application, it must be instanced inside the App.js file:

...

import * as ObslySDKReact from 'obsly-sdk-js-full/react';

export default function App() {

  ObslySDKReact.init({
    ObslyKey: obslyKey,
    instanceURL: instanceURL,
    remoteConfigURL: remoteConfigURL,
    proEnv: proEnv,
    appVersion: "1.0.0",
    appName: "MyApplication",
    logLevel: logLevel,
    config: {...},
  })  

  ...
}

Upon adding this script, the SDK becomes operational and begins its analysis, providing valuable insights into user interactions and system performance.


Configuration

SDK parameters

The SDK initialization method accepts various parameters to customize its behavior according to your application's needs. Below is a detailed description of each parameter:

ParameterDescriptionRequiredDefault valueTypeExample
ObslyKeyAuthorization Api KeyYesN/Astring"your-api-key"
instanceURLApi server URLYesN/Astring"https://api.url"
remoteConfigURLRemote config server URLNoN/Astring"https://config.url"
proEnvProduction environmentNotruebooleanfalse
appVersionVersion of the appNoundefinedstring"1.0.0"
appNameName of the AppNoundefinedstring"MyApp"
logLevelSDK console log levelNo"error"string"warn"
configCustom configuration object. See detailsNonullobjectSee details
debugModeEnable / Disable debug modeNofalsebooleantrue
sessionIDSet a custom Session ID on initNoN/Astringcustom_session_id

Config structure

ParameterTypeDefault ValueDescription
enableCrashesBooleantrueActivate or deactivate Crash events.
enableLifeCycleLogBooleantrueActivate or deactivate Life Cycle events.
enableRequestLogBooleantrueActivate or deactivate Request events.
enableTaggerBooleantrueActivate or deactivate Tag events.
enablePerformanceBooleantrueActivate or deactivate Performance events.
enableUIBooleantrueActivate or deactivate UI events.
hostBlacklistArray[String]nullURLs to blacklist for request events.They can be wildcards.
hostBodyWhitelistArray[String]nullURLs to capture request body. They can be wildcards.
requestHeadersWhitelistArray[String]nullURLs to capture request headers. They can be wildcards.
automaticViewDetectionBooleantrue🧪 BETA Automatically detect and get the view name. Its only available for SPA pages.
rageClickObject{}Configuration for Rage Click events.
rageClick.activeBooleantrueActivate or deactivate Rage Click events.
rageClick.screenshotBooleantrueCapture screenshot on Rage Click events.
rageClick.screenshotPercentNumber[0,1]0.25The ratio of screenshots to be taken based on Rage Click events. This reduces the number of screenshots taken. It must be a value between 0 and 1
sessionMaxLengthMinsNumber60Duration of a session in minutes.
keepSessionOnRefreshBooleanfalseKeep the session active after a page refresh.
enableScreenshotOnUiBooleanfalseIf it's true, on each Click, and Life Cycle events will be attached an screenshot.
captureConsoleBooleantrueIf it's true, console.warn and console.error will be captured as Tags.

Code Example

  ObslySDK.init({
    ObslyKey: "apiKey",
    instanceURL: "https://api-url",
    remoteConfigURL: "https://api-url",
    proEnv: true,
    appVersion: "4.1.0",
    appName: "myApp",
    config: {
      hostBlacklist: [
        'https://url1.com',
        'https://url2.com'
      ]
    }
  });

Wildcards

Wildcards are patterns that provide flexibility in matching URLs.

  • Pattern Types:

    • Simple Pattern: Matches a specific URL or domain. For example, https://example.com/* matches URLs starting with https://example.com/, including any path or query string after the base domain.
    • Subdomain Pattern: Matches URLs with subdomains. For example, https://*.example.com/* matches URLs that start with any subdomain of example.com, such as https://www.example.com/ or https://subdomain.example.com/.
    • Domain Pattern: Matches URLs with a specific domain, optionally including subdomains. For example, .example.com/ matches URLs for example.com and its subdomains.
  • Supported Expressions:

    • https://example.com/*: Matches https://example.com/ and any path or query string.
    • https://*.example.com/*: Matches any subdomain of example.com and any path or query string.
    • *.example.com/*: Matches example.com and any subdomain, including paths and query strings.

This wildcard pattern flexibility allows for broad or specific URL matching, based on your needs.

Developer Methods

These are the following modules available to use from the SDK:

Manage Sessions


Session Types

Sessions can be of two types: Stateless or Stateful.

  • Stateless Sessions: Each page reload or new tab is considered a new session.
  • Stateful Sessions: The session is maintained and shared across tabs. The session ends only through a timeout or forced closure using the provided methods. Additionally, if an event occurs during a stateful session, the session's timeout will be refreshed to the expiration time defined.
ParameterTypeDefault ValueDescription
sessionMaxLengthMinsNumber60Duration of a session in minutes.

Both the type of session (Stateless or Stateful) and the timeout duration are configurable through the SDK configuration with the parameters keepSessionOnRefresh and sessionMaxLengthMins.


Session Management Functions

This set of functions is dedicated to managing user sessions within your application. Sessions play a pivotal role in understanding user behavior. A new session is initialized on the first load of your web application. Sessions can be concluded in response to specific user actions, such as logging out or exiting the application.

Function Definitions

Function NameParametersTypeRequiredAsyncReturn TypeDescription
closeCurrentSessionNoneN/ANoYesvoidCloses the current session.
createNewSessioncustomSessionIDstringYesYesvoidInitiates a new Obsly session with a customSessionID. If the ID is invalid, it will be generated.

Description

  • closeCurrentSession()

    • Parameters: None
    • Return Type: void
    • Async: Yes
    • Description: Closes the current session.
  • createNewSession(customSessionID)

    • Parameters:
      • customSessionID: string (Required): The custom session ID to initiate the new session. If the ID is invalid, a new ID will be generated.
    • Return Type: void
    • Async: Yes
    • Description: Initiates a new Obsly session with a custom session ID. If the ID is invalid, a new ID will be generated.

Example

//Finishes the current Session and start automatically a new one
ObslySDK.closeCurrentSession();

//Finishes the current Session and start automatically a new one with a custom Session ID
ObslySDK.createNewSession("Custom Session ID");

Custom SessionID

There are two options to specify a custom Session ID:

  • Via the init function, as a parameter.
  • Using the createNewSession function after initialization.

Remember that if you are using a stateful session and you provide a custom Session ID, a new Session ID will be generated after the session expires.


Client identification


Client Identification involves associating unique identifiers with user sessions, enabling more precise tracking and personalized analysis.

Function Definitions

Function NameParametersTypeRequiredAsyncReturn TypeDescription
setUserIDuserIDstringYesNovoidSets the user ID.
setPersonIDpersonIDstringYesNovoidSets the person ID.
setPassportIDpassportIDstringYesNovoidSets the passport ID.
setContractIDcontractIDstringYesNovoidSets the contract ID.

Description

  • setUserID(userID)

    • Parameters:
      • userID: string (Required): The user ID to be set.
    • Return Type: void
    • Async: No
    • Description: Sets the user ID.
  • setPersonID(personID)

    • Parameters:
      • personID: string (Required): The person ID to be set.
    • Return Type: void
    • Async: No
    • Description: Sets the person ID.
  • setPassportID(passportID)

    • Parameters:
      • passportID: string (Required): The passport ID to be set.
    • Return Type: void
    • Async: No
    • Description: Sets the passport ID.
  • setContractID(contractID)

    • Parameters:
      • contractID: string (Required): The contract ID to be set.
    • Return Type: void
    • Async: No
    • Description: Sets the contract ID.

Example

// Set user ID
ObslySDK.setUserID("User1");

Application identification


Obsly SDK provides modules for identifying application-specific information. It allows to identify the App Name and the Version.

Function Definitions

Function NameParametersTypeRequiredAsyncReturn TypeDescription
setAppNameappNamestringYesNovoidSets the application name.
setAppVersionappVersionstringYesNovoidSets the application version.

Description

  • setAppName(appName)

    • Parameters:
      • appName: string (Required): The name of the application to be set.
    • Return Type: void
    • Async: No
    • Description: Sets the application name.
  • setAppVersion(appVersion)

    • Parameters:
      • appVersion: string (Required): The version of the application to be set.
    • Return Type: void
    • Async: No
    • Description: Sets the application version.

Example

// Set user ID
ObslySDK.setAppName("MyNewApp");

// Set user ID
ObslySDK.setAppVersion("1.2.0");

Tag

The Tag functionality in the Obsly SDK is designed to enable the creation of custom key-value pairs, known as tags, that can be attached to user sessions or events. \ These tags can be strategically attached to user sessions or specific events within your application. This functionality is particularly advantageous for generating 'breadcrumbs', which serve as navigational aids in comprehensively understanding a user's interaction flow within the application.

Tag

A Tag is an object with the following structure:

  • key: string (Required): A unique identifier for the tag. This should be a string that represents the tag's key.
  • value: string (Required): The value associated with the tag's key. This should be a string representing the value.
{
  "key": "TAG1",
  "value": "VALUE1"
}

Function definitions

Function NameParametersTypeRequiredAsyncReturn TypeDescription
addTagtagscategoryArray<Tag>stringYesYesYesvoidCreates a key & value tag with the given category and tags array.

Description

  • addTag(tags, category)

    • Parameters:
      • tags: Array<object> (Required): An array of key-value tag objects, each containing a key (string) and a value (string).
      • category: string (Required): A string representing the category for the tags.
    • Return Type: void
    • Async: Yes
    • Description: Creates a key-value tag with the provided tags array and associates it with the specified category.

Example

const tags = [
  {
    key: "TAG1",
    value: "VALUE1",
  },
  {
    key: "TAG2",
    value: "VALUE2",
  },
];

const category = "NEW_CATEGORY";

ObslySDK.addTag(tags, category);

Screenshot

This feature is especially useful for visual analysis and debugging purposes, offering a snapshot view of the user's current application state.

Function Definitions

Function NameParametersTypeRequiredAsyncReturn TypeDescription
addScreenshotNoneN/ANoYesvoidCreates a browser screenshot event.
getScreenshotNoneN/ANoYesPromise<string>Returns a Base64 image string of a screenshot.

Description

  • addScreenshot()

    • Parameters: None
    • Return Type: void
    • Async: Yes
    • Description: Creates a browser screenshot event.
  • getScreenshot()

    • Parameters: None
    • Return Type: Promise<string>
    • Async: Yes
    • Description: Returns a Base64 image string of a screenshot.

Example

const takeScreenshot = () => {
  ObslySDK.addScreenshot();
};

const screenImage = async () => {
  await ObslySDK.getScreenshot();
};

Performance

Metrics are a fundamental feature that allows for the precise measurement of performance within your application. \ They are primarily instrumented through performance events, which are designed to record the time elapsed between various stages or steps in a process.

Function Definitions

Function NameParametersTypeRequiredAsyncReturn TypeDescription
startTransactionnamedescriptionstartNanoTimeautofinishWithStepsCountstringstringnumbernumberYesNoNoNoYesvoidStarts a performance event with the given name and optional parameters for description, start time, and automatic finish after a specified number of steps.
endTransactionnameupdatedDescriptionstringstringYesNoYesvoidEnds a performance event with the specified name and optionally updates its description.
startSteptransactionNamestepNamedescriptionstartNanoTimestringstringstringnumberYesYesNoNoYesvoidStarts a step for an existing performance event with the specified name, step name, and optional parameters for description and start time.
finishSteptransactionNamestepNameupdatedDescriptionstringstringstringYesYesNoYesvoidEnds a step for an existing performance event and optionally updates the step's description.

Description

  • startTransaction(name, description, startNanoTime, autofinishWithStepsCount)

    • Parameters:
      • name: string (Required): The name of the performance event to start.
      • description: string (Optional): A description of the step.
      • startNanoTime: number (Optional): A number higher than 0 to set the start moment.
      • autofinishWithStepsCount: number (Optional): A number higher than 0 to automatically close the performance event after N steps.
    • Return Type: void
    • Async: Yes
    • Description: Starts a performance event with the given name and optional parameters for description, start time, and automatic finish after a specified number of steps.
  • finishTransaction(name, updatedDescription)

    • Parameters:
      • name: string (Required): The name of the performance event to end.
      • updatedDescription: string (Optional): An updated description for the performance event.
    • Return Type: void
    • Async: Yes
    • Description: Ends a performance event with the specified name and optionally updates its description.
  • startStep(transactionName, transactionName, description, startNanoTime)

    • Parameters:
      • transactionName: string (Required): The name of the performance event to which the step belongs.
      • stepName: string (Required): The name of the step.
      • description: string (Optional): A description of the step.
      • startNanoTime: number (Optional): A number higher than 0 to set the start moment of the step.
    • Return Type: void
    • Async: Yes
    • Description: Starts a step for an existing performance event with the specified name, step name, and optional parameters for description and start time.
  • finishStep(name, transactionName, updatedDescription)

    • Parameters:
      • transactionName: string (Required): The name of the performance event to which the step belongs.
      • stepName: string (Required): The name of the step.
      • updatedDescription: string (Optional): An updated description for the step.
    • Return Type: void
    • Async: Yes
    • Description: Ends a step for an existing performance event and optionally updates the step's description.

Example

async function createMetric() {

  // Start a new Transaction
  await ObslySDK.startTransaction("DASHBOARD", "Dashboard performance");

  // Create a new step Load Dashboard
  await ObslySDK.startStep("DASHBOARD", "Load Dashboard");

  // End step on Load Dashboard
  await ObslySDK.finishStep("DASHBOARD", "Load Dashboard");

  // Finally after all the steps, close the transaction
  await ObslySDK.endTransaction("DASHBOARD");

}

Metrics

Regarding metrics, we have 3 types of metrics:

  • Counter: Any metric that increments over time.
  • Gauge: For measuring fluctuating values.
  • HistogramTimer: For measuring execution time.

To use the different types of metrics, we have the following methods:

Function Definitions

Function NameParametersTypeRequiredAsyncReturn TypeDescription
incCounterkey: stringfbl: string (Optional)operation: string (Optional)view: string (Optional)state: string (Optional)stringstringstringstringstringYesNoNoNoNoNovoidIncrements the value of a counter by 1 with the given key. Optional parameters can provide additional context.
setGaugekey: stringvalue: numberfbl: string (Optional)operation: string (Optional)view: string (Optional)state: string (Optional)stringnumberstringstringstringstringYesYesNoNoNoNoNovoidSets the value of the metric with the given key and value. Optional parameters can provide additional context.
startHistogramTimerkey: stringfbl: string (Optional)operation: string (Optional)view: string (Optional)stringstringstringstringYesNoNoNoNovoidStarts a HistogramTimer with the given key. Optional parameters can provide additional context.
endHistogramTimerkey: stringfbl: string (Optional)operation: string (Optional)view: string (Optional)state: string (Optional)stringstringstringstringstringYesNoNoNoNoNovoidEnds a HistogramTimer with the given key. Optional parameters can provide additional context.

Description

  • incCounter(key, fbl, operation, view, state)

    • Parameters:
      • key: string (Required): The key or name of the metric to increment.
      • fbl: string (Optional): The functional block label where the increment is being executed.
      • operation: string (Optional): The operation being performed.
      • view: string (Optional): The view where the increment is being executed.
      • state: string (Optional): The state of the operation, e.g., "OK" or "KO".
    • Return Type: void
    • Async: No
    • Description: Increments the value of a counter by 1 with the specified key. Optional parameters provide additional context.
  • setGauge(key, value, fbl, operation, view, state)

    • Parameters:
      • key: string (Required): The key or name of the metric.
      • value: number (Required): The new value to set for the metric.
      • fbl: string (Optional): The functional block label where the gauge is being set.
      • operation: string (Optional): The operation being performed.
      • view: string (Optional): The view where the gauge is being set.
      • state: string (Optional): The state of the operation, e.g., "OK" or "KO".
    • Return Type: void
    • Async: No
    • Description: Sets the value of the metric with the given key and value. Optional parameters provide additional context.
  • startHistogramTimer(key, fbl, operation, view)

    • Parameters:
      • key: string (Required): The key or name of the metric.
      • fbl: string (Optional): The functional block label where the timer is being started.
      • operation: string (Optional): The operation being performed.
      • view: string (Optional): The view where the timer is being started.
    • Return Type: void
    • Async: No
    • Description: Starts a HistogramTimer with the specified key. Optional parameters provide additional context.
  • endHistogramTimer(key, fbl, operation, view, state)

    • Parameters:
      • key: string (Required): The key or name of the metric.
      • fbl: string (Optional): The functional block label where the timer is being ended.
      • operation: string (Optional): The operation being performed.
      • view: string (Optional): The view where the timer is being ended.
      • state: string (Optional): The state of the operation, e.g., "OK" or "KO".
    • Return Type: void
    • Async: No
    • Description: Ends a HistogramTimer with the specified key. Optional parameters provide additional context.

Example

async function fetchData(fbl, operation, view) {
  const key = "MY_FETCH_TIME";
  ObslySDK.startHistogramTimer(key, fbl, operation, view);
  let response = await fetch("https://api.example.com/data");
  ObslySDK.endHistogramTimer(key, fbl, operation, view);
  return await response.json();
}

async function onClick(fbl, operation, view) {
  const key = "CLICK_EVENT";
  ObslySDK.incCounter(key, fbl, operation, view);
  ...
}

async function onChange(value, fbl, operation, view) {
  const key = "MY_VALUE";
  ObslySDK.setGauge(key, value, fbl, operation, view)
}

const fbl = "FBL_EXAMPLE";
const operation = "OPERATION_EXAMPLE";
const view = "VIEW_EXAMPLE";

fetchData(fbl,operation,view);
onClick(fbl,operation,view);
onChange(2,fbl,operation,view);

Rage Click

Rage Click refers to a user behavior where multiple clicks are made in quick succession on a specific area of the screen or on a single component. This pattern often indicates that the user is experiencing frustration or difficulty with a particular part of the application, suggesting potential issues or malfunctions within that area. The rapid, repeated clicking is usually a sign that the user is attempting to interact with or resolve a problem that is not responding as expected.

By default, Rage Click is enabled and takes screenshots 25% of the time. These parameters can be configured during the initialization of the Obsly SDK See Configuration section.

Note: There may be elements in your application that you do not want to be treated as rage clicks, such as pagination buttons that are clicked in a very consecutive manner. In order to avoid false positives from rage clicks, you can put a tag on the component that you do not want to monitor.

The tag is data-ignore-rage-click, with value 'true'.

If you use data-ignore-rage-click-deep, also all its children will ignore Rage Click events.

Example

// Ignore only the parent
<div data-ignore-rage-click="true">
  <p>Here, I can detect rage click</p>
</div>


// Ignore the parent and all the children
<div data-ignore-rage-click-deep="true">
  <div id="Test"></div>
</div>

Application Context

In this application, there are three main concepts: Functional Blocks, Operations, and Views. Screens belong to Operations, and Operations belong to Functional Blocks, grouping views based on their functionality. This hierarchical structure helps organize and manage the application flow efficiently.

The context variables for Functional Block, Operation, and Screen are used to control and monitor application behavior. These variables are integrated into custom metrics tracking as well as Rage Click detection, ensuring comprehensive insights into user interactions and performance across different application contexts.


Funcion Definitions

Function NameParametersTypeRequiredAsyncReturn TypeDescription
setViewviewNamestringYesYesvoidSets the current view name.
setOperationoperationstringYesYesvoidSets the current operation.
setFunctionalBlockfunctionalBlockstringYesYesvoidSets the current Functional Block.

Description

  • setView(viewName)

    • Parameters:
      • viewName: string (Required): The name of the view to be set.
    • Return Type: void
    • Async: Yes
    • Description: Sets the current view name for the application.
  • setOperation(operation)

    • Parameters:
      • operation: string (Required): The name of the operation to be set.
    • Return Type: void
    • Async: Yes
    • Description: Sets the current operation for the application.
  • setFunctionalBlock(functionalBlock)

    • Parameters:
      • functionalBlock: string (Required): The name of the functional block to be set.
    • Return Type: void
    • Async: Yes
    • Description: Sets the current functional block for the application.

SDK Control

The following functions allow you to configure and manage the SDK's behavior and logging:


Function Definitions

Function NameParametersTypeRequiredAsyncReturn TypeDescription
pauseTrackerYesvoidPause capturing and sending events.
resumeTrackerYesvoidResets event capture and sending.
setLogLevellevelstringYesYesvoidSets the console log level for SDK Obsly. Allowed values: null, error, warn, log.
setRequestsBlacklistblackliststring[]YesNovoidAdds a blacklist of request URLs.
getSessionInfoYesobjectGets session information.
activateFullDebugYesvoidEnable full debug mode.
deactivateFullDebugYesvoidDisable full debug mode.

Descriptions

  • pauseTracker()

    • Parameters: None
    • Return Type: void
    • Async: Yes
    • Description: Pauses the sending of data to the server.
  • resumeTracker()

    • Parameters: None
    • Return Type: void
    • Async: Yes
    • Description: Resumes sending data to the server.
  • setLogLevel(level)

    • Parameters:
      • level: string (Required): The log level for the SDK Obsly. Allowed values are:
        • null
        • error
        • warn
        • log
    • Return Type: void
    • Async: Yes
    • Description: Sets the console log level for the SDK Obsly.
  • setRequestsBlacklist(blacklist)

    • Parameters:
      • blacklist: string[] (Required): Array of string URLs to be blacklisted.
    • Return Type: void
    • Async: No
    • Description: Adds a blacklist of request URLs.
  • getSessionInfo()

    • Parameters: None
    • Return Type: object
    • Async: Yes
    • Description: Gets session information.

Miscelaneous

This section includes various methods that do not fall into the previously defined categories.

Funcion Definitions

Function NameParametersTypeRequiredAsyncReturn TypeDescription
addFeedbackrating: numbermessage: stringimage: stringnumberstringstringYesNovoidAdds a new feedback event with a rating, a message, and an image. The image should be in Base64 format.

Description

  • addFeedback(rating, message, image)

    • Parameters:
      • rating: number (Required): The rating for the feedback event.
      • message: string (Required): The message associated with the feedback.
      • image: string (Required): The image related to the feedback, encoded in Base64 format.
    • Return Type: void
    • Async: No
    • Description: Adds a new feedback event with the specified rating, message, and Base64 encoded image.

Getting Help

At Obsly, we are committed to providing exceptional support and ensuring that your experience with our SDK is as smooth and productive as possible. \ The most effective way to reach out to us with any questions, feedback, or support requests is via email. \ Send us your inquiries at info@obsly.tech

We value your input and are always eager to hear from our users. Your feedback helps us continually improve our SDK and services, ensuring they meet your needs and expectations.

1.1.5

7 months ago

1.1.4

9 months ago

1.1.3

9 months ago

1.1.1

9 months ago

1.1.0

9 months ago

1.0.39

10 months ago

1.0.38

10 months ago

1.1.2

9 months ago

1.0.40

9 months ago

1.0.41

9 months ago

1.0.37

10 months ago

1.0.36

10 months ago

1.0.35

10 months ago

1.0.34

10 months ago

1.0.29

1 year ago

1.0.28

1 year ago

1.0.27

1 year ago

1.0.33

11 months ago

1.0.32

11 months ago

1.0.31

11 months ago

1.0.30

12 months ago

1.0.26

1 year ago

1.0.25

1 year ago

1.0.24

1 year ago

1.0.23

1 year ago

1.0.19

1 year ago

1.0.22

1 year ago

1.0.21

1 year ago

1.0.20

1 year ago

1.0.18

1 year ago

1.0.17

1 year ago

1.0.16

1 year ago

1.0.15

1 year ago

1.0.0

1 year ago