Sentry - Documentation

What is Sentry?

Sentry is an application monitoring and error tracking platform. It helps developers identify, understand, and fix crashes in real time. It goes beyond basic error logging by providing detailed context around errors, including user information, browser details, and even the complete stack trace. This rich context drastically reduces the time it takes to diagnose and resolve issues, leading to improved application stability and a better user experience. Sentry supports a wide range of languages and frameworks, making it a versatile solution for diverse development environments. It allows for proactive monitoring, allowing developers to anticipate and address potential problems before they impact users.

Key Features and Benefits

Why Use Sentry for JavaScript?

JavaScript applications, especially those running in browsers or within Node.js environments, can be notoriously difficult to debug. Sentry provides several key advantages for JavaScript developers:

Setting up your first Sentry project

  1. Create a Sentry Account: Sign up for a free Sentry account at https://sentry.io/.

  2. Create a New Project: Once logged in, create a new project. Select the appropriate platform (e.g., “JavaScript” if you are working on a web application). You’ll be given a DSN (Data Source Name). Keep this DSN safe; it’s crucial for connecting your application to Sentry.

  3. Install the Sentry SDK: Choose the appropriate SDK for your JavaScript framework (e.g., @sentry/browser for web applications, @sentry/node for Node.js). Install it via npm or yarn:

    npm install @sentry/browser --save
    # or
    yarn add @sentry/browser
  4. Initialize the SDK: In your JavaScript code, initialize the Sentry SDK with your DSN:

    import * as Sentry from '@sentry/browser';
    
    Sentry.init({
      dsn: "YOUR_DSN_HERE", // Replace with your actual DSN
      integrations: [new Integrations.BrowserTracing()], // For tracing
    });
  5. Test it out: Introduce a deliberate error in your code (e.g., accessing a non-existent property). Refresh your application. You should see the error appear in your Sentry project dashboard.

  6. Configure Options (Optional): Explore the numerous configuration options available in the Sentry SDK documentation to customize your error reporting (e.g., environment, release version, sample rate).

Remember to replace "YOUR_DSN_HERE" with your actual DSN from your Sentry project settings. Consult the official Sentry documentation for the most up-to-date instructions and advanced configuration options.

Installation and Setup

This section details how to install and configure the Sentry JavaScript SDKs for both browser and Node.js environments.

Installing the Sentry JavaScript SDK

Sentry offers distinct SDKs for different JavaScript environments. The core SDK, @sentry/core, provides fundamental functionality, while specialized SDKs like @sentry/browser and @sentry/node offer platform-specific integrations and features.

Choose the appropriate SDK based on your application’s environment:

You can install the SDK using either npm or yarn.

Initializing the SDK

After installing the chosen SDK, you must initialize it with your DSN (Data Source Name) and any desired configuration options. This typically involves a single call to the Sentry.init() function.

Basic Initialization (Browser):

import * as Sentry from '@sentry/browser';

Sentry.init({
  dsn: 'YOUR_DSN_HERE', // Replace with your actual DSN
});

Initialization with Integrations (Browser - Recommended):

Adding integrations enhances Sentry’s capabilities. The Integrations object provides pre-built integrations for features like tracing and debugging performance issues.

import * as Sentry from '@sentry/browser';
import { Integrations } from '@sentry/tracing';

Sentry.init({
  dsn: 'YOUR_DSN_HERE',
  integrations: [new Integrations.BrowserTracing()], // Enables automatic performance tracing
});

Basic Initialization (Node.js):

import * as Sentry from '@sentry/node';

Sentry.init({
  dsn: 'YOUR_DSN_HERE',
});

Remember to replace 'YOUR_DSN_HERE' with your actual DSN obtained from your Sentry project settings.

Configuring the SDK

The Sentry.init() function accepts a configuration object with numerous options to tailor Sentry’s behavior. Key configuration options include:

Refer to the official Sentry documentation for a complete list of configuration options and their details.

Different Integration Methods (npm, yarn, CDN)

npm:

npm install @sentry/browser --save

yarn:

yarn add @sentry/browser

CDN (less recommended for production): While possible to include the Sentry SDK via a CDN link, it’s generally less recommended for production deployments due to potential caching issues and the lack of fine-grained control offered by npm/yarn. Check the Sentry documentation for the current CDN links if you choose this method. This method will usually involve adding a <script> tag to your HTML.

Browser vs Node.js Setup Differences

The core functionality of the Sentry SDK remains consistent between browser and Node.js environments; however, some key differences exist:

Remember to always consult the official Sentry documentation for the most up-to-date and detailed instructions on installation, configuration, and usage for each SDK.

Basic Usage and Error Reporting

This section covers the fundamental aspects of using the Sentry SDK to report errors and other relevant information.

Reporting Errors Automatically

