series

  1. Sentry-Go SDK Chinese Practice Guide
  2. Let’s brush together Sentry For Go Official document Enriching Events
  3. Snuba:Sentry New search infrastructure ( be based on ClickHouse above )
  4. Sentry 10 K8S Cloud native architecture exploration ,Vue App 1 Minutes fast access
  5. Sentry(v20.12.1) K8S Cloud native architecture exploration , Before you play / Back end monitoring and event log big data analysis , High performance and high availability + Scalable cluster deployment
  6. Sentry(v20.12.1) K8S Cloud native architecture exploration ,Sentry JavaScript SDK Three ways to install and load

Basic Options

SDK You can configure it with a variety of options . These options are in SDK It’s basically standardized , But there are some differences in better adapting to platform features . The options are in SDK Set at first initialization .

Options are passed as objects to init() function :

Sentry.init({
  dsn: "https://[email protected]/0",
  maxBreadcrumbs: 50,
  debug: true,
});

Common Options

Span SDK List of common options for . These functions are available in all SDK It’s more or less the same in China , But to better support the platform , There will be some subtle differences . You can choose from environment variables or your ~/.sentryclirc Automatic read options in the file (SENTRY_DSN, SENTRY_ENVIRONMENT, SENTRY_RELEASE). For more information , Please see the Working with Projects.

dsn

DSN tell SDK Where to send the event . If this value is not provided ,SDK Will try to start from SENTRY_DSN Read it from the environment variable . If this variable doesn’t exist ,SDK No events will be sent .

In no process environment ( Such as browser ) In the runtime of ,fallback Will not apply .

debug

Turn debugging mode on or off . If debugging is enabled , If there is a problem sending the event ,SDK Will try to print out useful debugging information . The default is always false. It is generally not recommended to turn it on in a production environment , Just open it debug Patterns don’t cause any security problems .

release

Set up release( Distribution version ). some SDK Will try to automatically configure release, But it’s better to set it manually release, To make sure that release With your deploy integrations or source map uploads Sync . The version name is a string , however Sentry Some formats will be detected , And they may be presented differently . stay releases Learn about how to send release More about data , In order to Sentry I can tell you release And identify potential sources .

By default ,SDK You’ll try to get the environment variables SENTRY_RELEASE Read the value in ( In the browser. SDK in , Will be taken from window.SENTRY_RELEASE Read the value in , If available ).

environment

Set up the environment . This string is in free form , Not set by default . One release Can be associated with multiple environments , In order to be in UI Separate them ( You can consider staging And prod Or something like that ).

By default ,SDK Will try to start from SENTRY_ENVIRONMENT Read the value in the environment variable ( browser SDK With the exception of ).

sampleRate

Configure the sampling rate for error events , The scope is 0.0 To 1.0. The default value is 1.0, Indicates sent 100% The wrong event of . If set to 0.1, Only 10% The wrong event of . Events are randomly selected .

maxBreadcrumbs

This variable controls the crumbs that should be captured ( breadcrumbs ) total . The default value is 100.

attachStacktrace

When enabled , Stack traces are automatically attached to all recorded messages . Stack traces are always attached to exceptions ; However , When this option is set , Stack traces are also sent with messages . for example , This option means that the stack trace is displayed next to all log messages .

This option defaults to off.

For events with and without stack traces ,Sentry The groups in are different . result , Enable or disable this… For some events flag when , You will get a new group .

sendDefaultPii

If you enable this flag, Then some personal identification information (PII) Will be made by active integrations add to . By default , Don’t send this kind of data . If possible , We recommend that this feature be enabled by default to send all such data , And use management sensitive data Manually delete content you don’t want to send .

denyUrls

And should not be sent to Sentry Error of URL A list of matching strings or regular expression patterns . By default , All errors will be sent . This is a “contains( contain )” Match the entire file URL. therefore , If you add foo.com, It will also match https://bar.com/myfile/foo.com. By default , All errors will be sent .

allowUrls

Matching error URL List of strings or legacy aliases for regular expression patterns , These errors URL It should be sent exclusively to Sentry. By default , All errors will be sent . This is a “contains( contain )” Match the entire file URL. therefore , If you will foo.com Add to it , It will also match https://bar.com/myfile/foo.com. By default , All errors will be sent .

