Location>code7788 >text

Front-end Stability Tools - Sentry

Popularity:144 ℃/2024-11-15 16:25:44

What is Sentry?

Sentry is essentially a server-side application that receives error logs from a client (e.g., a web application, a mobile application, or a back-end service) and then aggregates, analyzes, and visualizes these logs. It provides detailed error reporting, including a stack trace, the context in which the error occurred (e.g., user information, device information, environment variables, etc.), and the frequency and trends of errors.

Why use Sentry?

  1. Real-time error tracking: Sentry captures errors in your application in real-time and notifies the development team immediately. This dramatically reduces the time from when a user reports a problem to when the development team discovers and resolves it.
  2. Improving the quality of applications: By continuously monitoring and analyzing error data, development teams can identify and resolve potential problems in a timely manner, thereby improving the quality and stability of applications.
  3. Detailed Error Reporting: Sentry provides very detailed bug reports, including full stack trace and contextual information. This enables developers to quickly pinpoint the root cause of a problem and effectively debug and fix it.
  4. Cross-platform and language support: Sentry supports a wide range of programming languages and platforms, including JavaScript, Python, Java, Ruby, PHP, and more. This means that no matter what technology stack your application is built on, Sentry provides effective bug tracking.
  5. Scalability and Integration: Sentry is powerfully extensible and can be integrated with a variety of third-party services and tools, such as Slack, GitHub, JIRA, and more. This enables development teams to customize workflows to their needs and seamlessly integrate with other team collaboration tools.
  6. Saving time and resources: By automating bug tracking and reporting, Sentry helps development teams save a lot of time manually troubleshooting issues. This not only improves development efficiency, but also reduces maintenance costs.
  7. Increased user satisfaction: Timely identification and resolution of problems in an application can significantly improve user experience and satisfaction. The ability to respond and resolve issues quickly when users encounter them will increase their trust and loyalty to the application.

access method

Sentry project address: the address of the company's privatization deployment

Preparation - Project Access sentry

  1. Login to sentry via domain name

  1. Came in and didn't see TEAM info, joined to group.

  1. After joining, go to Projects and check your projects in the group, if you don't have any, you need to create them.

  1. Creating a project requires permissions, if you don't have permissions, you can check out Members and find someone with permissions to help you create it.

  1. As shown below, follow the documentation directly to add to the project

  1. If it is a small program uni-app project, directly using the vue3 sdk can not be reported, then you can use the third-party plugin sentry-miniapp

1 import * as Sentry from "sentry-miniapp";
2 ({
3   dsn: "https://xxxxxxxxx",
4   // Set tracesSampleRate to 1.0 to capture 100%
5   // of transactions for performance monitoring.
6   // We recommend adjusting this value in production
7   tracesSampleRate: 1.0
8 });

 

In this way, the project completes the access to the sentry, and any errors in the project will be reported automatically, and you can find the reported errors in the lssues of the sentry.
In the background of sentry you can view the reported issue, if you think it does not affect you can click ignore, so that the same error will not be prompted again.
 

Sentry settings for VUE projects

