Pular para o conteúdo

Sentry Cheat Sheet

Overview

Sentry is an open-source application monitoring platform that provides real-time error tracking, performance monitoring, and session replay capabilities. It captures exceptions, stack traces, and breadcrumbs from your application, enabling fast debugging with full context including user information, device details, and release data.

Sentry supports over 100 platforms and frameworks including JavaScript, Python, Java, Go, Ruby, PHP, .NET, and mobile platforms. It offers both a cloud-hosted SaaS version and a self-hosted option. Features include release tracking, commit integration, alerting, dashboards, and distributed tracing for microservices.

Installation

# JavaScript / Node.js
npm install @sentry/node

# React
npm install @sentry/react

# Python
pip install sentry-sdk

# Go
go get github.com/getsentry/sentry-go

# Ruby
gem install sentry-ruby

# PHP
composer require sentry/sentry

# .NET
dotnet add package Sentry

# Sentry CLI (for releases, sourcemaps)
npm install -g @sentry/cli
curl -sL https://sentry.io/get-cli/ | bash

Core Configuration

Node.js / Express

const Sentry = require("@sentry/node");

Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
  environment: process.env.NODE_ENV,
  release: "my-app@1.2.0",
  tracesSampleRate: 0.2,
  profilesSampleRate: 0.1,
  integrations: [
    Sentry.httpIntegration(),
    Sentry.expressIntegration(),
  ],
});

const app = express();
Sentry.setupExpressErrorHandler(app);

Python / Django

import sentry_sdk

sentry_sdk.init(
    dsn="https://examplePublicKey@o0.ingest.sentry.io/0",
    environment="production",
    release="my-app@1.2.0",
    traces_sample_rate=0.2,
    profiles_sample_rate=0.1,
    send_default_pii=True,
)

React

import * as Sentry from "@sentry/react";

Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
  integrations: [
    Sentry.browserTracingIntegration(),
    Sentry.replayIntegration(),
  ],
  tracesSampleRate: 0.2,
  replaysSessionSampleRate: 0.1,
  replaysOnErrorSampleRate: 1.0,
});

Manual Error Capture

// Capture an exception
try {
  riskyOperation();
} catch (error) {
  Sentry.captureException(error);
}

// Capture a message
Sentry.captureMessage("Something unexpected happened", "warning");

// Capture with extra context
Sentry.captureException(error, {
  tags: { section: "payments" },
  extra: { orderId: "12345", amount: 99.99 },
  level: "error",
});
# Python error capture
import sentry_sdk

try:
    risky_operation()
except Exception as e:
    sentry_sdk.capture_exception(e)

sentry_sdk.capture_message("Unexpected state detected", level="warning")

Context and Breadcrumbs

// Set user context
Sentry.setUser({
  id: "user-123",
  email: "user@example.com",
  username: "jdoe",
  ip_address: "{{auto}}",
});

// Set tags for filtering
Sentry.setTag("page_locale", "en-us");
Sentry.setTag("feature_flag", "new-checkout");

// Set extra data
Sentry.setExtra("api_response", responseData);

// Add breadcrumb
Sentry.addBreadcrumb({
  category: "auth",
  message: "User logged in",
  level: "info",
  data: { method: "oauth" },
});

// Scoped context
Sentry.withScope((scope) => {
  scope.setTag("section", "billing");
  scope.setLevel("warning");
  Sentry.captureException(new Error("Payment retry"));
});

Performance Monitoring

// Manual transaction
const transaction = Sentry.startTransaction({
  op: "task",
  name: "Process Order",
});

const span = transaction.startChild({
  op: "db.query",
  description: "SELECT * FROM orders",
});
// ... database operation
span.finish();

transaction.finish();

Sentry CLI

CommandDescription
sentry-cli loginAuthenticate with Sentry
sentry-cli releases new VERSIONCreate a new release
sentry-cli releases set-commits VERSION --autoAssociate commits
sentry-cli releases files VERSION upload-sourcemaps ./distUpload source maps
sentry-cli releases finalize VERSIONFinalize a release
sentry-cli releases deploys VERSION new -e productionRecord deployment
sentry-cli send-event -m "Test event"Send a test event
sentry-cli monitor run SLUG -- commandWrap a cron job
# Complete release workflow
VERSION=$(sentry-cli releases propose-version)
sentry-cli releases new "$VERSION"
sentry-cli releases set-commits "$VERSION" --auto
sentry-cli releases files "$VERSION" upload-sourcemaps ./dist --url-prefix '~/static/js'
sentry-cli releases finalize "$VERSION"
sentry-cli releases deploys "$VERSION" new -e production

Advanced Usage

Custom Sampling

Sentry.init({
  dsn: "...",
  tracesSampler: (samplingContext) => {
    if (samplingContext.transactionContext.name === "/health") {
      return 0; // Drop health checks
    }
    if (samplingContext.transactionContext.name.includes("/api/critical")) {
      return 1.0; // Always sample critical paths
    }
    return 0.1; // 10% for everything else
  },
});

Before Send Hook

Sentry.init({
  dsn: "...",
  beforeSend(event, hint) {
    // Filter out non-critical errors
    if (event.exception?.values?.[0]?.type === "NetworkError") {
      return null; // Drop this event
    }
    // Scrub sensitive data
    if (event.request?.headers) {
      delete event.request.headers["Authorization"];
    }
    return event;
  },
});

Self-Hosted Sentry

# Clone and install self-hosted Sentry
git clone https://github.com/getsentry/self-hosted.git
cd self-hosted
./install.sh
docker compose up -d

# Access at http://localhost:9000

Configuration

# .sentryclirc
[auth]
token=sntrys_YOUR_AUTH_TOKEN

[defaults]
org=my-org
project=my-project
url=https://sentry.io/

# Environment variables
export SENTRY_DSN="https://key@o0.ingest.sentry.io/0"
export SENTRY_AUTH_TOKEN="sntrys_..."
export SENTRY_ORG="my-org"
export SENTRY_PROJECT="my-project"
export SENTRY_ENVIRONMENT="production"
export SENTRY_RELEASE="my-app@1.2.0"

Troubleshooting

IssueSolution
Events not appearingVerify DSN is correct; check sentry-cli send-event -m "test"
Source maps not workingEnsure upload-sourcemaps path and --url-prefix match deployed assets
Too many events (quota)Adjust sampleRate, use beforeSend to filter noise
Duplicate eventsCheck for multiple Sentry.init() calls or duplicate error handlers
PII in eventsUse beforeSend to scrub data or set send_default_pii: false
Performance data missingVerify tracesSampleRate > 0 and tracing integration is loaded
High latency from SDKReduce tracesSampleRate; SDK is async but can add overhead
Self-hosted disk fullPrune old events: docker compose run --rm web cleanup