The Sentry JavaScript SDKs automatically capture many common JavaScript errors. For browser-based applications using @sentry/browser, this includes uncaught exceptions and errors within Promise rejections. For Node.js applications, errors that bubble up to the top-level event loop are automatically captured. However, for robust error tracking, explicitly reporting errors (as shown in the next section) is recommended. Automatic capture provides a safety net, but manual reporting offers more control and context.

Manually Reporting Errors and Messages

While the SDK automatically captures many errors, explicitly reporting errors using Sentry.captureException() and Sentry.captureMessage() offers greater control and allows you to add crucial context.

try {
  // Code that might throw an error
  const result = 1 / 0; // Division by zero
} catch (error) {
  Sentry.captureException(error);
}
Sentry.captureMessage('An unexpected issue occurred.');

Setting Extra Context (User, Tags, Breadcrumbs)

Enriching error reports with context significantly speeds up debugging. The Sentry SDK allows you to add user information, tags, and breadcrumbs to provide valuable insights into the state of your application before an error occurred.

Sentry.setUser({ id: 'user123', email: 'user@example.com' }); // Avoid sensitive data like PII in production
Sentry.setTag('environment', 'production');
Sentry.setTags({'feature': 'login', 'version': '2.0'});
Sentry.addBreadcrumb({
  category: 'ui',
  message: 'User clicked login button',
  data: { buttonId: 'loginBtn' }
});

Handling Uncaught Exceptions

While the SDK attempts to capture uncaught exceptions automatically, explicitly handling them provides a more graceful user experience and potentially allows for cleanup before the application crashes. The window.onerror (browser) or process.on('uncaughtException') (Node.js) events can be used.

Browser (using window.onerror):

window.onerror = function (message, source, lineno, colno, error) {
  Sentry.captureException(error || new Error(message));
  return true; // Prevents the default browser error handling.
};

Node.js (using process.on('uncaughtException')):

process.on('uncaughtException', (error) => {
  Sentry.captureException(error);
  // Consider adding graceful shutdown logic here
  process.exit(1); // Exit the process to prevent further issues
});

Reporting Performance Issues

Use Sentry’s tracing capabilities to monitor the performance of your application. This involves instrumenting your code to track the duration and status of transactions (individual operations or units of work).

(Note: This requires setting up the @sentry/tracing integration, as shown in the earlier setup sections).

Example: Integrating Sentry into a React app

import React from 'react';
import * as Sentry from '@sentry/react';
import { Integrations } from '@sentry/tracing';

Sentry.init({
  dsn: 'YOUR_DSN_HERE',
  integrations: [
    new Integrations.BrowserTracing(),
    new Sentry.Integrations.React(),
  ],
  tracesSampleRate: 1.0, // Capture 100% of transactions
});

function MyComponent() {
  const handleClick = () => {
    try {
      // Some potentially error-prone code
      const result = 1/0;
    } catch (error) {
      Sentry.captureException(error);
    }
  };

  return (
    <div>
      <button onClick={handleClick}>Click me</button>
    </div>
  );
}

export default MyComponent;

Remember to install the necessary packages: npm install @sentry/react @sentry/tracing. Replace 'YOUR_DSN_HERE' with your actual DSN. This example demonstrates basic error handling within a React component, along with enabling tracing. More advanced React usage may involve integrating with React’s error boundaries for more comprehensive error handling within your React component structure.

Advanced Configuration

This section delves into more advanced configuration options within the Sentry SDK, allowing for fine-grained control over error reporting and data collection.

Customizing Error Handling

Beyond the basic Sentry.captureException() and Sentry.captureMessage() methods, Sentry offers several ways to customize error handling:

Sentry.init({
  dsn: 'YOUR_DSN_HERE',
  beforeSend(event) {
    // Check if the event is from a specific source
    if (event.exception && event.exception.values[0].type === 'MyCustomError') {
      // Add extra context
      event.extra = { extraData: 'Additional info' };
    } else if (event.exception && event.exception.values[0].type === 'IgnoreThisError') {
      return null; // Don't send this event to Sentry
    }
    return event;
  },
});

Breadcrumbs provide a trail of events preceding an error, offering valuable context for debugging. Advanced usage includes:

Sentry.addBreadcrumb({
  category: 'api',
  message: 'API call made',
  type: 'http',
  data: { url: '/api/users', method: 'GET', status: 200 },
  level: Sentry.Severity.Log //Set severity level (info, warning, error, etc.)
});

Sampling and Rate Limiting

For high-volume applications, sampling and rate limiting are crucial for managing the amount of data sent to Sentry.

Integration with other tools and services

Sentry integrates with numerous third-party tools to streamline your workflow. Examples include:

Session Tracking

Sentry can track user sessions, providing insights into session duration, crashes per session, and user engagement. This allows you to identify problematic patterns related to user activity and application stability. Enabling session tracking usually involves using specific SDK integrations or configuration options.

