background

When the system we developed comes online, we need to monitor its health. Because testing can’t cover all possible exceptions, users may not operate our system exactly the way they want, and unexpected upstream data returns may trigger some exceptions.

For back-end applications, logs are used to discover and locate problems (for example, logs whose level is ERROR and response status code is abnormal).

For the front-end code, because it runs on the client side, if some JS runtime exception occurs, the error may be ignored forever if there is no reported action and user feedback. If the error has been serious enough to affect the use of most users, there may be user feedback, and then there will be repeated communication confirmation, and the recurrence process is complicated.

For exceptions in system operation, we always want to find them as soon as possible, locate and resolve them quickly, so that exceptions can affect fewer users. Sentry is an open source error reporting and application performance monitoring platform for applications developed in major languages. I’ve heard about Sentry for a long time and tried it on a few applications in the second half of the 20th year. In this article, we will introduce the basic concepts of Sentry, the process of installing it in front and back applications (Vue/Django), and its basic use for error reporting, management, and application performance monitoring.

Sentry offers both SaaS services and on-premise deployment, with no major difference in functionality (SaaS services require payment when used in large quantities). For enterprise applications, if you don’t want the code to leak, it is usually deployed locally.

Sentry access

Main steps for Vue application access

  1. To create a project, select Browser Tab and select Vue application.

2. Here’s a simple access guide.

  • The following three packages are required to implement error and performance data reporting. If you do not want to enable performance monitoring, you can install the two packages directly.
    • @sentry/browser (Sentry’s core browser SDK)
    • @sentry/integrations (contains Sentry’s Vue integration)
    • @sentry/tracing (instruments performance data)
  • The Sentry is initialized in main.js following the NPM package
    // main.js
    // Configuration is enabled only in a formal environment
    if (process.env.VUE_APP_ENV === 'production') {
        Sentry.init({
            // data source name
            dsn: 'xxxxx'.integrations: [
                new VueIntegration({
                    Vue,
                    // Enable performance monitoring
                    tracing: true
                }),
                new Integrations.BrowserTracing()
            ],
            // Set the sampling rate for performance monitoring
            tracesSampleRate: 0.2.// We use vUE environment variables to distinguish between two sets of environment
            environment: process.env.VUE_APP_REGION_ENV,
            // The version of the application, which will be carried when the error is reported, can distinguish the reported data from which version of the code
            release: `${process.env.VUE_APP_VERSION}-${process.env.VUE_APP_REGION_ENV}`
        })
    
        Vue.prototype.$sentry = Sentry
    }
    Copy the code
  • We want to include the user information in the reported data (you can check the user’s operation behavior and contact the user when there is an exception), and set the user information in Vuex actions
    // src/store/modules/user.js
        // Set the context in sentry
        setSentryInfo({ commit, state }) {
            return new Promise((resolve, reject) = > {
                this._vm.$sentry.configureScope(scope= > {
                    scope.setUser({
                        username: state.name
                    })
                })
                resolve()
            })
        },
        // Get user information
        getUserInfo(. omit) {
            return new Promise((resolve, reject) = >{ getUserInfo(... Omitted). Then (response= >{...// The current vue instance sentry property sets the user information
                    if (this._vm.$sentry) {
                        dispatch('setSentryInfo')}... resolve(data) }).catch(error= > {
                    reject(error)
                })
            })
        },
    Copy the code
  1. Upload sourcemap. Because of the current front-end engineering applications will generally obfuscate the source code compression. Without Sourcemap, the errors reported are obscure and difficult to locate in the source code.
    // vue.config.js configures the webpack chain operation
    config
        .when(process.env.VUE_APP_ENV === 'production'.config= > {
                config
                    .plugin('@sentry/webpack-plugin')
                    .use(SentryWebpackPlugin, [{
                        authToken: 'xxxx'.org: 'xxx'.project: 'xx'.url: 'xxxx'.// webpack specific configuration
                        include: './dist'.// Upload the version of sourcemap to match the sentry initialization in vue
                        release: `${process.env.npm_package_version}-${process.env.VUE_APP_REGION_ENV}`
                    }])
                    .end()
            }
        )
    Copy the code

