obsly-sdk-js-full
TypeScript icon, indicating that this package has built-in type declarations

1.1.5 • Public • Published

Logo

Obsly SDK for Javascript

Optimize Your Applications with Real-time Insights

npm version


🚀 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:

Parameter Description Required Default value Type Example
ObslyKey Authorization Api Key Yes N/A string "your-api-key"
instanceURL Api server URL Yes N/A string "https://api.url"
remoteConfigURL Remote config server URL No N/A string "https://config.url"
proEnv Production environment No true boolean false
appVersion Version of the app No undefined string "1.0.0"
appName Name of the App No undefined string "MyApp"
logLevel SDK console log level No "error" string "warn"
config Custom configuration object. See details No null object See details
debugMode Enable / Disable debug mode No false boolean true
sessionID Set a custom Session ID on init No N/A string custom_session_id

Config structure

Parameter Type Default Value Description
enableCrashes Boolean true Activate or deactivate Crash events.
enableLifeCycleLog Boolean true Activate or deactivate Life Cycle events.
enableRequestLog Boolean true Activate or deactivate Request events.
enableTagger Boolean true Activate or deactivate Tag events.
enablePerformance Boolean true Activate or deactivate Performance events.
enableUI Boolean true Activate or deactivate UI events.
hostBlacklist Array[String] null URLs to blacklist for request events.They can be wildcards.
hostBodyWhitelist Array[String] null URLs to capture request body. They can be wildcards.
requestHeadersWhitelist Array[String] null URLs to capture request headers. They can be wildcards.
automaticViewDetection Boolean true [🧪 BETA] Automatically detect and get the view name. Its only available for SPA pages.
rageClick Object {} Configuration for Rage Click events.
rageClick.active Boolean true Activate or deactivate Rage Click events.
rageClick.screenshot Boolean true Capture screenshot on Rage Click events.
rageClick.screenshotPercent Number[0,1] 0.25 The 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
sessionMaxLengthMins Number 60 Duration of a session in minutes.
keepSessionOnRefresh Boolean false Keep the session active after a page refresh.
enableScreenshotOnUi Boolean false If it's true, on each Click, and Life Cycle events will be attached an screenshot.
captureConsole Boolean true If 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

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.
Parameter Type Default Value Description
sessionMaxLengthMins Number 60 Duration 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 Name Parameters Type Required Async Return Type Description
closeCurrentSession None N/A No Yes void Closes the current session.
createNewSession customSessionID string Yes Yes void Initiates 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


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

Function Definitions

Function Name Parameters Type Required Async Return Type Description
setUserID userID string Yes No void Sets the user ID.
setPersonID personID string Yes No void Sets the person ID.
setPassportID passportID string Yes No void Sets the passport ID.
setContractID contractID string Yes No void Sets 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

Application identification


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

Function Definitions

Function Name Parameters Type Required Async Return Type Description
setAppName appName string Yes No void Sets the application name.
setAppVersion appVersion string Yes No void Sets 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

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 Name Parameters Type Required Async Return Type Description
addTag tags

category
Array<Tag>
string
Yes
Yes
Yes void Creates 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

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 Name Parameters Type Required Async Return Type Description
addScreenshot None N/A No Yes void Creates a browser screenshot event.
getScreenshot None N/A No Yes Promise<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

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 Name Parameters Type Required Async Return Type Description
startTransaction name
description
startNanoTime
autofinishWithStepsCount
string
string
number
number
Yes
No
No
No
Yes void Starts a performance event with the given name and optional parameters for description, start time, and automatic finish after a specified number of steps.
endTransaction name
updatedDescription
string
string
Yes
No
Yes void Ends a performance event with the specified name and optionally updates its description.
startStep transactionName
stepName
description
startNanoTime
string
string
string
number
Yes
Yes
No
No
Yes void Starts a step for an existing performance event with the specified name, step name, and optional parameters for description and start time.
finishStep transactionName
stepName
updatedDescription
string
string
string
Yes
Yes
No
Yes void Ends 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

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 Name Parameters Type Required Async Return Type Description
incCounter key: string
fbl: string (Optional)
operation: string (Optional)
view: string (Optional)
state: string (Optional)
string
string
string
string
string
Yes
No
No
No
No
No void Increments the value of a counter by 1 with the given key. Optional parameters can provide additional context.
setGauge key: string
value: number
fbl: string (Optional)
operation: string (Optional)
view: string (Optional)
state: string (Optional)
string
number
string
string
string
string
Yes
Yes
No
No
No
No
No void Sets the value of the metric with the given key and value. Optional parameters can provide additional context.
startHistogramTimer key: string
fbl: string (Optional)
operation: string (Optional)
view: string (Optional)
string
string
string
string
Yes
No
No
No
No void Starts a HistogramTimer with the given key. Optional parameters can provide additional context.
endHistogramTimer key: string
fbl: string (Optional)
operation: string (Optional)
view: string (Optional)
state: string (Optional)
string
string
string
string
string
Yes
No
No
No
No
No void Ends 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

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

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 Name Parameters Type Required Async Return Type Description
setView viewName string Yes Yes void Sets the current view name.
setOperation operation string Yes Yes void Sets the current operation.
setFunctionalBlock functionalBlock string Yes Yes void Sets 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

SDK Control

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


Function Definitions

Function Name Parameters Type Required Async Return Type Description
pauseTracker Yes void Pause capturing and sending events.
resumeTracker Yes void Resets event capture and sending.
setLogLevel level string Yes Yes void Sets the console log level for SDK Obsly. Allowed values: null, error, warn, log.
setRequestsBlacklist blacklist string[] Yes No void Adds a blacklist of request URLs.
getSessionInfo Yes object Gets session information.
activateFullDebug Yes void Enable full debug mode.
deactivateFullDebug Yes void Disable 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

Miscelaneous

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

Funcion Definitions

Function Name Parameters Type Required Async Return Type Description
addFeedback rating: number
message: string
image: string
number
string
string
Yes No void Adds 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.

Package Sidebar

Install

npm i obsly-sdk-js-full

Homepage

obsly.tech

Weekly Downloads

16

Version

1.1.5

License

ISC

Unpacked Size

242 kB

Total Files

7

Last publish

Collaborators

  • kakxem
  • alexsmlm
  • joangaga