sentryInit pseudo-code

  1 // Call the sentryInit function to initialize the configuration of the Sentry
  2 sentryInit({
  3   // Pass the init method and app instance of the sentry to the sentryInit
  4   sentry: { init },
  5   app,
  6 
  7   // Specify the DSN (Data Source Name) of the Sentry item for sending error data to the correct Sentry item
  8   dsn: 'https://xxxxx',
  9 
 10   // Configure integrations, here two integrations are added: BrowserTracing and Replay
 11   integrations: [
 12     // BrowserTracing integration for tracking performance issues in the browser, such as page load times, etc.
 13     new BrowserTracing({
 14       // Tracing of Vue routes via vueRouterInstrumentation
 15       routingInstrumentation: vueRouterInstrumentation(router),
 16     }),
 17     // Replay integration is used to record and replay user actions, helping developers better understand the context in which errors occur
 18     new Replay({
 19       // Configure the interfaces that are allowed to be collected, if there is a non-homologous interface domain name needs to be configured here
 20       networkDetailAllowUrls: [],
 21       
 22       // Configure the fields to be captured in the request header By default, only Content-Type, Content-Length, Accept, Authorization need to be captured.
 23       networkRequestHeaders: ['traceparent', '__refreshid__', 'Cookie', 'Authorization'],
 24       
 25       // Configure the fields to be captured in the response header
 26       networkResponseHeaders: ['traceparent', 'set-cookie'],
 27       
 28       // Whether to desensitize all text, set to false here.
 29       maskAllText: false,
 30       
 31       // Whether to desensitize all inputs, set to false here
 32       maskAllInputs: false,
 33       
 34       // Whether to block all media loading, set to false here
 35       blockAllMedia: false,
 36     }),
 37   ],
 38 
 39   // Sets the sampling rate of the trace, 1.0 means 100% of the trace events are captured Values between 0 and 1.0, events are randomly selected
 40   tracesSampleRate: 1.0,
 41 
 42   // Setting environment variables to distinguish between different environments (e.g. development, test, production, etc.)
 43   environment: ,
 44 
 45   // Whether or not to turn on error reporting.
 46   enabled: true,
 47 
 48   // Setting the version number can be used to filter and locate errors for a specific version
 49   release: .BUILD_TIME as string,
 50 
 51   // Configure the types of errors or error messages to be ignored that will not be reported to Sentry
 52   ignoreErrors: [
 53     'ResizeObserver loop limit exceeded',
 54     // ... (Other errors to ignore)
 55     // 'ResizeObserver loop completed with undelivered notifications',
 56     // /Failed to fetch dynamically imported module/,
 57     // /Failed to load module script/,
 58     // /Importing a module script failed/,
 59     // /promise rejection captured with keys: code, error, msg/,
 60     // /exception captured with keys: code, data, msg/,
 61     // /Unable to preload CSS for/,
 62     // /exception captured with keys: errorFields, outOfDate, values/,
 63   ],
 64   
 65   initialScope: {
 66     tags: { "my-tag": "my value" },
 67     user: { id: 4222xxx, email: "" },
 68   },
 69 
 70   // Setting the user name
 71   username: ,
 72 
 73   // Whether to log errors to the console, set to true here.
 74   logErrors: true,
 75 })
 76 
 77 
 78 
 79 export function configSentryPlugin() {
 80   return vitePluginSentry({
 81         // Specify the URL of the Sentry service
 82         url: '',
 83     
 84         // Specify the authorization token for Sentry, which is the credential for connecting to the Sentry service and performing bug tracking
 85         authToken: '', //sentry authorization token
 86     
 87         // Specifies the name of the organization in the Sentry
 88         org: 'sentry',
 89     
 90         // Specify the name of the item in the Sentry
 91         project: 'xxxx',
 92     
 93         // Specify the version of the release. The value of the environment variable BUILD_TIME is used here for the version information.
 94         release: .BUILD_TIME as string,
 95     
 96         // Configure source map settings to more accurately locate errors in Sentry
 97         sourceMaps: {
 98           // Specify the files or folders that need to be included in the source map, in this case the folder '. /dist/assets' folder
 99           include: ['./dist/assets'],
100           
101           // Specify the files or folders to ignore, here the 'node_modules' folder is ignored.
102           ignore: ['node_modules'],
103           
104           // Set the URL prefix of the source map to construct the correct source map URL in Sentry
105           urlPrefix: '~/cloudConfigAssets',
106         },
107     
108         // Set up to skip environment checks and upload source maps and error messages to Sentry even in non-production environments.
109         skipEnvironmentCheck: true,
110     })  
111 }
Proactive reporting of errors in the program
Methods.sentryLog (Active upload error.' info')
Usage: You can pre-built in the project, for example, interface catch error in the project, make some identification for yourself, so as to locate the problem.
 

Setting up enterprise bot alerts for projects

  1. Prepare enterprise microsoft bots.

API for enterprise wechat bots to send messages: /document/path/91770
  1. Use sentry's webhook plugin to notify enterprise microsoft.

  1. Click on settings, projects

Find the corresponding project, then click Alert setting, you can add the hooks address in the callback urls of WEBHOOKS.
If there is no WEBHOOKS piece, then you may need an administrator to open it and fill it in. It's at the bottom of the same page.
 