autoSessionTracking

When set to true when ,SDK Will send session Event to Sentry. All browsers SDK We all support that , Every page loads to Sentry Send a session.

normalizeDepth

Sentry SDK Normalize any context data to a given depth . Any data that contains a deeper structure than that key Will be trimmed and used for its type ([Object] or [Array]) marked , Without further operation . By default ,walking The depth of this is 3 level .

Integration Configuration

For many platforms ,SDK Integration can be configured with . On some platforms , This is a init() Part of the call , And on other platforms , Different models are applied .

integrations

In some SDK in , Configure integration through this parameter during library initialization . To learn more , Please refer to our documentation for specific integrations .

defaultIntegrations

This can be used to disable the integration added by default . When set to false when , No default integration will be added .

Hooks

These options can be used in a variety of ways hook SDK, To customize the reporting of events .

beforeSend

Use SDK-specific The event object calls this function , You can return the modified event object or nothing , To skip reporting events . for example , This can be used to manually split before sending PII.

beforeBreadcrumb

In the crumbs (breadcrumb) Add to scope (scope) Before , Use SDK Specific crumbs (SDK-specific breadcrumb) Object to call this function . When the function returns nothing , Will delete breadcrumb. To pass breadcrumb, Please return the first parameter , It includes breadcrumb object . Callbacks usually get a second parameter ( be called “hint”), This parameter contains the creation breadcrumb The original object of , To further customize the look of the crumbs .

Transport Options

Transports Is used to send events to Sentry. The transmission can be customized to some extent , To better support highly specific deployment .

transport

Switch out of the transport. How it works depends on SDK. for example , It can be used to capture events for unit testing , Or send events through more complex settings that require proxy authentication .

Tracing Options

tracesSampleRate

0 To 1 Number between , Controls the percentage of probability that a given transaction is sent to the sentinel .(0 Express 0%,1 Express 100%) The same applies to all transactions created in the application . You have to define this or tracesSampler To enable tracing .

tracesSampler

A function is responsible for determining that a given transaction will be sent to Sentry The probability percentage of . It will automatically be passed information about the transaction and the context in which it was created , And must return a value between 0( The probability of being sent is 0%) and 1( The probability of being sent is 100%) Number between . It can also be used to filter transactions , Return… For unwanted transactions 0. You have to define this or tracesSampleRate To enable tracing .

Releases & Health

One release Is the version of the code deployed into the environment . When you Sentry Provide relevant release Information time , You can :

  • Identify issues and regressions introduced in the new version
  • Predicting which submission raises questions , Who could be responsible for
  • Solve the problem by including the problem number in the submit message
  • Receive email notification when deploying code

Besides ,releases It is also used to put source maps Applied to compressed JavaScript in , To see the original 、 Untransformed source code .

Bind the Version

In the configuration client SDK It contains a release ID( Often referred to as “version” ). This ID It’s usually a git SHA Or custom version number .

release The name cannot :

  • Contains line breaks or spaces
  • Use forward slashes (/), The backslash (\), Period (.), Or double periods (..)
  • exceed 200 Characters

The release of each organization is global ; Precede them with some project specific (project-specific) Things that are , To make it easy to distinguish .

Sentry.init({
  release: "[email protected]",
});

stay Node/npm Use in the environment JavaScript A common way to do this is to use process.env.npm_package_version, As shown below :

Sentry.init({
  release: "my-project-name@" + process.env.npm_package_version,
});

How to make versions available to code is up to you . for example , You can use the environment variables set during the build process .

This will work release Value marks each event . We recommend that you tell… Before deploying the new version Sentry, Because it’s going to release some new features , As about releases As described in the document . however , If you do not ,Sentry You’ll see it for the first time release ID Automatically create a release Entity .

End of configuration SDK after , You can install repository integration( Repository Integration ) Or manually Sentry Provide your own submission metadata . Read the documentation about setting up a distribution , For information about Integration , Associate commit and inform when the release is deployed Sentry For more information .

Release Health

