From 120693ea969a21ebc98a32165c97abd4bdcfd0f6 Mon Sep 17 00:00:00 2001 From: Rick Foster <115846221+rick-bt@users.noreply.github.com> Date: Tue, 3 Oct 2023 10:15:34 -0700 Subject: [PATCH] Add new Web SDK docs (#2465) --- .../language-integrations/javascript.md | 341 ++++++++++++++- .../language-integrations/node.md | 402 +++++++++++++++++- .../language-integrations/react.md | 372 ++++++++++++++++ .../platform-integrations/overview.md | 1 + sidebars.js | 1 + 5 files changed, 1079 insertions(+), 38 deletions(-) create mode 100644 docs/error-reporting/language-integrations/react.md diff --git a/docs/error-reporting/language-integrations/javascript.md b/docs/error-reporting/language-integrations/javascript.md index 77bc3ac6de..12e638c9b9 100644 --- a/docs/error-reporting/language-integrations/javascript.md +++ b/docs/error-reporting/language-integrations/javascript.md @@ -9,37 +9,336 @@ import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; import useBaseUrl from '@docusaurus/useBaseUrl'; -Backtrace provides an open source module that you can use to capture uncaught JavaScript errors, as well as manually send reports. +[Backtrace](https://backtrace.io) captures and reports handled and unhandled exceptions in your production software so +you can manage application quality through the complete product lifecycle. -## What You'll Need +The [@backtrace-labs/browser](#) SDK connects your JavaScript application to Backtrace. The basic integration is quick +and easy, after which you can explore the rich set of Backtrace features. -- A Backtrace account ([log in](https://backtrace.io/login) or sign up for a [free trial license](https://backtrace.io/sign-up)). -- Your subdomain name (used to connect to your Backtrace instance). For example, `https://example-subdomain.sp.backtrace.io`. -- A Backtrace project and a [submission token](/error-reporting/project-setup/submission-url). +## Basic Integration -## Download and Documentation +### Install the package -The download of `backtrace-js` module and its full documentation is available at [https://github.com/backtrace-labs/backtrace-js](https://github.com/backtrace-labs/backtrace-js). +``` +$ npm install @backtrace-labs/browser +``` + +### Integrate the SDK + +Add the following code to your application before all other scripts to report client-side errors to Backtrace. + +```ts +// Import the BacktraceClient from @backtrace-labs/browser with your favorite package manager. +import { BacktraceClient, BacktraceConfiguration } from '@backtrace-labs/browser'; + +// Configure client options +const options: BacktraceConfiguration = { + // Name of the website/application + name: 'MyWebPage', + // Version of the website + version: '1.2.3', + // Submission url + // is the subdomain of your Backtrace instance (.backtrace.io) + // can be found in Project Settings/Submission tokens + url: 'https://submit.backtrace.io///json', +}; + +// Initialize the client with the options +const client = BacktraceClient.initialize(options); + +// By default, Backtrace will send an error for Uncaught Exceptions and Unhandled Promise Rejections + +// Manually send an error +client.send(new Error('Something broke!')); +``` + +### Upload source maps + +Client-side error reports are based on minified code. Upload source maps and source code to resolve minified code to +your original source identifiers. + +[(Source Map feature documentation)](/error-reporting/platform-integrations/source-map/) + +## Error Reporting Features + +### Attributes + +Custom attributes are key-value pairs that can be added to your error reports. They are used in report aggregation, +sorting and filtering, can provide better contextual data for an error, and much more. They are foundational to many of +the advanced Backtrace features detailed in +[Error Reporting documentation](/error-reporting/getting-started/). + +There are several places where attributes can be added, modified or deleted. + +#### Attach attributes object to BacktraceClient + +It is possible to include an attributes object during [BacktraceClient](#backtraceclient) initialization. This list of +attributes will be included with every error report, referred to as global attributes. + +```ts +// Create an attributes object that can be modified throughout runtime +const attributes: Record = { + release: 'PROD', +}; + +// BacktraceClientOptions +const options: BacktraceConfiguration = { + name: 'MyWebPage', + version: '1.2.3', + url: 'https://submit.backtrace.io///json', + + // Attach the attributes object + userAttributes: attributes, +}; + +// Initialize the client +const client = BacktraceClient.initialize(options); +``` + +You can also include attributes that will be resolved when creating a report: + +```ts +// BacktraceClientOptions +const options: BacktraceConfiguration = { + name: 'MyWebPage', + version: '1.2.3', + url: 'https://submit.backtrace.io///json', + + // Attach the attributes object + userAttributes: () => ({ + user: getCurrentUser(), + }), +}; + +// Initialize the client +const client = BacktraceClient.initialize(options); +``` + +#### Add attributes during application runtime + +Global attributes can be set during the runtime once specific data has be loaded (e.g. a user has logged in). + +```ts +const client = BacktraceClient.initialize(options); +... + +client.addAttribute({ + "clientID": "de6faf4d-d5b5-486c-9789-318f58a14476" +}) +``` + +You can also add attributes that will be resolved when creating a report: + +```ts +const client = BacktraceClient.initialize(options); +... + +client.addAttribute(() => ({ + "clientID": resolveCurrentClientId() +})) +``` + +#### Add attributes to an error report + +The attributes list of a BacktraceReport object can be directly modified. + +```ts +const report: BacktraceReport = new BacktraceReport('My error message', { myReportKey: 'myValue' }); +report.attributes['myReportKey'] = 'New value'; +``` + +--- + +### File Attachments + +Files can be attached to error reports. This can be done when initalizing the BacktraceClient, updating the +BacktraceClient, or dynamically for specific reports. When including attachments in BacktraceClient, all files will be +uploaded with each report. + +```ts +// Import attachment types from @backtrace-labs/browser +import { BacktraceStringAttachment, BacktraceUint8ArrayAttachment } from "@backtrace-labs/browser"; + +// BacktraceStringAttachment should be used for text object like a log file, for example +const attachment1 = new BacktraceStringAttachment("logfile.txt", "This is the start of my log") -## Example Usage +// BacktraceUint8ArrayAttachment should be used for binary files +const attachment2 = new BacktraceUint8ArrayAttachment("connection_buffer", new Uint8Array(2)); -```javascript -// Import backtrace-js with your favorite package manager. -import * as bt from 'backtrace-js'; +// Setup array of files to attach +const attachments = [attachment1]; -bt.initialize({ - endpoint: "https://yourcompany.sp.backtrace.io:6098", - token: "51cc8e69c5b62fa8c72dc963e730f1e8eacbd243aeafc35d08d05ded9a024121" +// BacktraceClientOptions +const options = { + name: "MyWebPage", + version: "1.2.3", + url: "https://submit.backtrace.io///json", + + // Attach the files to all reports + attachments, +} + +const client = BacktraceClient.initialize(options); + +// Later decide to add an attachment to all reports +client.addAttachment(attachment2) + +// After catching an exception and generating a report +try { + throw new Error("Caught exception!") +} catch (error) { + const report = const report = new BacktraceReport(error, {}, [new BacktraceStringAttachment("CaughtErrorLog", "some error logging data here")]) + client.send(report); +} +``` + +--- + +### Breadcrumbs + +Breadcrumbs are snippets of chronological data tracing runtime events. This SDK records a number of events by default, +and manual breadcrumbs can also be added. + +[(Breadcrumbs feature documentation)](/error-reporting/web-console/debug/#breadcrumbs) + +#### Breadcrumbs Configuration + +| Option Name | Type | Description | Default | Required? | +| -------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------- | ---------------------------------------- | +| `enable` | Boolean | Determines if the breadcrumbs support is enabled. By default the value is set to true. | `true` | | +| `logLevel` | BreadcrumbLogLevel | Specifies which log level severity to include. By default all logs are included. | All Logs | | +| `eventType` | BreadcrumbType | Specifies which breadcrumb type to include. By default all types are included. | All Types | | +| `maximumBreadcrumbs` | Number | Specifies maximum number of breadcrumbs stored by the library. By default, only 100 breadcrumbs will be stored. | `100` | | +| `intercept` | (breadcrumb: RawBreadcrumb) => RawBreadcrumb \| undefined; | Inspects breadcrumb and allows to modify it. If the undefined value is being returned from the method, no breadcrumb will be added to the breadcrumb storage. | All Breadcrumbs | | + +```ts +import { BacktraceClient, BacktraceConfiguration } from '@backtrace-labs/browser'; + +// BacktraceClientOptions +const options: BacktraceConfiguration = { + // ignoring all but breadcrumbs config for simplicity + breadcrumbs: { + // breadcrumbs configuration + }, +}; + +// Initialize the client +const client = BacktraceClient.initialize(options); +``` + +#### Default Breadcrumbs + +| Type | Description | +| --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| HTTP | Adds a breadcrumb with the url, request type, and reponse status for Fetch or XMLHttpRequests. | +| History | Adds breadcrumb on pushstate and popstate. | +| Document/Window | Adds a breadcrumb for document.click, document.dblclick, document.drag, document.drop, window.load, window.unload, window.pagehide, window.pageshow, window.online, and window.offline. | +| Console | Adds a breadcrumb every time console log is being used by the developer. | + +#### Intercepting Breadcrumbs + +If PII or other information needs to be filtered from a breadcrumb, you can use the intercept function to skip or filter +out the sensitive information. Any RawBreadcrumb returned will be used for the breadcrumb. If undefined is returned, no +breadcrumb will be added. + +#### Manual Breadcrumbs + +In addition to all of the default breadcrumbs that are automatically collected, you can also manually add breadcrumbs of +your own. + +```ts +client.breadcrumbs?.info('This is a manual breadcrumb.', { + customAttr: 'wow!', }); +``` -// Later, when you have an error: -bt.report(new Error("something broke")); +--- + +### Application Stability Metrics + +The Backtrace Browser SDK has the ability to send usage Metrics to be viewable in the Backtrace UI. + +[(Stability Metrics feature documentation)](/error-reporting/project-setup/stability-metrics/) + +#### Metrics Configuration + +| Option Name | Type | Description | Default | Required? | +| ---------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- | ---------------------------------------- | +| `metricsSubmissionUrl` | String | Metrics server hostname. By default the value is set to https://events.backtrace.io. | `https://events.backtrace.io` | | +| `enable` | Boolean | Determines if the metrics support is enabled. By default the value is set to true. | `true` | | +| `autoSendInterval` | Number | Indicates how often crash free metrics are sent to Backtrace. The interval is a value in ms. By default, session events are sent on application startup/finish, and every 30 minutes while the application is running. If the value is set to 0. The auto send mode is disabled. In this situation the application needs to maintain send mode manually. | On application startup/finish | | +| `size` | Number | Indicates how many events the metrics storage can store before auto submission. | `50` | | + +#### Metrics Usage + +```ts +// metrics will be undefined if not enabled +client.metrics?.send(); ``` -## Testing +--- + +## Advanced SDK Features + +### Manually send an error + +There are several ways to send an error to Backtrace. For more details on the definition of `client.send()` see +[Methods](#backtraceclient-methods) below. -```bash -npm install -./node_modules/.bin/browserify test/app.js --outfile test/out.js -node test/server.js +```ts +// send as a string +await client.send('This is a string!'); + +// send as an Error +await client.send(new Error('This is an Error!')); + +// as a BacktraceReport (string) +await client.send(new BacktraceReport('This is a report with a string!')); + +// as a BacktraceReport (Error) +await client.send(new BacktraceReport(new Error('This is a report with a string!'))); ``` + +### BacktraceClient + +BacktraceClient is the main SDK class. Error monitoring starts when this object is instantiated, and it will compose and +send reports for unhandled errors and unhandled promise rejections. It can also be used to manually send reports from +exceptions and rejection handlers. + +#### BacktraceClientOptions + +The following options are available for the BacktraceClientOptions passed when initializing the BacktraceClient. + +| Option Name | Type | Description | Default | Required? | +| ----------------------------------- | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | ------------------------------------------------------- | +| `url` | String | Submission URL to send errors to | | | +| `name` | String | Your application name | | | +| `version` | String | Your application version | | | +| `token` | String | The submission token for error injestion. This is required only if submitting directly to a Backtrace URL. (uncommon) | | | +| `userAttributes` | Dictionary | Additional attributes that can be filtered and aggregated against in the Backtrace UI. | | | +| `attachments` | BacktraceAttachment[] | Additional files to be sent with error reports. See [File Attachments](#file-attachments) | | | +| `beforeSend` | (data: BacktraceData) => BacktraceData \| undefined | Triggers an event every time an exception in the managed environment occurs, which allows you to skip the report (by returning a null value) or to modify data that library collected before sending the report. You can use the BeforeSend event to extend attributes or JSON object data based on data the application has at the time of exception. See [BeforeSend](#beforesend) | | | +| `skipReport` | (report: BacktraceReport) => boolean | If you want to ignore specific types of error reports, we recommend that you use the skipReport callback. By using it, based on the data generated in the report, you can decide to filter the report, or send it to Backtrace. | | | +| `captureUnhandledErrors` | Boolean | Enable unhandled errors | `true` | | +| `captureUnhandledPromiseRejections` | Boolean | Enable unhandled promise rejection | `true` | | +| `timeout` | Integer | How long to wait in ms before timing out the connection | `15000` | | +| `ignoreSslCertificate` | Boolean | Ignore SSL Certificate errors | `false` | | +| `rateLimit` | Integer | Limits the number of reports the client will send per minute. If set to '0', there is no limit. If set to a value greater than '0' and the value is reached, the client will not send any reports until the next minute. | `0` | | +| `metrics` | BacktraceMetricsOptions | See [Backtrace Stability Metrics](#application-stability-metrics) | | | +| `breadcrumbs` | BacktraceBreadcrumbsSettings | See [Backtrace Breadcrumbs](#breadcrumbs) | | | + +#### BacktraceClient Methods + +| Name | Return Type | Description | +| ----------------------------------------------------------------------------------------------------------------------------------------------- | --------------- | --------------------------------------------------------------------------------- | +| `addAttribute(attributes: Record)` | void | Add attributes to the BacktraceClient reports | +| `addAttachment(attachment: BacktraceAttachment)` | void | Add an attachment to the BacktraceClient reports | +| `initialize(options: BacktraceClientOptions)` | BacktraceClient | Initializes a new BacktraceClient (returns the same instance on subsequent calls) | +| `builder(options: BacktraceClientOptions).build()` | BacktraceClient | (Advanced) Sets up a new BacktraceClient for reporting | +| `send(data: BacktraceReport \| Error \| string, reportAttributes: Record = {}, reportAttachments: BacktraceAttachment[] = [])` | `Promise` | Asynchronously sends error data to Backtrace | +| `dispose` | void | Disposes the client | + +### BacktraceReport + +A Backtrace Report is the format that ultimately gets sent to Backtrace. Its structure can be found in +`BacktraceReport.ts`. diff --git a/docs/error-reporting/language-integrations/node.md b/docs/error-reporting/language-integrations/node.md index 5308c29747..4fd35042ae 100644 --- a/docs/error-reporting/language-integrations/node.md +++ b/docs/error-reporting/language-integrations/node.md @@ -3,38 +3,406 @@ id: node title: Node.js Integration Guide sidebar_label: Node.js description: Use Node in your Backtrace project. + --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; import useBaseUrl from '@docusaurus/useBaseUrl'; -Backtrace provides an open source module that you can use to capture uncaught JavaScript errors in Node.js and manually send reports. +[Backtrace](https://backtrace.io) captures and reports handled and unhandled exceptions in your production software so +you can manage application quality through the complete product lifecycle. + +The [@backtrace-labs/node](#) SDK connects your JavaScript application to Backtrace. The basic integration is quick and +easy, after which you can explore the rich set of Backtrace features. + +## Basic Integration + +### Install the package + +``` +$ npm install @backtrace-labs/node +``` + +### Integrate the SDK + +Add the following code to your application before all other scripts to report node errors to Backtrace. + +```ts +// Import the BacktraceClient from @backtrace-labs/node with your favorite package manager. +import { BacktraceClient, BacktraceConfiguration } from '@backtrace-labs/node'; + +// Configure client options +const options: BacktraceConfiguration = { + // Submission url + // is the subdomain of your Backtrace instance (.backtrace.io) + // can be found in Project Settings/Submission tokens + url: 'https://submit.backtrace.io///json', +}; + +// Initialize the client with the options +const client = BacktraceClient.initialize(options); + +// By default, Backtrace will send an error for Uncaught Exceptions and Unhandled Promise Rejections + +// Manually send an error +client.send(new Error('Something broke!')); +``` + +### Upload source maps + +Client-side error reports are based on minified code. Upload source maps and source code to resolve minified code to +your original source identifiers. + +[(Source Map feature documentation)](/error-reporting/platform-integrations/source-map/) + +## Error Reporting Features + +### Attributes + +Custom attributes are key-value pairs that can be added to your error reports. They are used in report aggregation, +sorting and filtering, can provide better contextual data for an error, and much more. They are foundational to many of +the advanced Backtrace features detailed in +[Error Reporting documentation](/error-reporting/getting-started/). By default attributes such +as application name and version are populated automatically based on your package.json information. If Backtrace cannot +find them, you need to provide them manually via userAttributes attributes. + +There are several places where attributes can be added, modified or deleted. + +#### Attach attributes object to BacktraceClient + +It is possible to include an attributes object during [BacktraceClient](#backtraceclient) initialization. This list of +attributes will be included with every error report, referred to as global attributes. + +```ts +// Create an attributes object that can be modified throughout runtime +const attributes: Record = { + release: 'PROD', +}; + +// BacktraceClientOptions +const options: BacktraceConfiguration = { + url: 'https://submit.backtrace.io///json', + + // Attach the attributes object + userAttributes: attributes, +}; + +// Initialize the client +const client = BacktraceClient.initialize(options); +``` + +You can also include attributes that will be resolved when creating a report: + +```ts +// BacktraceClientOptions +const options: BacktraceConfiguration = { + url: 'https://submit.backtrace.io///json', + + // Attach the attributes object + userAttributes: () => ({ + attribute: getAttributeValue(), + }), +}; + +// Initialize the client +const client = BacktraceClient.initialize(options); +``` + +#### Add attributes during application runtime + +Global attributes can be set during the runtime once specific data has be loaded (e.g. a user has logged in). + +```ts +const client = BacktraceClient.initialize(options); +... + +client.addAttribute({ + "clientID": "de6faf4d-d5b5-486c-9789-318f58a14476" +}) +``` + +You can also add attributes that will be resolved when creating a report: + +```ts +const client = BacktraceClient.initialize(options); +... + +client.addAttribute(() => ({ + "clientID": resolveCurrentClientId() +})) +``` + +#### Add attributes to an error report + +The attributes list of a BacktraceReport object can be directly modified. + +```ts +const report: BacktraceReport = new BacktraceReport('My error message', { myReportKey: 'myValue' }); +report.attributes['myReportKey'] = 'New value'; +``` + +--- + +### File Attachments + +Files can be attached to error reports. This can be done when initalizing the BacktraceClient, updating the +BacktraceClient, or dynamically for specific reports. When including attachments in BacktraceClient, all files will be +uploaded with each report. + +```ts +// Import attachment types from @backtrace-labs/node +import { BacktraceStringAttachment, BacktraceUint8ArrayAttachment } from "@backtrace-labs/node"; + +// BacktraceStringAttachment should be used for text object like a log file, for example +const stringAttachment = new BacktraceStringAttachment("logfile.txt", "This is the start of my log") + +// Buffer attachment is an attachment type dedicated to store buffer data +const bufferAttachment = new BacktraceBufferAttachment('buffer-attachment.txt', Buffer.from('sample')); + +// File attachment is an attachment type dedicated for streaming files +const fileAttachment = new BacktraceFileAttachment('/path/to/sample/file'); + +// BacktraceClientOptions +const options = { + url: "https://submit.backtrace.io///json", + + // Attach the files to all reports + attachments: [path.join('/path/to/attachment'), stringAttachment], +} + +const client = BacktraceClient.initialize(options); + +// Later decide to add an attachment to all reports +client.addAttachment(bufferAttachment) -## What You'll Need +// After catching an exception and generating a report +try { + throw new Error("Caught exception!") +} catch (error) { + const report = const report = new BacktraceReport(error, {}, [fileAttachment]) + client.send(report); +} +``` + +--- + +### Breadcrumbs -- A Backtrace account ([log in](https://backtrace.io/login) or sign up for a [free trial license](https://backtrace.io/sign-up)). -- Your subdomain name (used to connect to your Backtrace instance). For example, `https://example-subdomain.sp.backtrace.io`. -- A Backtrace project and a [submission token](/error-reporting/project-setup/submission-url). +Breadcrumbs are snippets of chronological data tracing runtime events. This SDK records a number of events by default, +and manual breadcrumbs can also be added. -## Download +[(Breadcrumbs feature documentation)](/error-reporting/web-console/debug/#breadcrumbs) -You can download the `backtrace-node` module from the npm package with the same name or from [https://github.com/backtrace-labs/backtrace-node](https://github.com/backtrace-labs/backtrace-node). +#### Breadcrumbs Configuration -## Example Usage +| Option Name | Type | Description | Default | Required? | +| -------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------- | ---------------------------------------- | +| `enable` | Boolean | Determines if the breadcrumbs support is enabled. By default the value is set to true. | `true` | | +| `logLevel` | BreadcrumbLogLevel | Specifies which log level severity to include. By default all logs are included. | All Logs | | +| `eventType` | BreadcrumbType | Specifies which breadcrumb type to include. By default all types are included. | All Types | | +| `maximumBreadcrumbs` | Number | Specifies maximum number of breadcrumbs stored by the library. By default, only 100 breadcrumbs will be stored. | `100` | | +| `intercept` | (breadcrumb: RawBreadcrumb) => RawBreadcrumb \| undefined; | Inspects breadcrumb and allows to modify it. If the undefined value is being returned from the method, no breadcrumb will be added to the breadcrumb storage. | All Breadcrumbs | | + +```ts +import { BacktraceClient, BacktraceConfiguration } from '@backtrace-labs/node'; + +// BacktraceClientOptions +const options: BacktraceConfiguration = { + // ignoring all but breadcrumbs config for simplicity + breadcrumbs: { + // breadcrumbs configuration + }, +}; + +// Initialize the client +const client = BacktraceClient.initialize(options); +``` -```javascript -var bt = require('backtrace-node'); -bt.initialize({ - endpoint: "https://yourcompany.sp.backtrace.io:6098", - token: "51cc8e69c5b62fa8c72dc963e730f1e8eacbd243aeafc35d08d05ded9a024121", +#### Default Breadcrumbs + +| Type | Description | +| ------- | ------------------------------------------------------------------------ | +| Console | Adds a breadcrumb every time console log is being used by the developer. | + +#### Intercepting Breadcrumbs + +If PII or other information needs to be filtered from a breadcrumb, you can use the intercept function to skip or filter +out the sensitive information. Any RawBreadcrumb returned will be used for the breadcrumb. If undefined is returned, no +breadcrumb will be added. + +#### Manual Breadcrumbs + +In addition to all of the default breadcrumbs that are automatically collected, you can also manually add breadcrumbs of +your own. + +```ts +client.breadcrumbs?.info('This is a manual breadcrumb.', { + customAttr: 'wow!', }); +``` -// ... +--- + +### Application Stability Metrics + +The Backtrace Node SDK has the ability to send usage Metrics to be viewable in the Backtrace UI. + +[(Stability Metrics feature documentation)](/error-reporting/project-setup/stability-metrics/) -bt.report(new Error("something broke")); +#### Metrics Configuration + +| Option Name | Type | Description | Default | Required? | +| ---------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- | ---------------------------------------- | +| `metricsSubmissionUrl` | String | Metrics server hostname. By default the value is set to https://events.backtrace.io. | `https://events.backtrace.io` | | +| `enable` | Boolean | Determines if the metrics support is enabled. By default the value is set to true. | `true` | | +| `autoSendInterval` | Number | Indicates how often crash free metrics are sent to Backtrace. The interval is a value in ms. By default, session events are sent on application startup/finish, and every 30 minutes while the application is running. If the value is set to 0. The auto send mode is disabled. In this situation the application needs to maintain send mode manually. | On application startup/finish | | +| `size` | Number | Indicates how many events the metrics storage can store before auto submission. | `50` | | + +#### Metrics Usage + +```ts +// metrics will be undefined if not enabled +client.metrics?.send(); ``` -## Documentation +--- + +### Offline database support + +The Backtrace Node SDK can cache generated reports and crashes to local disk before sending them to Backtrace. This is +recommended; in certain configurations Node applications can crash before the SDK finishes submitting data, and under +slow internet conditions your application might wait in a closing window until the HTTP submission finishes. In such an +event occurs cached reports will be sent on next application launch. + +With offline database support you can: + +- cache your reports when the user doesn't have Internet connection or the service is unavailable, +- capture crashes, +- manually decide when to send them or not. + +By default the offline database support is disabled. To enable it, please add "enable: true" and the path to the +directory where Backtrace can store crash data. + +```ts +const client = BacktraceClient.initialize({ + // ignoring all but database config for simplicity + database: { + enable: true, + path: '/path/to/the/database/directory', + captureNativeCrashes: true, + }, +}); + +// manually send and keep the data on connection issue +client.database.send(); +// manually send and remove all data no matter if received success or not. +client.database.flush(); +``` + +#### Database Configuration + +| Option Name | Type | Description | Default | Required? | +| ------------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | ------------------------------------------------------- | +| `enabled` | Boolean | Enable/disable offline database support. | false | | +| `path` | String | Local storage path for crash data. | - | | +| `createDatabaseDirectory` | Boolean | Allow the SDK to create the offline database directory.. | true | | +| `autoSend` | Boolean | Sends reports to the server based on the retry settings. If the value is set to 'false', you can use the Flush or Send methods as an alternative. | true | | +| `maximumNumberOfRecords` | Number | The maximum number of reports stored in the offline database. When the limit is reached, the oldest reports are removed. If the value is equal to '0', then no limit is set. | 8 | | +| `retryInterval` | Number | The amount of time (in ms) to wait between retries if the database is unable to send a report. | 60 000 | | +| `maximumRetries` | Number | The maximum number of retries to attempt if the database is unable to send a report. | 3 | | +| `captureNativeCrashes` | Boolean | Capture and symbolicate stack traces for native crashes if the runtime supports this. A crash report is generated, stored locally, and uploaded upon next start. | false | | + +--- + +#### Native crash support + +The Backtrace Node SDK can capture native crashes generated by a Node application such as Assert/OOM crashes. In order +to collect them, the SDK uses the Node's `process.report` API. After setting up the native crash support, your +`process.report` settings may be overridden and your crash data might be created in the database directory. + +Database records sent in the next session may not have some information about the crashing session such as attributes or +breadcrumbs. To reduce database record size, attachment support was limited only to file attachments. + +#### Manual database operations + +Database support is available in the client options with the BacktraceDatabase object. You can use it to manually +operate on database records. Options are detailed in [BacktraceDatabase Methods](#backtracedatabase-methods). + +## Advanced SDK Features + +### Manually send an error + +There are several ways to send an error to Backtrace. For more details on the definition of `client.send()` see +[Methods](#backtraceclient-methods) below. + +```ts +// send as a string +await client.send('This is a string!'); + +// send as an Error +await client.send(new Error('This is an Error!')); + +// as a BacktraceReport (string) +await client.send(new BacktraceReport('This is a report with a string!')); + +// as a BacktraceReport (Error) +await client.send(new BacktraceReport(new Error('This is a report with a string!'))); +``` + +### BacktraceClient + +BacktraceClient is the main SDK class. Error monitoring starts when this object is instantiated, and it will compose and +send reports for unhandled errors and unhandled promise rejections. It can also be used to manually send reports from +exceptions and rejection handlers. + +#### BacktraceClientOptions + +The following options are available for the BacktraceClientOptions passed when initializing the BacktraceClient. + +| Option Name | Type | Description | Default | Required? | +| ----------------------------------- | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | ------------------------------------------------------- | +| `url` | String | Submission URL to send errors to | | | +| `token` | String | The submission token for error injestion. This is required only if submitting directly to a Backtrace URL. (uncommon) | | | +| `userAttributes` | Dictionary | Additional attributes that can be filtered and aggregated against in the Backtrace UI. | | | +| `attachments` | BacktraceAttachment[] | Additional files to be sent with error reports. See [File Attachments](#file-attachments) | | | +| `beforeSend` | (data: BacktraceData) => BacktraceData \| undefined | Triggers an event every time an exception in the managed environment occurs, which allows you to skip the report (by returning a null value) or to modify data that library collected before sending the report. You can use the BeforeSend event to extend attributes or JSON object data based on data the application has at the time of exception. See [BeforeSend](#beforesend) | | | +| `skipReport` | (report: BacktraceReport) => boolean | If you want to ignore specific types of error reports, we recommend that you use the skipReport callback. By using it, based on the data generated in the report, you can decide to filter the report, or send it to Backtrace. | | | +| `captureUnhandledErrors` | Boolean | Enable unhandled errors | `true` | | +| `captureUnhandledPromiseRejections` | Boolean | Enable unhandled promise rejection | `true` | | +| `timeout` | Integer | How long to wait in ms before timing out the connection | `15000` | | +| `ignoreSslCertificate` | Boolean | Ignore SSL Certificate errors | `false` | | +| `rateLimit` | Integer | Limits the number of reports the client will send per minute. If set to '0', there is no limit. If set to a value greater than '0' and the value is reached, the client will not send any reports until the next minute. | `0` | | +| `metrics` | BacktraceMetricsOptions | See [Backtrace Stability Metrics](#application-stability-metrics) | | | +| `breadcrumbs` | BacktraceBreadcrumbsSettings | See [Backtrace Breadcrumbs](#breadcrumbs) | | | +| `database` | BacktraceDatabaseSettings | See [Backtrace Database](#offline-database-support) | | | + +#### BacktraceClient Methods + +| Name | Return Type | Description | +| ----------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- | --------------------------------------------------------------------------------- | +| `addAttribute(attributes: Record)` | void | Add attributes to the BacktraceClient reports | +| `addAttachment(attachment: BacktraceAttachment)` | void | Add an attachment to the BacktraceClient reports | +| `initialize(options: BacktraceClientOptions)` | BacktraceClient | Initializes a new BacktraceClient (returns the same instance on subsequent calls) | +| `builder(options: BacktraceClientOptions).build()` | BacktraceClient | (Advanced) Sets up a new BacktraceClient for reporting | +| `send(data: BacktraceReport \| Error \| string, reportAttributes: Record = {}, reportAttachments: BacktraceAttachment[] = [])` | Promise<void> | Asynchronously sends error data to Backtrace | + +#### BacktraceDatabase Methods + +| Name | Return Type | Description | +| ----------------------------------------------------------------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `enabled` | Boolean | Determines if the database is enabled | +| `start()` | Boolean | Starts the database | +| `add(backtraceData: Backtracedata, attachments: BacktraceAttachment[])` | BacktraceDatabaseRecord \| undefined | Adds manually a data object to the database. If the database is not available or the record cannot be stored on the hard drive, the add method can return undefined. | +| `get()` | BacktraceDatabaseRecord[] | Returns all records stored in the database | +| `count()` | Number | Returns the number of records stored in the database | +| `dispose()` | void | Disables the database integration | +| `remove(record: BacktraceDatabaseRecord)` | void | Removes the record from the database | +| `flush()` | Promise<void> | Sends all records to Backtrace and remove them no matter if the submission was successful or not | +| `send()` | Promise<void> | Sends all records to Backtrace. If the submission process fails, the retry information is being increased by the records are not removed from the database. | +| `dispose` | void | Disposes the client | + +### BacktraceReport -For more advanced usage or to learn more about backtrace-node, refer to the official package documentation at [https://github.com/backtrace-labs/backtrace-node#readme](https://github.com/backtrace-labs/backtrace-node#readme). +A Backtrace Report is the format that ultimately gets sent to Backtrace. Its structure can be found in +`BacktraceReport.ts`. diff --git a/docs/error-reporting/language-integrations/react.md b/docs/error-reporting/language-integrations/react.md new file mode 100644 index 0000000000..7a6c08912a --- /dev/null +++ b/docs/error-reporting/language-integrations/react.md @@ -0,0 +1,372 @@ +--- +id: react +title: React Integration Guide +sidebar_label: React +description: Use React in your Backtrace project. +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import useBaseUrl from '@docusaurus/useBaseUrl'; + +[Backtrace](https://backtrace.io) captures and reports handled and unhandled exceptions in your production software so +you can manage application quality through the complete product lifecycle. + +The [@backtrace-labs/react](#) SDK connects your React application to Backtrace. The basic integration is quick and +easy, after which you can explore the rich set of Backtrace features. + +## Basic Integration + +### Install the package + +``` +$ npm install @backtrace-labs/react +``` + +### Integrate the SDK + +Add the following code to your application before all other scripts to report client-side errors to Backtrace. + +```ts +// Import the BacktraceClient from @backtrace-labs/react with your favorite package manager. +import { BacktraceClient, BacktraceConfiguration } from '@backtrace-labs/react'; + +// Configure client options +const options: BacktraceConfiguration = { + // Name of the website/application + name: 'MyWebPage', + // Version of the website + version: '1.2.3', + // Submission url + // is the subdomain of your Backtrace instance (.backtrace.io) + // can be found in Project Settings/Submission tokens + url: 'https://submit.backtrace.io///json', +}; + +// Initialize the client with the options +const client = BacktraceClient.initialize(options); + +// By default, Backtrace will send an error for Uncaught Exceptions and Unhandled Promise Rejections + +// Manually send an error +client.send(new Error('Something broke!')); +``` + +### Add a Backtrace Error Boundary + +The `@backtrace-labs/react` SDK offers an Error Boundary that will handle errors during rendering, send the error and +component stack to Backtrace, and allow you to provide a fallback component. + +Props: + +```ts +type RenderFallback = () => ReactElement; + +export interface Props { + children: ReactNode; + fallback?: ReactElement | RenderFallback; + name?: string; // to identify the ErrorBoundary when multiple are used +} +``` + +Usage: + +```ts +import { ErrorBoundary } from '@backtrace-labs/react'; +import Fallback from './components/Fallback'; + + + +; +``` + +### Upload source maps + +Client-side error reports are based on minified code. Upload source maps and source code to resolve minified code to +your original source identifiers. + +[(Source Map feature documentation)](/error-reporting/platform-integrations/source-map/) + +## Error Reporting Features + +### Attributes + +Custom attributes are key-value pairs that can be added to your error reports. They are used in report aggregation, +sorting and filtering, can provide better contextual data for an error, and much more. They are foundational to many of +the advanced Backtrace features detailed in +[Error Reporting documentation](/error-reporting/getting-started/). + +There are several places where attributes can be added, modified or deleted. + +#### Attach attributes object to BacktraceClient + +It is possible to include an attributes object during [BacktraceClient](#backtraceclient) initialization. This list of +attributes will be included with every error report, referred to as global attributes. + +```ts +// Create an attributes object that can be modified throughout runtime +const attributes: Record = { + release: 'PROD', +}; + +// BacktraceClientOptions +const options: BacktraceConfiguration = { + name: 'MyWebPage', + version: '1.2.3', + url: 'https://submit.backtrace.io///json', + + // Attach the attributes object + userAttributes: attributes, +}; + +// Initialize the client +const client = BacktraceClient.initialize(options); +``` + +You can also include attributes that will be resolved when creating a report: + +```ts +// BacktraceClientOptions +const options: BacktraceConfiguration = { + name: 'MyWebPage', + version: '1.2.3', + url: 'https://submit.backtrace.io///json', + + // Attach the attributes object + userAttributes: () => ({ + user: getCurrentUser(), + }), +}; + +// Initialize the client +const client = BacktraceClient.initialize(options); +``` + +#### Add attributes during application runtime + +Global attributes can be set during the runtime once specific data has be loaded (e.g. a user has logged in). + +```ts +const client = BacktraceClient.initialize(options); +... + +client.addAttribute({ + "clientID": "de6faf4d-d5b5-486c-9789-318f58a14476" +}) +``` + +You can also add attributes that will be resolved when creating a report: + +```ts +const client = BacktraceClient.initialize(options); +... + +client.addAttribute(() => ({ + "clientID": resolveCurrentClientId() +})) +``` + +#### Add attributes to an error report + +The attributes list of a BacktraceReport object can be directly modified. + +```ts +const report: BacktraceReport = new BacktraceReport('My error message', { myReportKey: 'myValue' }); +report.attributes['myReportKey'] = 'New value'; +``` + +--- + +### File Attachments + +Files can be attached to error reports. This can be done when initalizing the BacktraceClient, updating the +BacktraceClient, or dynamically for specific reports. When including attachments in BacktraceClient, all files will be +uploaded with each report. + +```ts +// Import attachment types from @backtrace-labs/react +import { BacktraceStringAttachment, BacktraceUint8ArrayAttachment } from "@backtrace-labs/react"; + +// BacktraceStringAttachment should be used for text object like a log file, for example +const attachment1 = new BacktraceStringAttachment("logfile.txt", "This is the start of my log") + +// BacktraceUint8ArrayAttachment should be used for binary files +const attachment2 = new BacktraceUint8ArrayAttachment("connection_buffer", new Uint8Array(2)); + +// Setup array of files to attach +const attachments = [attachment1]; + +// BacktraceClientOptions +const options = { + name: "MyWebPage", + version: "1.2.3", + url: "https://submit.backtrace.io///json", + + // Attach the files to all reports + attachments, +} + +const client = BacktraceClient.initialize(options); + +// Later decide to add an attachment to all reports +client.addAttachment(attachment2) + +// After catching an exception and generating a report +try { + throw new Error("Caught exception!") +} catch (error) { + const report = const report = new BacktraceReport(error, {}, [new BacktraceStringAttachment("CaughtErrorLog", "some error logging data here")]) + client.send(report); +} +``` + +--- + +### Breadcrumbs + +Breadcrumbs are snippets of chronological data tracing runtime events. This SDK records a number of events by default, +and manual breadcrumbs can also be added. + +[(Breadcrumbs feature documentation)](/error-reporting/web-console/debug/#breadcrumbs) + +#### Breadcrumbs Configuration + +| Option Name | Type | Description | Default | Required? | +| -------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------- | ---------------------------------------- | +| `enable` | Boolean | Determines if the breadcrumbs support is enabled. By default the value is set to true. | `true` | | +| `logLevel` | BreadcrumbLogLevel | Specifies which log level severity to include. By default all logs are included. | All Logs | | +| `eventType` | BreadcrumbType | Specifies which breadcrumb type to include. By default all types are included. | All Types | | +| `maximumBreadcrumbs` | Number | Specifies maximum number of breadcrumbs stored by the library. By default, only 100 breadcrumbs will be stored. | `100` | | +| `intercept` | (breadcrumb: RawBreadcrumb) => RawBreadcrumb \| undefined; | Inspects breadcrumb and allows to modify it. If the undefined value is being returned from the method, no breadcrumb will be added to the breadcrumb storage. | All Breadcrumbs | | + +```ts +import { BacktraceClient, BacktraceConfiguration } from '@backtrace-labs/react'; + +// BacktraceClientOptions +const options: BacktraceConfiguration = { + // ignoring all but breadcrumbs config for simplicity + breadcrumbs: { + // breadcrumbs configuration + }, +}; + +// Initialize the client +const client = BacktraceClient.initialize(options); +``` + +#### Default Breadcrumbs + +| Type | Description | +| --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| HTTP | Adds a breadcrumb with the url, request type, and reponse status for Fetch or XMLHttpRequests. | +| History | Adds breadcrumb on pushstate and popstate. | +| Document/Window | Adds a breadcrumb for document.click, document.dblclick, document.drag, document.drop, window.load, window.unload, window.pagehide, window.pageshow, window.online, and window.offline. | +| Console | Adds a breadcrumb every time console log is being used by the developer. | + +#### Intercepting Breadcrumbs + +If PII or other information needs to be filtered from a breadcrumb, you can use the intercept function to skip or filter +out the sensitive information. Any RawBreadcrumb returned will be used for the breadcrumb. If undefined is returned, no +breadcrumb will be added. + +#### Manual Breadcrumbs + +In addition to all of the default breadcrumbs that are automatically collected, you can also manually add breadcrumbs of +your own. + +```ts +client.breadcrumbs?.info('This is a manual breadcrumb.', { + customAttr: 'wow!', +}); +``` + +--- + +### Application Stability Metrics + +The Backtrace React SDK has the ability to send usage Metrics to be viewable in the Backtrace UI. + +[(Stability Metrics feature documentation)](/error-reporting/project-setup/stability-metrics/) + +#### Metrics Configuration + +| Option Name | Type | Description | Default | Required? | +| ---------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- | ---------------------------------------- | +| `metricsSubmissionUrl` | String | Metrics server hostname. By default the value is set to https://events.backtrace.io. | `https://events.backtrace.io` | | +| `enable` | Boolean | Determines if the metrics support is enabled. By default the value is set to true. | `true` | | +| `autoSendInterval` | Number | Indicates how often crash free metrics are sent to Backtrace. The interval is a value in ms. By default, session events are sent on application startup/finish, and every 30 minutes while the application is running. If the value is set to 0. The auto send mode is disabled. In this situation the application needs to maintain send mode manually. | On application startup/finish | | +| `size` | Number | Indicates how many events the metrics storage can store before auto submission. | `50` | | + +#### Metrics Usage + +```ts +// metrics will be undefined if not enabled +client.metrics?.send(); +``` + +--- + +## Advanced SDK Features + +### Manually send an error + +There are several ways to send an error to Backtrace. For more details on the definition of `client.send()` see +[Methods](#backtraceclient-methods) below. + +```ts +// send as a string +await client.send('This is a string!'); + +// send as an Error +await client.send(new Error('This is an Error!')); + +// as a BacktraceReport (string) +await client.send(new BacktraceReport('This is a report with a string!')); + +// as a BacktraceReport (Error) +await client.send(new BacktraceReport(new Error('This is a report with a string!'))); +``` + +### BacktraceClient + +BacktraceClient is the main SDK class. Error monitoring starts when this object is instantiated, and it will compose and +send reports for unhandled errors and unhandled promise rejections. It can also be used to manually send reports from +exceptions and rejection handlers. + +#### BacktraceClientOptions + +The following options are available for the BacktraceClientOptions passed when initializing the BacktraceClient. + +| Option Name | Type | Description | Default | Required? | +| ----------------------------------- | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | ------------------------------------------------------- | +| `url` | String | Submission URL to send errors to | | | +| `name` | String | Your application name | | | +| `version` | String | Your application version | | | +| `token` | String | The submission token for error injestion. This is required only if submitting directly to a Backtrace URL. (uncommon) | | | +| `userAttributes` | Dictionary | Additional attributes that can be filtered and aggregated against in the Backtrace UI. | | | +| `attachments` | BacktraceAttachment[] | Additional files to be sent with error reports. See [File Attachments](#file-attachments) | | | +| `beforeSend` | (data: BacktraceData) => BacktraceData \| undefined | Triggers an event every time an exception in the managed environment occurs, which allows you to skip the report (by returning a null value) or to modify data that library collected before sending the report. You can use the BeforeSend event to extend attributes or JSON object data based on data the application has at the time of exception. See [BeforeSend](#beforesend) | | | +| `skipReport` | (report: BacktraceReport) => boolean | If you want to ignore specific types of error reports, we recommend that you use the skipReport callback. By using it, based on the data generated in the report, you can decide to filter the report, or send it to Backtrace. | | | +| `captureUnhandledErrors` | Boolean | Enable unhandled errors | `true` | | +| `captureUnhandledPromiseRejections` | Boolean | Enable unhandled promise rejection | `true` | | +| `timeout` | Integer | How long to wait in ms before timing out the connection | `15000` | | +| `ignoreSslCertificate` | Boolean | Ignore SSL Certificate errors | `false` | | +| `rateLimit` | Integer | Limits the number of reports the client will send per minute. If set to '0', there is no limit. If set to a value greater than '0' and the value is reached, the client will not send any reports until the next minute. | `0` | | +| `metrics` | BacktraceMetricsOptions | See [Backtrace Stability Metrics](#application-stability-metrics) | | | +| `breadcrumbs` | BacktraceBreadcrumbsSettings | See [Backtrace Breadcrumbs](#breadcrumbs) | | | + +#### BacktraceClient Methods + +| Name | Return Type | Description | +| ----------------------------------------------------------------------------------------------------------------------------------------------- | --------------- | --------------------------------------------------------------------------------- | +| `addAttribute(attributes: Record)` | void | Add attributes to the BacktraceClient reports | +| `addAttachment(attachment: BacktraceAttachment)` | void | Add an attachment to the BacktraceClient reports | +| `initialize(options: BacktraceClientOptions)` | BacktraceClient | Initializes a new BacktraceClient (returns the same instance on subsequent calls) | +| `builder(options: BacktraceClientOptions).build()` | BacktraceClient | (Advanced) Sets up a new BacktraceClient for reporting | +| `send(data: BacktraceReport \| Error \| string, reportAttributes: Record = {}, reportAttachments: BacktraceAttachment[] = [])` | `Promise` | Asynchronously sends error data to Backtrace | +| `dispose` | void | Disposes the client | + +### BacktraceReport + +A Backtrace Report is the format that ultimately gets sent to Backtrace. Its structure can be found in +`BacktraceReport.ts`. diff --git a/docs/error-reporting/platform-integrations/overview.md b/docs/error-reporting/platform-integrations/overview.md index 40219c819f..79347a6061 100644 --- a/docs/error-reporting/platform-integrations/overview.md +++ b/docs/error-reporting/platform-integrations/overview.md @@ -45,6 +45,7 @@ Integrate Backtrace in your games and apps across languages and platforms with o
  • Go
  • JavaScript
  • Node.js
  • +
  • React
  • Python
  • diff --git a/sidebars.js b/sidebars.js index 8f0f7489c8..a2c09095eb 100644 --- a/sidebars.js +++ b/sidebars.js @@ -445,6 +445,7 @@ module.exports = { 'error-reporting/language-integrations/go', 'error-reporting/language-integrations/javascript', 'error-reporting/language-integrations/node', + 'error-reporting/language-integrations/react', 'error-reporting/language-integrations/python', ], },