preface

Given that the front end is diversifying and scenarios are becoming more complex, the production environment often has problems that the local and test environments cannot reproduce. Moreover, the specific behavior and operation of the user can not be expected, and the back-end error monitoring can only detect the error log after the request is made, so we can only rely on the user feedback when the error occurs. However, this feedback is not real time, often only screenshots or text descriptions, which do not provide the other key information we need, and the static resource files in production environments are often obfuscated and compressed, so the error stack information we get is not very meaningful.

Therefore, the front-end project needs a mature error monitoring system, which can help us monitor the project running status in real time, provide rich and detailed error information, and even provide the ability to restore the scene. Allow developers to follow up and resolve errors in a timely manner.

This article focuses on the steps and rule Settings for front-end projects to access Sentry and other backend uses of Sentry.

Why Sentry

  1. The market has a mature monitoring platform
  • Fundebug
  • Bugsnag
  • Badjs
  • Sentry
  1. The advantage of the Sentry
  • Open source, there are free versions
  • Can deploy your own server, security
  • Error messages and alarm mechanisms are improved
  • Simple and easy to use, low development cost
  • Error tracking and state flow are timely and convenient
  • Rich in the SDK
  • The community is active

By comprehensive comparison, these advantages of Sentry can not only grasp the front-end error report of production environment in time and send out notification, but also provide rich error information and path for developers to locate and solve, meeting the basic needs of front-end project error monitoring; It is open source and free, can build their own servers, do not worry about the risk of data and sensitive information leakage, and support a variety of development languages and frameworks. Therefore, Sentry was chosen as the error monitoring scheme of the front-end platform.

Introduction to the

Sentry is a service that helps you monitor and fix crashes in realtime. The server is in Python, but it contains a full API for sending events from any language, in any application.

Sentry is a service that helps you monitor and fix errors in real time. The server uses Python, but it contains a full API for sending events from any language in any application.

  • Liverpoolfc.tv: sentry. IO
  • Community: forum. Sentry. IO

concept

  • Event: Indicates an Event.

Each generated log record, each event has a lot of meta information, including event level, project information, environment and so on. You can click the JSON data corresponding to an event to view the data

  • It’s an Issue.

An exception in the same place is called an Issue (an aggregation of the same class of issues). If two errors occur in the same location, two Events will be generated, but only one Issue.

  • DSN: client (project-specific) key

The DSN is a URL containing the relevant key information through which the client communicates with the server (sentry server) and reports the error message.

  • Auth Token: Authorization Token.

Authorization tokens allow you to use the Sentry API based on your account. We use @sentry/cli to upload sourceMap files and other operations. Sentry/CLI calls the corresponding API methods based on the Auth Token.

  • Org: indicates the name of an organization.

Specifies the organization name on the Sentry server deployed by the company.

  • Release: Indicates the version number.

  • Project: indicates the name of the client. (Specific project name to access Sentry)

  • Tag: Indicates the Tag.

The deployment of

Although the official Version of Sentry is free, we recommend building our own Sentry service due to security and functionality limitations. There are two official ways to install: by Python or by Docker. Officially, it is recommended to use Docker for deployment. Since the official documentation is very detailed, it will not be described here. It is important to modify the corresponding configuration file according to the actual needs.

  • Install the Docker – Compose
  • Pull the Sentry warehouse
  • Modify the corresponding configuration file
  • Domain name mapping
  • Create an administrator password and user

Access to the

1. Create a project

  • Create a new project on the Sentry server: ProjectName and select Team.
  • Select the corresponding development language template, Vue here.

2. Access the Sentry

  • After creating the project, a detailed configuration step document will be displayed, and you can configure it according to the document.

  • Install dependencies
$ yarn add @sentry/browser -D
$ yarn add @sentry/integrations -D
Copy the code
  • The Sentry instance is generated at the entry file
import Vue from 'vue' import * as Sentry from '@sentry/browser' import * as Integrations from '@sentry/integrations' Sentry.init({DSN: 'https://xxx.sentry domain/project ID ', integrations: [new integrations.vue ({Vue, attachProps: true})],})Copy the code

P.S. Here DSN is the client key corresponding to the newly created project. Go to Project > Settings > Client Key (DSN) to check.

3. Upload SourceMap

When the above steps are complete, manually add an error and the startup project will see the corresponding error under the Sentry server project. But here we can only see the description of the error message. We can’t see which line in which file the error message was reported and the specific error message. Since our resource files are obfuscated and compressed for production, we started uploading sourceMap to the server to restore errors.

There are two ways to upload sourceMap: using the Sentry -CLI command line and the Webpack plug-in. Because the command-line approach is too cumbersome and divorced from front-end engineering concepts. Therefore, the sourceMap file is uploaded by using webpack plug-in.

  • Install the WebPack plug-in
yarn add @sentry/webpack-plugin -D
Copy the code
  • Add the Sentry configuration file.sentryclirc to the project root directory

When @sentry/cli uploads the sourcemap file, it automatically checks the information in the configuration file and uses