By observing user adoption , Application usage ,crashes Percentage and session data To watch health of releases.Release health Will provide insight into the impact of crashes and errors related to the user experience , And pass release Details , Charts and filters reveal the trend of each new problem .

initialization SDK after ,SDK Will automatically manage the beginning and end of the session .

Sentry.init({
  autoSessionTracking: true
});

Environments

Sentry Received with environment Tag the event when , The environment is created automatically . The environment is case sensitive . Environment names cannot contain line breaks , Space or forward slash , character string “None” Or exceed 64 Characters . You cannot delete the environment , But you can hide them .

Sentry.init({
  environment: "production",
});

Environments Can help you in sentry.io Of “ Problem details ” Better filtering in the page issues,releases and user feedback, You can go to documentation that covers using environments Learn more about .

Filtering and Sampling Events

take Sentry Adding to your app can give you a lot of valuable information about errors and performance . A lot of information is useful —— As long as the information is correct , The quantity is reasonable .

Sentry SDK Several configuration options are available to help you control this , Enables you to filter out unwanted events , And we can get representative samples from it .

Note: Sentry UI Also provides the use of Inbound Filters How to filter Events . however , We recommend that you filter at the client level , Because it eliminates the overhead of sending events that you don’t really need .

Filtering Error Events

Use beforeSend Callback method and configure , Enable or disable integrations, Put your SDK Configured to filter error events .

Using beforeSend

all Sentry SDK All support beforeSend The callback method . Called immediately before the event is sent to the server beforeSend, So this is the final location where you can edit its data . It takes the event object as a parameter , So you can customize the logic and the data available on the event , Use it to modify the data of an event or delete it completely ( By returning null).

Sentry.init({
  // ...
  beforeSend(event, hint) {
    const error = hint.originalException;
    if (
      error &&
      error.message &&
      error.message.match(/database unavailable/i)
    ) {
      event.fingerprint = ["database-unavailable"];
    }
    return event;
  },
});

Also pay attention to , Bread crumbs (breadcrumbs) Can filter , Such as our Breadcrumbs documentation Described .

Event Hints

before-send The callback function also passes event And the second parameter hint, It contains one or more hints .

Usually ,hint Save the original exception , In order to extract additional data or influence grouping . In this case , If you catch some kind of exception , Then force the fingerprint (fingerprint) Convert to normal :

Sentry.init({
  // ...
  beforeSend(event, hint) {
    const error = hint.originalException;
    if (
      error &&
      error.message &&
      error.message.match(/database unavailable/i)
    ) {
      event.fingerprint = ["database-unavailable"];
    }
    return event;
  },
});

When SDK Create an event or breadcrumb for the transfer (breadcrumb) when , The transfer is usually created from some kind of source object . for example , Error events are usually created from logging or exception instances . To better customize ,SDK Send these objects to specific callbacks ( beforeSendbeforeBreadcrumb or SDK Event processor system in ).

Using Hints

  1. beforeSend / beforeBreadcrumb
  2. eventProcessors

Event and breadcrumb Of hints Is an object that contains various kinds of information used to group events or breadcrumbs together . Usually ,hints Keep the original exception , So that you can extract other data or influence groups .

For events , for example event_id,originalException,syntheticException( Internally used to generate clearer stack traces ), And any other arbitrary data.

For crumbs ,hints The use of depends on the implementation . about XHR request ,hint contain xhr Object itself . For user interaction ,hint contain DOM Element and event name, etc .

In this example , If you catch some kind of exception , The fingerprint (fingerprint) Force to a common value :

Sentry.init({
  // ...
  beforeSend(event, hint) {
    const error = hint.originalException;
    if (
      error &&
      error.message &&
      error.message.match(/database unavailable/i)
    ) {
      event.fingerprint = ["database-unavailable"];
    }
    return event;
  },
});

Hints for Events

originalException

  • Lead to Sentry SDK Create the original exception for the event . This is for change Sentry SDK Ways to group events or extract additional information are very useful .

syntheticException

  • When a string or non error is thrown (non-error) Object time ,Sentry A composite exception will be created , So you can get a basic stack trace . This exception is stored here to further extract the data .

Hints for Breadcrumbs

