Skip to content

Browser Log Collection


Actively send log data of different levels (corresponding source:browser_log metric type log data) from Web browsers or Javascript clients to Guance.

  • Custom log data collection: Integrate the SDK into client applications to collect different log data for different scenarios.
  • Automatically collect error information from the application end (including network errors, console errors, and js errors) and report it to Guance.
  • Custom error levels (debug, critical, error, info, warn), custom Logger objects, and custom Log fields.
  • Automatically collect RUM related data and associate it with RUM business scenarios.

Getting Started

Prerequisites

  1. Ensure DataKit is installed and configured to be accessible via the public network, and install the IP geolocation database.
  2. When integrating the SDK, set datakitOrigin to the DataKit domain name or IP.

  1. Obtain parameters such as clientToken and site from the console.
  2. When integrating the SDK, there is no need to configure datakitOrigin. Data will be sent to the public DataWay by default.

SDK Configuration

Access Method Introduction
NPM Bundle the SDK code together with your front-end project. This method ensures no impact on front-end page performance, but might miss requests and errors that occur before SDK initialization.
CDN Asynchronous Loading Introduce the SDK script via CDN accelerated cache as an asynchronous script. This method ensures that the download of the SDK script does not affect page loading performance, but might miss requests and errors that occur before SDK initialization.
CDN Synchronous Loading Introduce the SDK script via CDN accelerated cache as a synchronous script. This method ensures the collection of all errors, resources, requests, and performance metrics, but might affect page loading performance.

NPM

import { datafluxLogs } from "@cloudcare/browser-logs"
datafluxLogs.init({
  datakitOrigin: "<DataKit Domain or IP>", // Required for DK access method
  clientToken: "clientToken", // Required for public OpenWay access
  site: "Public OpenWay Address", // Required for public OpenWay access
  //service: 'browser',
  //forwardErrorsToLogs:true
})

CDN Asynchronous Loading

<script>
  ;(function (h, o, u, n, d) {
    h = h[d] = h[d] || {
      q: [],
      onReady: function (c) {
        h.q.push(c)
      },
    }
    d = o.createElement(u)
    d.async = 1
    d.src = n
    n = o.getElementsByTagName(u)[0]
    n.parentNode.insertBefore(d, n)
  })(
    window,
    document,
    "script",
    "https://static.guance.com/browser-sdk/v3/dataflux-logs.js",
    "DATAFLUX_LOGS"
  )
  DATAFLUX_LOGS.onReady(function () {
    DATAFLUX_LOGS.init({
      datakitOrigin: "<DataKit Domain or IP>", // Required for DK access method
      clientToken: "clientToken", // Required for public OpenWay access
      site: "Public OpenWay Address", // Required for public OpenWay access
      //service: 'browser',
      //forwardErrorsToLogs:true
    })
  })
</script>

CDN Synchronous Loading

<script
  src="https://static.guance.com/browser-sdk/v3/dataflux-logs.js"
  type="text/javascript"
></script>
<script>
  window.DATAFLUX_LOGS &&
    window.DATAFLUX_LOGS.init({
      datakitOrigin: "<DataKit Domain or IP>", // Required for DK access method
      clientToken: "clientToken", // Required for public OpenWay access
      site: "Public OpenWay Address", // Required for public OpenWay access
      //service: 'browser',
      //forwardErrorsToLogs:true
    })
</script>

Configuration

Initialization Parameters