Transactions

Transactions represent units of work within your application. They are crucial for performance monitoring, especially in applications with complex interactions. Properly instrumenting your application with transactions provides a view into the performance bottlenecks. This often involves using the @sentry/tracing integration to track the duration of specific functions or API calls, giving you a clear picture of where your application spends most of its time. You can define start and end points, which will help you visualize your application flow better.

Remember to always refer to the official Sentry documentation for the most comprehensive and up-to-date information on advanced configuration options and best practices. The specifics of certain integrations and features may vary depending on the SDK version and your chosen platform (browser vs. Node.js).

Integrations

Sentry provides official and community-supported integrations for various JavaScript frameworks and libraries, streamlining error reporting and context collection.

React Integration

The @sentry/react package provides seamless integration with React applications. It leverages React’s error boundaries to catch and report errors within components. Key features include:

Installation:

npm install @sentry/react @sentry/tracing --save

Initialization:

import * as Sentry from '@sentry/react';
import { Integrations } from '@sentry/tracing';

Sentry.init({
  dsn: 'YOUR_DSN_HERE',
  integrations: [
    new Integrations.BrowserTracing(),
    new Sentry.Integrations.React(),
  ],
});

Angular Integration

While there isn’t a dedicated @sentry/angular package, integrating Sentry into Angular applications is straightforward using the @sentry/browser SDK. You can leverage Angular’s error handling mechanisms and Zone.js to capture errors. Consider using Angular’s error handling capabilities in conjunction with Sentry to handle errors gracefully.

Installation:

npm install @sentry/browser --save

Initialization: (within your Angular application’s initialization process, perhaps in app.module.ts or a similar entry point)

import { Injectable } from '@angular/core';
import * as Sentry from '@sentry/angular';
import { Integrations } from '@sentry/tracing';


@Injectable({
  providedIn: 'root'
})
export class SentryService {
  constructor() {
    Sentry.init({
      dsn: 'YOUR_DSN_HERE',
      integrations: [new Integrations.BrowserTracing()],
      tracesSampleRate: 1.0,
    });
  }
}

Then, ensure that the SentryService is imported and included in the relevant Angular module.

Vue.js Integration

Similar to Angular, the @sentry/browser SDK works well with Vue.js. You can manually capture exceptions using Sentry.captureException() or integrate with Vue’s error handling mechanisms. Consider using Vue’s error handling in conjunction with Sentry’s error handling to provide a robust error-reporting system.

Installation:

npm install @sentry/browser --save

Initialization: (within your Vue application’s main.js or a similar entry point)

import Vue from 'vue';
import * as Sentry from '@sentry/browser';
import { Integrations } from '@sentry/tracing';

Sentry.init({
  dsn: 'YOUR_DSN_HERE',
  integrations: [new Integrations.BrowserTracing()],
});

Vue.config.errorHandler = (error, instance, info) => {
  Sentry.captureException(error);
};

new Vue({
  // ... your Vue app configuration
});

Node.js Integration

The @sentry/node package specifically targets Node.js applications. It integrates with the Node.js event loop to capture uncaught exceptions and provides support for features specific to server-side environments, like request context.

Installation:

npm install @sentry/node --save

Initialization:

import * as Sentry from '@sentry/node';

Sentry.init({
  dsn: 'YOUR_DSN_HERE',
});

You may need to handle uncaught exceptions explicitly using process.on('uncaughtException') to ensure they’re properly reported to Sentry.

Other Framework and Library Integrations

Sentry maintains a list of supported integrations on their website. This list is frequently updated, so check their official documentation for the most current information. Many popular JavaScript frameworks and libraries may have community-supported integrations or examples readily available.

Custom Integrations

For frameworks or libraries not officially supported, you can create custom integrations. This generally involves creating a class that implements the required Sentry integration interface, handling specific aspects of error capturing and context enrichment relevant to the target framework or library. Refer to Sentry’s documentation for the details of creating custom integrations. This typically involves extending the base integration class and providing relevant methods to capture context and handle specific framework-related events.

Remember that the specific initialization and configuration details may vary slightly depending on the framework and SDK version. Consult the official Sentry documentation for the most accurate and updated instructions for each integration.

Monitoring and Troubleshooting

This section guides you through effectively using Sentry’s dashboard and tools to monitor your application’s health and troubleshoot issues.

Understanding Sentry’s Dashboard

The Sentry dashboard provides a centralized view of your application’s errors and performance. Key areas include:

Familiarize yourself with the dashboard’s navigation and filtering options to effectively monitor your applications.

Filtering and Searching Issues

The Sentry dashboard provides robust filtering and search capabilities to isolate specific issues:

Effective filtering and searching are crucial for prioritizing and managing issues.

Analyzing Error Reports