[defaults] url=https://xxxxxx // - sentry server address org= XXX // - organization name project= projectName // - projectname [auth] token= XXX // - auth tokenCopy the code

Note: Select project:read and Project: Releases for Auth Token.

  • Webpack configuration file to add plug-ins
Const SentryCliPlugin = require('@sentry/webpack-plugin') const version = '' Config.plugin ('SentryCliPlugin').use(SentryCliPlugin, [{release: version, // include: // urlPrefix: "~/static/js/", ignore: ['node_modules'], setCommits: {/ / = = = = = = = = = = = = = = = = = = = = need to corresponding project git address = = = = = = = = = = = = = repo: 'https://xxx.xx.xx', / / = = = = = = = = = = = = = = = = = = = = need to corresponding project git address = = = = = = = = = = = = = auto: true,}}])Copy the code

Here are a few points to note:

  • The SourceMap format must be “source-map”.
  • Version Number Version can be set according to the actual situation and the company’s coding specifications, and the version number should also be filled in at the entrance (consistent).
  • The urlPrefix setting should be consistent with the actual resource path (more on this later).

4. Upload the file to Sentry and delete SourceMap

The @sentry/ CLI plug-in does not automatically delete the corresponding map file after uploading the sourcemap file to the Sentry server. To ensure the security of site code, delete the map file after uploading.

  • Use the clean-webpack-plugin plugin
config.plugins.push(
  new CleanWebpackPlugin({
    cleanAfterEveryBuildPatterns: ["./dist/js/*.js.map"]
  })
)
Copy the code
  • Using rimraf, the delete is performed in the postbuild script
"postbuild:prod": "rimraf ./dist/js/*.js.map"
Copy the code
  • Exclude the Map file when uploading the file to the server after packaging

5. Distinguish the environment

To avoid too many unnecessary alarms, you can set codes to distinguish different environments and perform different operations for different environments. The distinction here is based on the BUILD_ENV environment variable (injected in the script command). The following changes need to be made :(the bold part is the new modified code)

  • Package. json script command
"build:test": "cross-env BUILD_ENV=test vue-cli-service build",
"build:prod": "cross-env BUILD_ENV=production vue-cli-service build",
Copy the code
  • Entry file generated instance
import Vue from 'vue' import * as Sentry from '@sentry/browser' import * as Integrations from '@sentry/integrations' const isProd = process.env.BUILD_ENV === 'production' isProd && Sentry.init({ dsn: [new integrations.vue ({Vue, attachProps: true})],})Copy the code
  • Webpack configuration file
Const SentryCliPlugin = require('@sentry/webpack-plugin') const version = '' const isProd = process.env.build_env  === 'production' config.when(isProd, config => { config.devtool('source-map') config.plugin('SentryCliPlugin').use(SentryCliPlugin, [ { release: Include: './dist', include: './dist', include: './dist' "~ / static/js/", ignore: [' node_modules], setCommits: {/ / = = = = = = = = = = = = = = = = = = = = need to corresponding project git address = = = = = = = = = = = = = repo: 'https://xxx.xx.xx', / / = = = = = = = = = = = = = = = = = = = = need to corresponding project git address = = = = = = = = = = = = = auto: true,}},])})Copy the code
  • Finally, you can optionally modify the Sentry exception reporting method
import * as Sentry from '@sentry/browser' const isProd = process.env.BUILD_ENV === 'production' function ResetCaptureout(Sentry: any) { if (isProd) return Sentry Sentry.captureException = function() { const args = Array. The prototype. Slice. The call (the arguments). The join (") return the console. The log (' % csentry: ', 'color: red; ', args) } Sentry.captureMessage = function() { const args = Array.prototype.slice.call(arguments).join(' ') return The console. The log (' % csentry: ', 'color: green; ', args) } return Sentry } Sentry = ResetCaptureout(Sentry)Copy the code

6. After the deployment is complete, you can verify the deployment on the Sentry server

  • To check whether to build the corresponding version: Project -> Version

  • To check whether the SourceMap file was uploaded successfully, go to a version -> Artifacts

7. If you see the version and the corresponding artifacts uploaded successfully, it means that the access has been completed. At this time, if an error occurs again, we can see the specific source information.

extension

  • WebHook associated

Sentry offers a number of plug-in integrations. In addition to email notifications, Sentry can also be plugged into other enterprise office software such as Linkedin or Linkedin for efficient and quick notifications.

  • Path: Project -> Settings -> Legacy Integrations -> Webhook -> Turn on -> Configure Plugin

  • GitLab warehouse integration

By integrating the Gitlab repository, we can associate release deployments, commit records, Sentry issues, etc.

  • Path: Sentry -> Settings -> Integration -> GitLab -> Add

  • Clicking Add Another will bring up detailed instructions
  • After the installation is complete, you can select the corresponding warehouse under the Group to add
  • Issue related

When a new error occurs on a Sentry, you can choose to associate the error message with the repository as an issue, which is relatively simple and won’t go into detail. The effect is shown below

The alarm set

The Sentry itself provides composite items, which can be set according to the actual situation such as the specific service and error information. There are three common ways: alarm rule setting, error inbound filters, and Issue Owners designation. These three methods are described briefly as follows.

The alarm rules

  • Set the path

Sentry -> Project -> Settings -> Alerts -> Edit/Add

  • Optional description

  • An event is seen: When An event occurs

  • An issue is the first seen

  • An issue changes state from resolved to unresolved: An issue changes state from resolved to unresolved

  • An issue changes state from Ignored to unresolved: An issue changes state from ignored to unresolved: An issue changes state from ignored to unresolved: An issue is reminded when An issue that is “ignored” to be resolved under the XX condition is retriggered

  • An issue is seen more than xx times in xx time: For some known low levels, you can set the number of times before the alarm is generated for problems that do not affect usage

  • An event’s tags match XX equal to/does not equal XXX: The decision is made according to the event tag value

  • An event’s level is equal/ Does not equal XXX: Select the event level (fatal/error/warning/log)

  • Trigger action

When the event that is generated meets the alarm rules, the notification action is triggered. You can choose Email or other integration. Since the company uses flying book as daily office IM, it is set here to trigger flying book WebHook. The effect is as follows:

Inbound filter

The inbound filter can be used to filter for certain versions, users with certain IP addresses, or for problems caused by specific browser versions. Most importantly, we can customize filter rules through inbound filters for known negligible issues, such as non-code robustness issues such as request timeouts, no permissions, invalidation of logins, etc.

  • Set the path

Sentry -> Project -> Settings -> Inbound filters

  • View filtering errors

Issue Owners

Through the Issue Owners option, we can automatically establish the association between the Issue and the responsible person when the Issue occurs, and at the same time directly send email or fly book to notify the corresponding responsible partner. There are two Settings, both based on regular expressions.

  • Path: Specifies the owners directory where the source file resides

  • Page routing (URL) : Specifies the specific page routing and owners

Error solution

  • Resolve
    • Current version resolution: After the version is released, modify the issue status
    • Next version resolved: The issue is resolved as soon as it is discovered, and the code goes online with the next version
    • Other versions: This option is not used
  • Ignore
    • Time dimension: ignored before xx time (customizable time)
    • Quantity dimension: ignored until xx times
    • User dimension: ignore this error until xx more users reproduce it

The principle of

Front-end error type

  • Instant run error: Code error
  • Resource loading error
  • Image loading error

Method for reporting errors

  • Reporting using network requests
  • Use pictures to report

Implementation principle of Sentry

  • Init initializes, configures information like release and project DSN, and then mounts the Sentry object to the global object.
  • Override the window.onError method.

When an Error occurs at runtime, JS throws an Error object, which can be obtained through the window.onError method. Sentry uses TraceKit to rewrite the window. onError method and encapsulate the differences of different browsers.

  • Rewrite window. Onunhandledrejection method.

Because the window. The onerror event without access to promise an unhandled exception, at this moment need to use Windows. Onunhandledrejection method to catch exceptions to report. The method handles the error in different ways depending on the type of object received.

  1. If you receive an ErrorEvent object, you simply pull out its error attribute, which is the corresponding Error object.
  2. If you receive a DOMError or DOMException, you can simply parse the name and message, since these errors are usually caused by using the deprecated DOMAPI and do not carry an error stack.
  3. If a standard error object is received, no action is taken
  4. If you receive a normal JavaScript object
  5. Upload with Ajax

When an exception occurs at the current end, the Fetch request will eventually be called and reported to the corresponding Sentry server, using the DSN passed in when the Sentry is initialized.

Record on pit

  • urlPrefix

When uploading the sourceMap file, the path to the static resource file after the package and the final upload may differ from project to project. Therefore, you need to configure the urlPrefix option. This option refers to the full path of the corresponding resource file in the production environment after the project goes live. In the command, ~ indicates the root directory of the website. The following is an example:

Site domain name: www.demo.com

Static resource paths:

www.demo.com/assets/js/1…

www.demo.com/assets/js/1…

So here: ~ = www.demo.com

The urlPrefix option should be configured as: ~/assets/js/

P.S. Defaults to ~/static/js/

Take the picture above for example:

The path of the Sentry resource is domain name /js/chunk-xxxx.js

  • The sourceMap type must be source-map. Otherwise, the error cannot be restored.
  • The DSN is configured as the HTTPS header, so cross-domain issues need to be handled.
  • Sentry errors can be viewed through the console Network option.
  • Running to the Sentry community, or raking past issues, will solve 80% of the problems.

conclusion

Front-end project business scenarios are increasingly complex, and some weird bugs often appear, and testing is difficult to cover 100% of the scenarios. Some small code problems can have unintended consequences. Rather than waiting for users to take the blame when they find a problem, it’s better to use a monitoring system to detect it early and stop it before it causes real damage.

reference

www.feishu.cn/hc/zh-CN/ar… Zhuanlan.zhihu.com/p/75385179 juejin. Cn/post / 684490… zhuanlan.zhihu.com/p/75577689 zhuanlan.zhihu.com/p/89539449

Article | Evan

Focus on object technology, hand in hand to the cloud of technology