Configuring alert rules for projects

  1. Go to the Alerts page

  1. After entering, select variables such as issues, error level, environment, etc. Then you can set conditions and filter information according to your actual situation.

Setting the sourceMap of a project

Locating the wrong position

The code in the front-end project was obfuscated. Although the error can be captured, but we can not locate the specific location in the console. So sentry can upload sourceMap so that the error can be localized to a specific line.

Ideas for implementation

The local code is packaged (there is sourceMap in the packaged file), and then uploaded to the sentry service via command or plugin, and sentry then matches to the corresponding js and map according to the release version. then you can view the location of the error in sentry.
(The sourceMap is uploaded to sentry, but not to production, so this piece has to be handled in each project.)
  1. Generate uploaded token

This is where project:write and project:releases are usually checked.
This generates the authtoken
  1. Upload method

There are 2 ways to upload sourceMap, one is to upload it manually, and the other is to upload it through a plugin (we recommend using a plugin to save time)
Uploading with the plugin
webpack
You can install '@sentry/webpack-plugin' to upload it.
 1 // 
 2 const SentryCliPlugin = require('@sentry/webpack-plugin')
 3 
 4 ...
 5 
 6 configureWebpack(config) {
 7      if (.NODE_ENV === 'production') {
 8           ('sentry').use(SentryCliPlugin, [{
 9              include: './dist/assets',    // Specify the upload directory
10              ignoreFile: '.gitignore',  // Specifying an Ignore File Configuration
11              release: .VUE_APP_BASE_API,  // Specify the release version
12              ignore: ['node_modules', ''], 
13              configFile: './.sentryclirc',   // Specify the sentry upload configuration
14              urlPrefix: '~/assets/'   // Keep it consistent with the publicpath
15         }])
16     }
17 }

vite

Can install 'vite-plugin-sentry'
 1 import vitePluginSentry from 'vite-plugin-sentry';
 2 
 3 vitePluginSentry({
 4   url: '',
 5   authToken: 'xxx', // sentry authorization token
 6   org: 'sentry',
 7   project: 'xxx',
 8   skipEnvironmentCheck: true,
 9   release: .BUILD_TIME as string,
10   sourceMaps: {
11     include: ['./dist/assets'],
12     ignore: ['node_modules'],
13     urlPrefix: `${.VITE_PUBLIC_PATH}/assets`,
14   },
15 }),
16 
17 build: {
18     target: 'es2015',
19     sourcemap: true,
20 },
This way, it can be automatically packaged and uploaded when using the build command
Empty the sourceMap file with the command
sentry-cli release files xxx delete -all
 
Finally, add a command to delete the sourcemap after the build is complete to avoid having the sourcemap on the production environment.
rm ./dist/**/*.map
 

Reporting method encapsulation

pseudocode

 1 /**
 2  * :: sentry initialization function
 3  *
 4  * @param options - sentry objects
 5  *
 6  * @returns returns the current refresh id
 7  * @public
 8  */
 9 export declare const sentryInit: ({ sentry, app, environment, enabled, release, tracesSampleRate, tags, username, dsn, isMiniapp, integrations, normalizeDepth, beforeSend, ...otherOptions }: SentryOptions) => {
10     __refreshId__: string;
11 };
12 /**
13  * :: Base sentry reporting function
14  *
15  * @param sentry - sentry object
16  * @param error - error message
17  * @param options - additional information
18  *
19  * @returns type and meaning of return value
20  * @public
21  */
22 export declare const sentryLog: (sentry: any, error: Error | string, options: SentryLogOptions) => void;
23 /**
24  *
25  * :: Logging historical api request information
26  *
27  * @param apiLog - api data
28  * @param maxSaveLength - maximum save length
29  *
30  * @returns None
31  * @public
32  */
33 export declare const saveApiLog: (apiLog: ApiLog, maxSaveLength?: number) => void;
34 /**
35  * :: Sentry api interface error reporting function
36  *
37  * @param sentry - sentry object
38  * @param error - error message
39  * @param options - additional information
40  *
41  * @returns None
42  * @public
43  */
44 export declare const sentryApiLog: (sentry: any, error: Error | string, options: SentryApiLogOptions) => void;