Analyzing error reports involves understanding the details provided in individual events:

Thoroughly examine these details to understand the cause and impact of each error.

Using Debug Tools

Sentry offers several tools to aid in debugging:

Properly using these tools streamlines the debugging process.

Troubleshooting Common Issues

Common Sentry integration issues:

If you encounter issues not covered here, consult Sentry’s documentation and community forums for additional assistance. The Sentry support channels offer valuable resources for solving more complex problems.

Performance Monitoring

Sentry’s performance monitoring capabilities extend beyond basic error tracking, allowing you to proactively identify and address performance bottlenecks in your applications.

Setting up Performance Monitoring

Enabling performance monitoring typically involves:

  1. Installing the necessary packages: Ensure you have the appropriate Sentry SDK installed (e.g., @sentry/browser or @sentry/node). Crucially, you’ll likely need the @sentry/tracing package for transaction tracing.

  2. Initializing the SDK with tracing integration: When initializing the Sentry SDK, include the Integrations.BrowserTracing() (for browser applications) or equivalent integration for your environment. This enables automatic transaction tracing.

    import * as Sentry from '@sentry/browser';
    import { Integrations } from '@sentry/tracing';
    
    Sentry.init({
      dsn: 'YOUR_DSN_HERE',
      integrations: [new Integrations.BrowserTracing()],
      tracesSampleRate: 1.0, // Adjust sampling rate as needed
    });
  3. (Optional) Manual instrumentation: For more granular control, you can manually instrument specific parts of your application to track custom transactions. This allows you to define transactions that are meaningful to your application’s architecture.

  4. Adjust sampling rate: The tracesSampleRate option controls the percentage of transactions that are sent to Sentry. Lowering this value (e.g., to 0.1 for 10%) reduces the amount of data sent, which is beneficial for high-traffic applications.

Understanding Performance Metrics

Once performance monitoring is enabled, Sentry will collect various metrics, including:

Analyzing these metrics provides insights into the performance characteristics of your application.

Identifying Performance Bottlenecks

By examining the collected performance data, you can pinpoint performance bottlenecks:

Effective bottleneck identification requires careful analysis of the collected metrics and their relationships.

Improving Application Performance

Once you’ve identified performance bottlenecks, you can apply various techniques to optimize your application:

Implementing these optimizations often involves iterative improvements and thorough testing to verify the effectiveness of the changes. Remember to monitor your application’s performance over time using Sentry to track the impact of any optimizations.

Security Considerations

Security is paramount when using Sentry. This section outlines important security practices to protect your data and applications.

Protecting Sensitive Data

Sentry automatically anonymizes much of the data it collects, but you must take additional steps to protect sensitive information:

Authentication and Authorization

Sentry’s access control mechanisms help you manage who can access your project data:

Properly configuring authentication and authorization is critical to restricting access to sensitive data and maintaining the security of your Sentry account.

Data Privacy

Compliance with data privacy regulations (like GDPR, CCPA, etc.) requires careful consideration:

Ensure that your use of Sentry complies with all relevant data privacy regulations and best practices. If you’re unsure about specific requirements, consult legal counsel. Properly configuring your Sentry project and understanding the anonymization and data-handling capabilities is critical for achieving data privacy compliance.

API Reference

This section provides a high-level overview of the Sentry APIs. For complete and up-to-date details, always refer to the official Sentry documentation. The APIs are subject to change, so checking the latest version is crucial.

Client API

The Sentry client SDKs (e.g., @sentry/browser, @sentry/node, @sentry/react) expose a JavaScript API for interacting with the Sentry service. Key functions include:

These are some of the most commonly used functions. The full API documentation provides a complete list of methods and their parameters.

Server API

The Sentry server API allows programmatic interaction with Sentry’s backend. This API is primarily used for integrating Sentry with other systems, automating tasks, or accessing detailed data programmatically. Examples include:

The Sentry server API typically uses RESTful endpoints and often requires authentication using API tokens. Consult the official Sentry API documentation for specific endpoints, authentication methods, and detailed usage instructions. The API documentation details available endpoints, request formats (usually JSON), response formats, and authentication methods. Remember that the server API may require specific authentication and authorization to access certain endpoints and data.

This API reference provides a brief overview. For precise details, including request parameters, response structures, error codes, and rate limits, refer to the comprehensive and constantly updated official Sentry documentation. The documentation usually includes code examples in various programming languages (including Python and Javascript) to demonstrate API usage.

Appendix

This appendix provides supplemental information to aid in your use of Sentry.

Glossary of Terms

FAQ

Troubleshooting Guide

Refer to the “Monitoring and Troubleshooting” section of this manual for detailed guidance. If you encounter problems not addressed there, check the Sentry documentation and community forums for solutions.

Further Resources

This appendix provides a starting point; for comprehensive information, always consult the official Sentry resources.