Parameter Type Required Default Value Description
datakitOrigin String Yes DataKit data reporting Origin Note: Protocol (including ://), domain name (or IP address) [and port number] e.g., https://www.datakit.com, http://100.20.34.3:8088.
clientToken String Yes Token for reporting data via OpenWay. Obtained from the Guance console. Required (for public OpenWay access).
site String Yes Address for reporting data via public OpenWay. Obtained from the Guance console. Required (for public OpenWay access).
service String No browser Log Service name
env String No Current environment of the Web application, e.g., Prod: Production environment; Gray: Gray environment; Pre: Pre-release environment; Common: Daily environment; Local: Local environment.
version String No Version number of the Web application
sessionSampleRate Number No 100 Metric data collection percentage: 100 means full collection, 0 means no collection.
tracingSampleRate Number No 100 Trace data sampling percentage: 100 means full collection, 0 means no collection.
forwardErrorsToLogs Boolean No true Set to false to stop collecting console.error, js, and network errors and reporting them to Guance log data.
silentMultipleInit Boolean No false Disallow multiple log objects from being initialized.
forwardConsoleLogs String/Array No Browser console log types to collect. Optional values: error, log, info, warn, error.
storeContextsToLocal Boolean No Version requirement: >3.1.2. Whether to cache user-defined data to local localstorage, e.g., custom data added by setUser, addGlobalContext APIs.
storeContextsKey String No Version requirement: >3.1.18. Define the key for storage in localstorage. Default is auto-generated if not filled. This parameter is mainly to distinguish shared stores under the same domain but different sub-paths.

Usage

After the SDK is initialized in the application, exposed JS APIs can be used to custom configure log data.

logger.debug | info | warn | error | critical (message: string, messageContext = Context)

NPM

import { datafluxLogs } from "@cloudcare/browser-logs"

datafluxLogs.logger.info("Button clicked", { name: "buttonName", id: 123 })

CDN Asynchronous

DATAFLUX_LOGS.onReady(function () {
  DATAFLUX_LOGS.logger.info("Button clicked", { name: "buttonName", id: 123 })
})

CDN Synchronous

window.DATAFLUX_LOGS && DATAFLUX_LOGS.logger.info("Button clicked", { name: "buttonName", id: 123 })

Return Data Structure

{
  "service": "browser",
  "session": {
    "id": "c549c2b8-4955-4f74-b7f8-a5f42fc6e79b"
  },
  "type": "logger",
  "_dd": {
    "sdk_name": "Web LOG SDK",
    "sdk_version": "1.0.0",
    "env": "",
    "version": ""
  },
  "device": {
    "os": "Mac OS",
    "os_version": "10.14.6",
    "os_version_major": "10",
    "browser": "Chrome",
    "browser_version": "90.0.4430.85",
    "browser_version_major": "90",
    "screen_size": "2560*1440",
    "network_type": "3g",
    "divice": "PC"
  },
  "user": {},
  "date": 1621321916756,
  "view": {
    "referrer": "",
    "url": "http://localhost:8080/",
    "host": "localhost:8080",
    "path": "/",
    "path_group": "/",
    "url_query": "{}",
    "id": "5dce64f4-8d6d-411a-af84-c41653ccd94a"
  },
  "application": {
    "id": "app_idxxxxxx"
  },
  "message": "XHR error get http://testing-ft2x-api.cloudcare.cn/api/v1/workspace/xxx",
  "status": "error",
  "tags": {},
  "error": {
    "source": "network",
    "stack": "Failed to load"
  },
  "resource": {
    "method": "get",
    "status": 0,
    "status_group": 0,
    "url": "http://testing-ft2x-api.cloudcare.cn/api/v1/workspace/xxx",
    "url_host": "testing-ft2x-api.cloudcare.cn",
    "url_path": "/api/v1/workspace/xxx",
    "url_path_group": "/api/?/workspace/xxx"
  }
}

Status Parameter

After initializing the SDK, use the provided log API to define different types of statuses.

log (message: string, messageContext: Context, status? = 'debug' | 'info' | 'warn' | 'error' | 'critical')

NPM

import { datafluxLogs } from '@cloudcare/browser-logs'

datafluxLogs.logger.log(<MESSAGE>,<JSON_ATTRIBUTES>,<STATUS>);

CDN Asynchronous

DATAFLUX_LOGS.onReady(function () {
  DATAFLUX_LOGS.logger.log(<MESSAGE>,<JSON_ATTRIBUTES>,<STATUS>);
})

CDN Synchronous

window.DATAFLUX_LOGS && DATAFLUX_LOGS.logger.log(<MESSAGE>,<JSON_ATTRIBUTES>,<STATUS>);

Parameter Description

Parameter Description
<MESSAGE> The Message field in Guance logs.
<JSON_ATTRIBUTES> Extra data describing the Message, is a Json object.
<STATUS> Log level. Optional values: debug, info, warn, error, critical.

Custom Adding Extra Data TAGs


After initializing the LOG, use the setGlobalContextProperty(key:string,value:any) API to add extra TAGs to all LOG events collected from the application.

Add TAG

window.DATAFLUX_LOGS && window.DATAFLUX_LOGS.setGlobalContextProperty('<CONTEXT_KEY>', '<CONTEXT_VALUE>');

// Code example
window.DATAFLUX_LOGS && window.DATAFLUX_LOGS.setGlobalContextProperty('isvip', 'xxxx');
window.DATAFLUX_LOGS && window.DATAFLUX_LOGS.setGlobalContextProperty('activity', {
    hasPaid: true,
    amount: 23.42
});
DATAFLUX_LOGS.onReady(function() {
    DATAFLUX_LOGS.setGlobalContextProperty('<CONTEXT_KEY>', '<CONTEXT_VALUE>');
})

// Code example
DATAFLUX_LOGS.onReady(function() {
    DATAFLUX_LOGS.setGlobalContextProperty('isvip', 'xxxx');
})
DATAFLUX_LOGS.onReady(function() {
    DATAFLUX_LOGS.setGlobalContextProperty('activity', {
        hasPaid: true,
        amount: 23.42
    });
})
import { datafluxLogs } from '@cloudcare/browser-logs'
datafluxLogs.setGlobalContextProperty('<CONTEXT_KEY>', <CONTEXT_VALUE>);

// Code example
datafluxLogs && datafluxLogs.setGlobalContextProperty('isvip', 'xxxx');
datafluxLogs.setGlobalContextProperty('activity', {
    hasPaid: true,
    amount: 23.42
});

Replace TAG (Overwrite)

window.DATAFLUX_LOGS &&
     window.DATAFLUX_LOGS.setGlobalContext({ '<CONTEXT_KEY>': '<CONTEXT_VALUE>' });

// Code example
window.DATAFLUX_LOGS &&
     window.DATAFLUX_LOGS.setGlobalContext({
        codeVersion: 34,
    });
 window.DATAFLUX_LOGS.onReady(function() {
     window.DATAFLUX_LOGS.setGlobalContext({ '<CONTEXT_KEY>': '<CONTEXT_VALUE>' });
})

// Code example
 window.DATAFLUX_LOGS.onReady(function() {
     window.DATAFLUX_LOGS.setGlobalContext({
        codeVersion: 34,
    })
})
import { datafluxLogs } from '@cloudcare/browser-logs'

datafluxLogs.setGlobalContext({ '<CONTEXT_KEY>': '<CONTEXT_VALUE>' });

// Code example
datafluxLogs.setGlobalContext({
    codeVersion: 34,
});

Get All Set Custom TAGs

var context = window.DATAFLUX_LOGS &&  window.DATAFLUX_LOGS.getGlobalContext();
 window.DATAFLUX_LOGS.onReady(function() {
    var context =  window.DATAFLUX_LOGS.getGlobalContext();
});
import { datafluxLogs } from '@cloudcare/browser-logs'

const context = datafluxLogs.getGlobalContext();

Remove Custom TAG Corresponding to a Specific Key

var context = window.DATAFLUX_LOGS &&  window.DATAFLUX_LOGS.removeGlobalContextProperty('<CONTEXT_KEY>');
 window.DATAFLUX_LOGS.onReady(function() {
    var context =  window.DATAFLUX_LOGS.removeGlobalContextProperty('<CONTEXT_KEY>');
});
import { datafluxLogs } from '@cloudcare/browser-logs'

const context = datafluxLogs.removeGlobalContextProperty('<CONTEXT_KEY>');

Remove All Custom TAGs

var context = window.DATAFLUX_LOGS &&  window.DATAFLUX_LOGS.clearGlobalContext();
 window.DATAFLUX_LOGS.onReady(function() {
    var context =  window.DATAFLUX_LOGS.clearGlobalContext();
});
import { datafluxLogs } from '@cloudcare/browser-logs'

const context = datafluxLogs.clearGlobalContext();

Custom User Identification


By default, the SDK automatically generates a unique identifier ID for the user. This ID does not carry any identifying attributes and can only distinguish different user properties. Therefore, we provide additional APIs to add different identifying attributes to the current user.

Attribute Type Description
user.id string User ID
user.name string User nickname or username
user.email string User email

Note: The following attributes are optional, but it is recommended to provide at least one.

Add User Identification

window.DATAFLUX_LOGS && window.DATAFLUX_LOGS.setUser({
    id: '1234',
    name: 'John Doe',
    email: 'john@doe.com',
})
window.DATAFLUX_LOGS.onReady(function() {
    window.DATAFLUX_LOGS.setUser({
        id: '1234',
        name: 'John Doe',
        email: 'john@doe.com',
    })
})
import { datafluxLogs } from '@cloudcare/browser-logs'
datafluxLogs.setUser({
    id: '1234',
    name: 'John Doe',
    email: 'john@doe.com',
})

Remove User Identification

window.DATAFLUX_LOGS && window.DATAFLUX_LOGS.clearUser()
window.DATAFLUX_LOGS.onReady(function() {
    window.DATAFLUX_LOGS.clearUser()
})
import { datafluxLogs } from '@cloudcare/browser-logs'
datafluxLogs.clearUser()

Feedback

Is this page helpful? ×