One, foreword

Any application will have all kinds of bugs due to various accidents or omissions. Although we have experienced a lot of testing, we still can’t cover all cases, and users will not operate in the way we expect, so it becomes very important to collect errors after launch.

Introduction to Sentry

Sentry – as well as its English meaning: the sentinel, sentry, like a sentinel, real-time monitoring system on the production status, in case of abnormal immediately will reduce the error of the routing path, inform us detailed information, such as wrong file and use the stack trace of rapid positioning error information to need to deal with.

It also has the following advantages:

  • Open source
  • Both front and back ends are supported
  • Extensive language and framework support such as:

  • SourceMap is supported, which makes it easy to locate problems when the front end packages and compresses obfuscated code

There is a limit to the number of times you can use Sentry’s free service, but you can use Sentry’s open source library to build your service on your own server.

3. Server building

Docker is recommended on the official website, so this tutorial uses Docker to build.

Environmental requirements:

  • The Docker 19.03.6 +
  • Compose 1.24.1 +
  • 4 CPU Cores
  • 8 GB of memory
  • 20 GB of hard disk space
git clone https://github.com/getsentry/onpremise.git
Copy the code

Go to the cloned folder and run the./install.sh script. During the installation, you will be prompted whether to create a user account. If you want the installation not to be prompted to stop, run./install.sh \–no-user-prompt.

After successful installation, access localhost:9000 to access the Sentry management system.

Use the React client

Installing the SDK:

npm install --save @sentry/react @sentry/tracing
Copy the code

Sentry configuration:

import React from "react";
import ReactDOM from "react-dom";
import * as Sentry from "@sentry/react";
import { Integrations } from "@sentry/tracing";
import App from "./App";

Sentry.init({
  dsn: "https://[email protected]/0".integrations: [new Integrations.BrowserTracing()],

  // We recommend adjusting this value in production, or using tracesSampler
  // for finer control
  tracesSampleRate: 1.0}); ReactDOM.render(<App />.document.getElementById("root"));
Copy the code

Common configuration options are as follows:

  • The DSN is the key that connects the client (project) to the Sentry server, allowing the two to communicate

  • Debug Enables or disables debugging mode

  • Release sets the release to identify new problems, regressions, and whether problems are resolved in the next release

  • Environment Setting environment

  • The tunnel setting will be used to transmit the URL of the captured event, rather than using DSN

  • SampleRate Indicates the sampling rate of configuration error events. The value ranges from 0.0 to 1.0

  • MaxBreadcrumbs The total amount of crumbs that should be captured

  • When attachStacktrace is enabled, stack traces are automatically attached to all recorded messages

  • DenyUrls should not be sent to the wrong URL for Sentry

  • AllowUrls matches the wrong URL that should be sent specifically to Sentry

  • AutoSessionTracking Sends session events

  • InitialScope data for the initialScope

  • NormalizeDepth Data is normalized to a given depth, such as ([Object] or [Array]), with 3 levels by default

Sentry also provides two higher-order components: ErrorBoundary and withProfiler.

The ErrorBoundary component automatically catches JavaScript errors and sends them from within the React component tree to Sentry, rendering the fallback UI.

import React from "react";
import * as Sentry from "@sentry/react";

<Sentry.ErrorBoundary fallback={"An error has occurred"}>
  <Example />
</Sentry.ErrorBoundary>;
Copy the code

ErrorBoundary has the following configuration items:

  • showDialogShould be presented if an error is caught at the error boundarySentry user feedback widget
  • dialogOptionsFeedback component configuration options
  • fallbackThe React element to render when an error boundary catches an error
  • onErrorThe function that is called when an error is encountered on the error boundary
  • onMountonUnmount
  • beforeCaptureFunction called before sending an error to Sentry

WithProfiler performs performance analysis on react components, including react.mount, react.render, and react.update.

Source Maps support:

The current front-end code is compressed and confused with various build packaging tools such as WebPack, and source maps are necessary to locate the problem. Sentry also provides webPack plug-in support.

npm install --save-dev @sentry/webpack-plugin
Copy the code

We then generate access tokens for our API in sentry’s background administration system.

Webpack configuration:

const SentryWebpackPlugin = require("@sentry/webpack-plugin");

module.exports = {
  // other webpack configuration
  devtool: 'source-map',
  plugins: [
    new SentryWebpackPlugin({
      // sentry-cli configuration
      authToken: process.env.SENTRY_AUTH_TOKEN,
      org: "example-org",
      project: "example-project",
      release: process.env.SENTRY_RELEASE,

      // webpack-specific configuration
      include: ".",
      ignore: ["node_modules", "webpack.config.js"],
    }),
  ],
};
Copy the code

5. Use in client Python

Installing the SDK:

pip install --upgrade sentry-sdk
Copy the code

Sentry configuration:

import sentry_sdk sentry_sdk.init( "https://[email protected]/0", # Set traces_sample_rate to 1.0 to capture 100% # of transactions for performance monitoring This value in production. Traces_sample_rate =1.0,)Copy the code

The configuration items are the same as react.

If you are using an older version of Raven, you can migrate with a few changes:

Old:

Import raven Client = raven.client ('https://[email protected]. IO /0', release="1.3.0")Copy the code

New:

The import sentry_sdk sentry_sdk. Init (' https://[email protected]/0 'release =' 1.3.0 ')Copy the code

Old:

client.tags_context({'key': 'value'})
Copy the code

New:

sentry_sdk.set_tag('key', 'value')
Copy the code

6. Actively catch errors

Sentry can automatically catch most errors in programs, but there are also asynchronous errors, such as interface request errors, that need to be caught manually:

axios.post(url)
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    Sentry.captureException(new Error("something went wrong"), scope);
  })
Copy the code

7. User identification

Users can be identified by setUser:

Sentry.setUser({ email: "[email protected]" });
Copy the code

The options are as follows:

  • Id User internal identifier.

  • The username username

  • Email mailbox

  • Ip_address Indicates the IP address of the user

8. Set labels

Tags in Sentry are powerful, such as filters and tag maps. Tags also help you quickly access related events and see the label distribution of a group of events. Common uses for tags include host names, platform versions, and user languages.

Sentry.setTag("page_locale", "de-at");
Copy the code

Nine, the attachment

Sentry can enrich your events and further research by storing additional files, such as configuration and log files, as attachments. Attachments will be retained for 30 days. If they exceed the total storage, they will not be saved.

import * as Sentry from "@sentry/react"; public attachmentUrlFromDsn(dsn: Dsn, eventId: string) { const { host, path, projectId, port, protocol, user } = dsn; return `${protocol}://${host}${port ! = = ' '? `:${port}` : ''}${ path ! = = ' '? `/${path}` : '' }/api/${projectId}/events/${eventId}/attachments/? sentry_key=${user}&sentry_version=7&sentry_client=custom-javascript`; } Sentry.addGlobalEventProcessor((event: Event) => { try { const client = Sentry.getCurrentHub().getClient(); const endpoint = attachmentUrlFromDsn( client.getDsn(), event.event_id ); const formData = new FormData(); formData.append( 'my-attachment', new Blob([JSON.stringify({ logEntries: ["my log"] })], { type: 'application/json', }), 'logs.json' ); fetch(endpoint, { method: 'POST', body: formData, }).catch((ex) => { // we have to catch this otherwise it throws an infinite loop in Sentry console.error(ex); }); return event; } catch (ex) { console.error(ex); }});Copy the code