event

  • For breadcrumbs created through browser Events ,Sentry SDK Events are usually treated as hint For crumbs . for example , This can be used to target DOM The data in the element is extracted into the crumbs .

level / input

  • For breadcrumbs created by intercepting from the console log . This will retain the original input data for the original console log level and log function .

response / input

  • For from HTTP Breadcrumbs requested to be created . This holds the response object ( come from fetch API) and fetch Function’s input parameters .

request / response / event

  • For from HTTP Breadcrumbs requested to be created . It holds the request and response objects ( From node HTTP API) And node Events (response or error).

xhr

  • For passing the old version XMLHttpRequest API adopt HTTP Breadcrumbs requested to be created . This will keep the original xhr object .

Decluttering Sentry

You can construct a list of allowed domains , This can throw an acceptable exception . for example , If your script is from cdn.example.com Loaded , And your site is example.com, Then you can put allowUrls Set to :

If you want to block a particular URL, You can also use denyUrls.

stay 5.17.0 Prior to version ,allowUrls and denyUrls Known as whitelistUrls and blacklistUrls. For backward compatibility reasons , These options are still supported , But in 6.0 They will be removed in version . For more information , Please see our Inclusive Language Policy.

Besides , Our community has been working for everyday ( for example Facebook,Chrome Extensions, etc ) Compiled a list of common ignore rules . I suggest you check these contents , See if they apply to you , It’s very useful .Here is the original gist. This is not us SDK The default value of ; This is just the highlight of a broad example .

Sentry.init({
  ignoreErrors: [
    // Random plugins/extensions
    "top.GLOBALS",
    // See: http://blog.errorception.com/2012/03/tale-of-unfindable-js-error.html
    "originalCreateNotification",
    "canvas.contentDocument",
    "MyApp_RemoveAllHighlights",
    "http://tt.epicplay.com",
    "Can't find variable: ZiteReader",
    "jigsaw is not defined",
    "ComboSearch is not defined",
    "http://loading.retry.widdit.com/",
    "atomicFindClose",
    // Facebook borked
    "fb_xd_fragment",
    // ISP "optimizing" proxy - `Cache-Control: no-transform` seems to
    // reduce this. (thanks @acdha)
    // See http://stackoverflow.com/questions/4113268
    "bmi_SafeAddOnload",
    "EBCallBackMessageReceived",
    // See http://toolbar.conduit.com/Developer/HtmlAndGadget/Methods/JSInjection.aspx
    "conduitPage",
  ],
  denyUrls: [
    // Facebook flakiness
    /graph\.facebook\.com/i,
    // Facebook blocked
    /connect\.facebook\.net\/en_US\/all\.js/i,
    // Woopra flakiness
    /eatdifferent\.com\.woopra-ns\.com/i,
    /static\.woopra\.com\/js\/woopra\.js/i,
    // Chrome extensions
    /extensions\//i,
    /^chrome:\/\//i,
    // Other plugins
    /127\.0\.0\.1:4001\/isrunning/i, // Cacaoweb
    /webappstoolbarba\.texthelp\.com\//i,
    /metrics\.itunes\.apple\.com\.edgesuite\.net\//i,
  ],
});

Sampling Error Events

To send a representative sample of the error to Sentry, Please be there. SDK Configuration will sampleRate Option is set between 0( The wrong 0%) and 1( The wrong 100%) Number between . This is a static ratio , The same will apply to all errors . for example , We need to sample 25% Error of :

Sentry.init({ sampleRate: 0.25 });

Note: The error sampling rate is not dynamic . Changing it requires redeployment . Besides , Set up SDK The sampling rate limits the visibility of the event source . Set a rate limit for the project ( Only in high volume And then discard the event ) It may be more suitable for your needs .

Filtering Transaction Events

To prevent certain transactions from being reported to Sentry, have access to tracesSampler configuration option , This option allows you to provide a function to evaluate the current transaction , And delete it when it’s not the transaction you want .( It also allows you to sample different transactions at different rates .)

Note: tracesSampler and tracesSampleRate Configuration options are mutually exclusive . If you define a tracesSampler To filter out certain transactions , Then you must also process unfiltered transactions by returning the rate at which you want them to be sampled .