It is enough to implement basic error reporting and application performance monitoring. There are other, richer Settings that you can view in the documentation. Vue access document

The main steps for accessing Django applications

Create a project like above, and select your Django application.

  1. Install the Sentry_sdk PIP package and initialize it in setting.py
import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration
sentry_sdk.init(
    dsn=os.environ.get('SENTRY_DSN'),
    integrations=[DjangoIntegration()],
    traces_sample_rate=1.0.# If you wish to associate users to errors (assuming you are using
    # django.contrib.auth) you may enable sending PII data.
    If Django uses authentication, you can enable it. If Django does not use authentication, you need to configure the default Personal Identification Info
    send_default_pii=True
)
Copy the code
  1. Configure the user information for reporting data. If you implement the authentication logic by yourself, add the following codes to the authentication logic code.
from sentry_sdk import set_user
set_user({'username': username})
Copy the code

In addition to adding identifying user information to the reported data, you can Enrich it by looking at Django Enrich Events

Sentry use

Basic terminology

  • Event: Every time an exception is triggered by an application, an Event is reported to the Sentry
  • Issue: Sentry groups reported exceptions using a fingerprint algorithm. The same exception events are grouped under one Issue.

After understanding these two basic concepts, I will introduce the Issue and Performance of Sentry.

Sentry Issue

List of issues and details

The following is an example of data reported by a previous application.

  • Issue list

In the exception list, we can see thatException type, exception name, trigger position, first trigger time, last trigger time, trend of the last 24/14d trigger icon of this type of exception, total trigger here, total number of people triggered, and the person assigned to follow the Issue.

  • Issue the details

On the Issue details page, we can view the specific information of the event triggered by the Issue recently, such asThe context, user, and location of the error. At the same time, if the issue is triggered multiple times, you can click in the upper right corner to switch the event data reported multiple times under the issue.Below the details, we can also see the time of the event Breadcrumbs.Breadcrumbs are some event clues before the exception is triggered. We can refer to this data to simulate some operation behaviors before the operation is triggered, so that problems can be more quickly reappeared and located.(For back-end applications, it is some code logic before the exception is triggered, such as requesting external interfaces, querying databases, etc.)We can also manage an Issue, such as assigning a follower, identifying the version to be solved, and ignoring it. At the same time, some dynamics of the Issue can also be seen under the Activity Tab of the Issue.

Call the police

When an exception is triggered, you want to receive an alarm about the exception as soon as possible. At this point we can set Alert. For example, set email or IM alarm (Github has DingDing plug-in), if it is the enterprise internal IM can also be developed to respond to the plug-in.

Sentry Performance

In addition to error reporting, Sentry can also be used for application performance monitoring.

Take the backend application as an example.

In the Performance list, we can see the loading time of different interfaces, such as TPM, line 50 and line 95, which can be sorted according to the response time, so as to evaluate the Performance of different interfaces and optimize the interface with slow response.

In the event data reported by performance monitoring, you can view the call stack of the code in the interface and find the call duration of each step.

Other common advanced usage methods

  1. Proactively catch and report errors

Sometimes we need to actively trigger error reporting, such as certain operations, deprecated interfaces being called, and capturing online runtime data to troubleshoot problems. You can use captureException or captureMessage provided by Sentry to report errors or text messages.

  1. Enrich the context for reporting data

In addition to the user information mentioned in our intervention, there are also tags, level, fingerprint, and extra data.

For example, to add tags, you can use scope.setTags to define different key/value pairs for events. When we look in the background, there are additional options for the filter criteria, which are set by setTags.

conclusion

Sentry is an open source error reporting and application monitoring solution. Applications developed in various mainstream languages can be accessed. After exceptions are reported, they will be filtered, classified according to certain algorithms, and rich environment and context information will be integrated to facilitate the recurrence and restoration of exceptions.

It is not a replacement for traditional logging and monitoring systems. It focuses on the exception information of the application, which allows us to find, locate and resolve problems faster and resolve exceptions sooner, thus affecting fewer users. At the same time, performance monitoring data can also provide direction for our application optimization.