Front-end monitoring is a big project, the final form is a precise, complete, automatic background system. This article takes you to understand what a perfect monitoring system can do, and then you can build a monitoring system according to the team and needs in line with their own business scenarios, saving by people.

Why is a front-end monitoring system needed

Everyone should have some experience. As the first person responsible for bugs (just kidding), the front-end students are easily passive when they are suddenly called to check bugs. Flustered, nervous, embarrassed front-end students how to save themselves? Naturally, find a way to prevent this from happening, establish a front-end monitoring system, open the eye of the omniscient, and turn the passive into the active.

How can the front end students fully demonstrate their value to the business-focused projects? Collect user profiles and use retention conversion rates and other data to deliver a one-two punch.

Collect front-end performance data, monitor and optimize key links for a long time. Let the data expose optimization points, let the data support optimization results.

Every time the launch line is terrified, not sure whether it can run normally, worried about platform compatibility problems

The composition of front-end monitoring system

By service module

According to the pain points described above, front-end monitoring system can be roughly classified into four categories:

- the front-end monitoring system | - | - user behavior monitoring error monitoring | - | - performance monitoring test monitoringCopy the code
  1. User Behavior Monitoring

    That is, the collection of user behavior is used to describe user portraits and improve product experience. For example, we can collect the page dwell time, the number of clicks on different buttons, the time from browsing to ordering, the choice of payment method, and so on. These data can be used to calculate the business conversion rate and build funnel model, providing data support for the next function and optimization of the product

  2. Monitoring errors

    Collect system errors caused by various reasons, including front-end code errors, interface format errors, and network errors. Error messages are then repeatedly filtered, error resolution assigned, and gracefully degraded.

  3. Performance monitoring

    That is to collect front-end performance data, such as page loading time, rendering time, CDN main traffic, packaging speed and size. Gradually optimize the most hip-pulling items to improve front-end performance.

  4. Test monitoring

    Generally, unit tests and code style tests are conducted before code submission or release. However, there is also a requirement to monitor E2E (End to End) test results. Automate interface test in Webview of Android, IOS and small programs to ensure that the code can run on various mainstream platforms.

  5. Operation data collection Strictly speaking, operation data collection is beyond the scope of front-end, but some data need front-end collection, such as daily active users and data related to project value, which may overlap with user behavior.

Differentiated by technical implementation

In terms of technical implementation, the realization of a monitoring system can be divided into three parts:

- according to the classification | - collect monitoring data of implementation | | - filtration, monitoring data, alarm and monitoring events subsequent processingCopy the code

The concrete implementation of these three parts is as follows:

How to collect monitoring data

To collect valuable data, we usually report data through code calls to the interface. If your code has a pattern, consider inserting it with a script.

In the front-end project, there are many ways to collect data, mainly centering on reporting at the appropriate time, including but not limited to:

  1. Report during the page life cycle
// onunload
window.onload=function(){
    axios.get('/api/report', {
        params: {
            userId: 'xxxxxxxx'.userAgent: window.navigator.userAgent,
            time: new Date().getTime(),
            reportContent: Visited `The ${window.location.href}Page `}})}// Or in Vue, beforeDestroy, etc
mounted() {
    axios.get('/api/report')}Copy the code
  1. In interactive events
const $dom = document.querySelector('#dom')
// event: input scroll
$dom.addEventListener('click'.function () {
    axios.get('/api/report', {
        params: {
            / /... .
            reportContent: 'Clicked'}})})Copy the code
  1. In the interceptor of the interface request method
axios.interceptors.response.use(function (response) {
    // An error code with the backend convention occurred
    if (response.data.code === 'Some error codes of concern') {
        // Send an error alarm
        axios.get('/api/report', {
            params: {
                userId: 'xxxxxxxx'.userAgent: window.navigator.userAgent,
                time: new Date().getTime(),
                reportContent: ` appeared${response.data.code}Error code `}})}return response;
}, function (error) {
    axios.get('/api/report', {
        params: {
            / /... .
            reportContent: 'Interface error, error message:${error.message}`}})return Promise.reject(error);
});
Copy the code
  1. In the exception catch chain:
try {
    // ...
} catch (error) {
    axios.get('/api/report', {
        params: {
            / /... .
            reportContent: An error occurred in the code block with the error message:${error.message}`}})}window.onerror = function (msg, url, lineNo, columnNo, error) {
    axios.get('/api/report', {
        params: {
            / /... .
            reportContent: 'A global error occurred:${error.message}`}})}window.addEventListener('unhandledrejection'.(error) = > {
    axios.get('/api/report', {
        params: {
            / /... .
            reportContent: 'occurs a promise that is not processed reject:${error.reason}`}})})// Vue
Vue.config.errorHandler = function(error, vm, info) {
  console.log('Vue component error:${error.message}`)}// React
componentDidCatch(error, info) {
  console.log(The React component failed:${error.message}`)}Copy the code
  1. There are also some scenarios of non-client data reporting, such as Jenkins packaging speed, CDN traffic consumption, automated test results before and after deployment, etc., which require the corresponding service to provide hooks to execute script reporting.

How to filter and display monitoring data

For some frequently reported data, we need to filter processing otherwise it will burden the server too much. For example, if an interface error or JS error occurs frequently, you can give different scenarios a code, and delete the necessary data and discard redundant data according to the code and error information.

Monitoring data is usually displayed in the form of a list + ICONS, for example, an online error list displayed in reverse chronological order + an analysis chart corresponding to each error. Through the screening of different dimensions, data visualization is achieved

Menus, tables, and forms for background management can use Element-Plus or ANTD. Visual diagrams can use ANTV or Echarts

In the list, we can also add buttons such as task assignment and quick operation to facilitate rapid response to the monitoring content.

Automatic monitoring

To keep the system running smoothly, we can automate code quality and results checks at certain times. Such as:

  1. Bind git repository hooks to check that the submitted code complies with the ESLint specification
  2. Bind git repository hooks and run unit tests at commit time to see if they all pass
  3. Run e2E tests after the code is deployed, and do different client tests on the released code
  4. Periodically test the interface to verify whether the interface conforms to the data format of the document

Graceful system degradation is supported

When a fatal error occurs in the system, the processing process can be automatically triggered to make an emergency switch to the degraded system. There are several options for degraded systems:

  1. An HTTP cache server such as Varnish temporarily returns an error interface from the cache
  2. Switch to the old version of the code
  3. A special degradation system was written as a backup
  4. Static resource report network error can switch to the standby CDN address

Practice related articles

The above is to introduce the system and implementation ideas of the front-end monitoring system, we can refer to more excellent articles in the specific practice of the company:

  • Come, work with me to develop your own multiterminal error monitoring platform (full version)
  • Front-end monitoring and front-end buried point design
  • An article about the development of the front – end error monitoring

Nine, Git, Shell basic knowledge and work practice