The simplest form ( Only for filtering ) As shown below :

Sentry.init({
  // ...
  tracesSampler: samplingContext => {
    if ("...") {
      // Drop this transaction, by setting its sample rate to 0%
      return 0;
    } else {
      // Default sample rate for all others (replaces tracesSampleRate)
      return 0.1;
    }
  };
});

To learn about tracesSampler More about options , see also SDK Of performance docs.

Sampling Transaction Events

about Sentry Performance monitoring , We recommend sampling your data , There are two reasons . First , Although capturing a single trace involves minimal overhead , But capture every page loaded or every API Tracking requests can add unwanted loads to the system . secondly , Enabling sampling allows you to better manage sending to Sentry Number of events for , In this way, you can adjust your quantity according to the needs of the organization .

When selecting the sampling rate , The goal is not to collect Too much data , It’s about collecting enough data , In order to draw meaningful conclusions . If you’re not sure what rate to choose , So start with a lower value , As you learn about traffic patterns and volume Learn more , Gradually increase it , Until you find a rate that balances performance and traffic with data accuracy .

To sample transactions , Can be tracesSampleRate The configuration options are set to 0( Of the transaction sent 0%) To 1( Of the transaction sent 100%) A number between , Or will tracesSampler Option is set to a function , This function will return this number , The number varies from transaction to transaction .

for example , take tracesSampleRate Option set to 0.2 Will lead to SDK Send only 20% Possible transaction events for :

Sentry.init({
  // ...
  tracesSampleRate: 0.2,
});

perhaps , You can provide one tracesSampler function , Sampling different transactions at different rates :

Sentry.init({
  // ...
  tracesSampler: samplingContext => {
    // Examine provided context data (including parent decision, if any) along
    // with anything in the global namespace to compute the sample rate or
    // sampling decision for this transaction
    if ("...") {
      // These are important - take a big sample
      return 0.5;
    } else if ("...") {
      // These are less important or happen much more frequently - only take 1%
      return 0.01;
    } else if ("...") {
      // These aren't something worth tracking - drop all transactions like this
      return 0;
    } else {
      // Default sample rate
      return 0.1;
    }
  };
});

To learn more about tracesSampler Information on options , Please check out SDK Of performance docs.

Shutdown and Draining

majority SDK The default behavior of is to send events asynchronously through the network in the background . This means that if the application closes unexpectedly , Some events may be lost .SDK Provides a mechanism to deal with this situation .

close Method optionally accepts a timeout in milliseconds , And return a promise, When all pending events are refreshed or timed out, the resolve The promise.

Sentry.close(2000).then(function() {
  // perform something after close
});

call close after , The current client will no longer be available . Just call… Before closing the application close It’s important .

perhaps , While keeping the client enabled for continued use ,flush Method clears the event queue .

Default Integrations

all Sentry Of SDK All provide integration (integrations), Expanded SDK The function of .

By default , System integration (System integrations) It’s enabled , To integrate into the standard library or the interpreter itself . They are on the record , So you can know what they’re doing , You can also disable them when they cause problems .

Enabled by Default

InboundFilters

Import name: Sentry.Integrations.InboundFilters

Through this integration , Depending on the type in a given exception , News or URL Ignore specific errors .

By default , It ignores to Script error or Javascript error: Script error The mistake at the beginning .

To configure this integration , Use it directly ignoreErrors,denyUrls, and allowUrls SDK Options . please remember ,denyURL and allowURL Only valid for captured exceptions , Instead of the original news event .

FunctionToString

Import name: Sentry.Integrations.FunctionToString

This integration makes SDK You can provide the original function and method names , Even if our bug or crumb handler packages them .

TryCatch

Import name: Sentry.Integrations.TryCatch

This integration encapsulates the native time and events APIs (setTimeoutsetIntervalrequestAnimationFrameaddEventListener/removeEventListener) stay try/catch Block handling async abnormal .

Breadcrumbs

Import name: Sentry.Integrations.Breadcrumbs

This integration encapsulates the native API To capture crumbs . By default ,Sentry SDK It encapsulates everything API.

Available options:

