قالب وردپرس درنا توس
Home / Tips and Tricks / How to use Sentry and GitLab to capture response errors – CloudSavvy IT

How to use Sentry and GitLab to capture response errors – CloudSavvy IT



Image with the GitLab and Sentry logos

Sentry is an error tracking platform that helps you monitor issues in your production deployments. It supports most popular programming languages ​​and frameworks.

GitLab is a Git-based DevOps platform to manage the entire software development lifecycle. GitLab integrates with Sentry to display logged errors. In this article, we̵

7;ll use the two services to stay ahead of issues in a React application.

To work

GitLab and Sentry both have self-hosted and SaaS options. The steps in this guide apply to both variants. We assume you already have a React project ready to use in your GitLab instance.

Log into Sentry and click the “Create Project” button in the top right corner. Click on “Comment” under the heading “Choose a platform”. This allows Sentry to adapt sample code snippets to fit your project.

Choose when you want to receive alerts using the options under ‘Set your default alert settings’. Select “Notify me of every new problem” to receive an email every time an error is registered. The “If there are more than” option filters out noise caused by duplicate events in a given time window.

Give your project a name in the “Project Name” field. Click “Create Project” to complete your installation.

Add Sentry to your codebase

Now you need to integrate Sentry with your React code. Add the Sentry library to your project’s dependencies with npm:

npm install @sentry/react

You should initialize Sentry in your app’s JavaScript as soon as possible. This gives Sentry insight into errors that occur early in the React lifecycle. Add Sentry’s bootstrap script for your first ReactDOM.render() call. This is usually in index.js:

import App from "./App.js";
import React from "react";
import ReactDOM from "react-dom";
import * as Sentry from "@sentry/react";
 
Sentry.init({
    dsn: "my-dsn"
});
 
ReactDOM.render(<App />, document.getElementById("react"));

To replace my-dsn with the DSN that Sentry displays on the screen for creating your project. The DSN uniquely identifies your project so that the service can correctly attribute events.

Log errors

Sentry will automatically log and report unhandled JavaScript errors. Although it is not possible appearance the crash lets you know that something went wrong before the user report arrives.

Here is an example App.js:

import React from "react";
 
export default () => {
    const data = null;
    return data.map((val, key) => {
        <h1 key={key}>{val}h1>;
    });
};

This code is broken—data set to null, so the map will be owned undefined. We’re trying to call data.map() regardless so that the app crashes. You should see a problem appear in Sentry.

Sentry issues contain as much data about the error as possible. You can see the page URL as well as information about the user’s device. Sentry automatically combines duplicate issues. This helps you see if an event was a one-off or a regular occurrence affecting multiple users.

Sentry automatically retrieves JavaScript resource maps when they are available. If you use create-react-app, source maps are automatically generated by npm run build. Make sure to copy them to your web server so Sentry can find them. You’ll see nice stack traces from the original source code instead of the obfuscated stack produced by the minified build output.

You can mark Sentry errors as Resolved or Ignored once they have been dealt with. You can find these buttons under the issue title and on the Issues summary page. Use Solved once you’re sure a problem has been resolved. Ignored is for cases where you do not intend to address the root cause. On React sites, this can be the case for errors caused by old browser versions.

Error Limits

React error limits allow you to display a fallback user interface when an error is thrown in a component. Sentry offers its own error-limiting wrapper. This creates a fallback UI and logs the caught error to Sentry.

import * as Sentry from "sentry";
 
export default () => {
    const data = null;
    return (
        <Sentry.ErrorBoundary fallback={<h1>Something went wrong.h1>}>
            {
                data.map((val, key) => {
                    <h1 key={key}>{val}h1>;
                });
            }
        Sentry.ErrorBoundary>
    );
};

Now you can display a warning to users when an error occurs. You will still receive the bug report in your Sentry project.

Add GitLab Integration

The integration of GitLab and Sentry has two sides. First, GitLab projects have an “Error Tracking” feature that displays your Sentry error list. You can mark errors as Fixed or Ignored from GitLab. The second part involves connecting Sentry to GitLab. This allows Sentry to create automatically GitLab problems when a new error is logged.

First, let’s take a look at GitLab’s Error Tracking screen. You need to create a Sentry API key. Click on your username in the top left corner of your Sentry UI and then on the API keys in the menu. Click “Create New Token” in the top right corner.

Add the following token ranges:

  • alerts:read
  • alerts:write
  • event:admin
  • event:read
  • event:write
  • project:read

This allows GitLab to read and update your Sentry errors.

Next, go to your GitLab project. Click Settings in the side menu and then Operations. Expand the Error Tracking section. Paste your Sentry Authentication Token into the “Auth Token” field and press “Connect”. If you’re using a self-hosted Sentry instance, you’ll also need to change the “Sentry API URI” field to match your server’s URI.

The “Project” drop-down list will be populated with a list of your Sentry projects. Select the correct project and press ‘Save changes’. You are now ready to use Error Tracking in GitLab.

Click Operations > Debug in the left sidebar. You will see your list of Sentry errors. It is filtered by Unresolved Issues by default. This can be changed using the drop-down lists in the top right corner. Click on an error to see the detailed stack trace without leaving GitLab. There are buttons to ignore, resolve, and convert a GitLab issue to a GitLab issue. Once you’ve opened a GitLab issue, you can assign that item to a team member to fix the bug.

Now you can add the second integration component: a link from Sentry back to GitLab. Click Settings in your Sentry sidebar and then Integrations. Find GitLab in the list and click the purple “Add Installation” button in the top right corner. Click “Next” to see the installation information.

Back on GitLab, click on your user icon in the top right corner, followed by ‘Preferences’. Click “Applications” in the menu on the left and add a new application. Use the details shown by Sentry in the installation settings pop-up.

GitLab displays an application ID and secret key. Return to the Sentry popup and enter these values. Add your GitLab server URL (gitlab.com for GitLab SaaS) and enter the relative URL path to your GitLab group (e.g. my-group). The integration does not work with personal projects.

Click the purple Submit button to create the integration. Sentry can now display GitLab information next to your errors. This includes the commit that introduced the error, and stack traces linking back to GitLab files. Sentry users with paid subscriptions can link GitLab and Sentry issues together.

Disable Sentry in development

You don’t necessarily want to use Sentry when running your app locally in development. Do not call Sentry.init() if you want to work with Sentry disabled. You can check for the presence of a local environment variable and disable Sentry if it is set.

if (process.env.NODE_ENV === "production") {
    Sentry.init({
        dsn: "my-dsn"
    });
}

NODE_ENV is set automatically by create-react-app. Production builds hardcode the variable to production. You can use this to selectively enable Sentry.

Enable Performance Profiling

Sentry can also profile your app’s browser performance. While not the main focus of this article, you can set up tracing with a few extra lines in your Sentry library initialization:

npm install @sentry/tracing
import {Integrations} from "@sentry/tracing";
 
Sentry.init({
    dsn: "my-dsn",
    integrations: [new Integrations.BrowserTracing()],
    tracesSampleRate: 1.0
});

Now you can see performance data in your Sentry project. This can help you identify slow-running code in production.

Conclusion

Sentry helps you find and fix errors before users report them. You can get real-time alerts if problems arise in production. Stack traces and browser data are displayed inline in each issue, giving you an instant starting point for a solution.

The combination of Sentry with GitLab provides an even closer integration with the software development process. If you already use GitLab for project management, adding the Sentry integration allows you to manage alerts within GitLab and create GitLab issues for new Sentry errors.


Source link