{ beacon: boolean; // Log HTTP requests done with the Beacon API
  console: boolean; // Log calls to `console.log`, `console.debug`, etc
  dom: boolean; // Log all click and keypress events
  fetch: boolean; // Log HTTP requests done with the Fetch API
  history: boolean; // Log calls to `history.pushState` and friends
  sentry: boolean; // Log whenever we send an event to the server
  xhr: boolean; // Log HTTP requests done with the XHR API
}

GlobalHandlers

Import name: Sentry.Integrations.GlobalHandlers

This integration adds a global handler to capture the uncapped exceptions And untreated rejections.

Options available :

{
  onerror: boolean;
  onunhandledrejection: boolean;
}

LinkedErrors

Import name: Sentry.Integrations.LinkedErrors

This integration allows you to configure link errors . They will be read recursively to the specified limit , And by specific key Perform a search . By default ,Sentry SDK Set the limit to 5, The key used key yes cause.

Options available :

{
  key: string;
  limit: number;
}

UserAgent

Import name: Sentry.Integrations.UserAgent

This integration will user-agent Information is attached to the event , This enables us to correctly categorize and use specific operating systems (OS), browser (browser) And version (version) Information marks it .

Modifying System Integrations

To disable system integration , Calling init() Set when defaultIntegrations: false.

To override their settings , Please provide one with configuration to integrations New instance of option . for example , Turn off the console call captured by the browser :integrations: [new Sentry.Integrations.Breadcrumbs({ console: false })].

Removing an Integration

This example removes the default enabled integration of adding breadcrumbs to an event :

Sentry.init({
  // ...
  integrations: function(integrations) {
    // integrations will be all default integrations
    return integrations.filter(function(integration) {
      return integration.name !== "Breadcrumbs";
    });
  },
});

Pluggable Integrations

These pluggable integrations are for specific applications and / Or code snippet of framework added function . We recorded them , So you can see what they do , And they can be enabled .

How to Enable

install @sentry/integrations package , And provide one with your configuration to integrations New instance of option . load SDK after , Including plug-ins .

Example :

import * as Sentry from "@sentry/browser";
import { ReportingObserver as ReportingObserverIntegration } from "@sentry/integrations";
Sentry.init({
  dsn: "___PUBLIC_DSN___",
  integrations: [new ReportingObserverIntegration()],
});

ExtraErrorData

Import name: Sentry.Integrations.ExtraErrorData

This integration extracts all non-native objects from the error object (non-native) attribute , And use them as extra Data is attached to the event .

Options available :

{
  // limit of how deep the object serializer should go. Anything deeper than limit will
  // be replaced with standard Node.js REPL notation of [Object], [Array], [Function] or
  // a primitive value. Defaults to 3.
  depth: number;
}

CaptureConsole

Import name: Sentry.Integrations.CaptureConsole

This integration captures all of the Console API call , And use captureMessage Call to redirect them to Sentry. then , It triggers again to keep the default native behavior .

{
  // array of methods that should be captured
  // defaults to ['log', 'info', 'warn', 'error', 'debug', 'assert']
  levels: string[];
}

Dedupe

Import name: Sentry.Integrations.Dedupe

This kind of integration can de duplicate some events . If you receive many repeated errors , May help . Please note that ,Sentry Only stack traces and fingerprints will be compared .

Debug

Import name: Sentry.Integrations.Debug

Through this integration , You can check the contents of the handled event , The event will be passed to beforeSend And effectively send it to Sentry SDK. Whenever you register , It will be Throughout Run as the final integration .

Options available :

{
  // trigger DevTools debugger instead of using console.log
  debugger: boolean;
  // stringify event before passing it to console.log
  stringify: boolean;
}

RewriteFrames

Import name: Sentry.Integrations.RewriteFrames

This integration allows you to apply transformations to every frame of the stack trace . stay streamlined Scene , You can use it to change the name of the file frame , Or provide it with an iterative function to apply any arbitrary transformation .

stay Windows On the machine , You have to use Unix Path and skip root Volume in options (volume) To activate . for example ,C:\\Program Files\\Apache\\www Can’t work , however ,/Program Files/Apache/www Sure .

Options available :

{
  // root path that will be appended to the basename of the current frame's url
  root: string;
  // function that takes the frame, applies a transformation, and returns it
  iteratee: (frame) => frame;
}

ReportingObserver

Import name: Sentry.Integrations.ReportingObserver

This integration with ReportingObserver API hook , And send the captured event to the Sentry. It can be configured to handle only specific problem types .

Options available :

{
  types: <'crash'|'deprecation'|'intervention'>[];
}

Custom Integrations

Use the following format in JavaScript Add a custom integration :

// All integration that come with an SDK can be found on Sentry.Integrations object
// Custom integration must conform Integration interface: https://github.com/getsentry/sentry-javascript/blob/master/packages/types/src/integration.ts
Sentry.init({
  // ...
  integrations: [new MyAwesomeIntegration()],
});

rrweb: Session Replays

Sentry Provided with rrweb Of proof-of-concept( Proof of concept ) Integrate , The toolkit is used to record and replay user sessions . When diagnosing complex user behavior in a feature rich single page application , This can be very useful .

About available hints Information about , see also hints in JavaScript

Playback uses Attachments.

Configuration

First , You need to add @sentry/rrweb and rrweb software package :

npm install --save @sentry/rrweb rrweb

Next , Use Sentry SDK Register for integration . This will vary depending on the framework you use :

import * as Sentry from "@sentry/browser";
import SentryRRWeb from "@sentry/rrweb";
Sentry.init({
  dsn: "___PUBLIC_DSN___",
  integrations: [
    new SentryRRWeb({
      // ...options
    }),
  ],
  // ...
});

More about configuration , see also @sentry/rrweb project on GitHub.

After capturing the replay of the event , You will find that the event is in the “Replay” Part of the “ Problem details ” You can see .

Sampling

To meet the needs of the organization , You may wish to replay sampling . The easiest way is to initialize Sentry SDK Make a sampling decision . for example , Here are Sentry How sampling itself is used to capture only samples of employees :

const hasReplays = getCurrentUser().isStaff;
let integrations = [];
if (hasReplays) {
  console.log("[sentry] Instrumenting session with rrweb");
  integrations.push(new SentryRRWeb());
}
Sentry.init({
  dsn: "___PUBLIC_DSN___",
  integrations,
});
Sentry.setTag("rrweb.active", hasReplays ? "yes" : "no");

You’ll notice that we also set up rrweb.active Mark , The tag can help us identify the attached replay Events , Because otherwise we won’t be able to find them . When the configuration is complete , You will be able to simply use… In search queries rrweb.active:yes.

Sentry Testkit

When building tests for an application , You want the assertion to be correct flow-tracking Or an error is being sent to Sentry, Instead of actually sending it to Sentry The server . such , You won’t be running tests or other CI Flooding with error reports during operation Sentry.

Note: Wix, One Sentry partners , Responsible for maintaining Sentry Testkit.

Sentry Testkit It’s a Sentry plug-in unit , Allow interception Sentry The report of , And further check the data being sent . It allows the Sentry Work natively in your application , And by overriding the default Sentry The transmission mechanism of , The report is not really sent , It’s recorded locally in memory . In this way , The recorded report can be obtained later , For your own use 、 verification , Or you can develop it locally / Any other use in the test environment .

Installation

npm install sentry-testkit --save-dev

Using in tests

const sentryTestkit = require("sentry-testkit");
const { testkit, sentryTransport } = sentryTestkit();
// initialize your Sentry instance with sentryTransport
Sentry.init({
  dsn: "___PUBLIC_DSN___",
  transport: sentryTransport,
  //... other configurations
});
// then run any scenario that should call Sentry.catchException(...)
expect(testkit.reports()).toHaveLength(1);
const report = testkit.reports()[0];
expect(report).toHaveProperty(/*...*/);

You can also visit sentry-testkit Warehouse testing section See more usage examples in .

Testkit API

Sentry Testkit By a very simple and direct API form . stay Sentry Testkit Docs You can see the complete API Description and documentation .

Chinese documents are synchronized to :

  • https://getsentry.hacker-linner.com
 I'm for less .
WeChat :uuhells123.
official account :*** Afternoon tea .
Thank you for your support ????????????!