mirror of
https://github.com/sanjeed5/awesome-cursor-rules-mdc.git
synced 2026-11-30 14:52:55 +08:00
Regenerate all MDC rules with fresh Exa data and December 2025 best practices
- Refreshed all 241 library rules with current best practices - Updated Exa search results for all libraries with 2025 content - Fixed --regenerate-all flag logic to properly process all libraries - Removed duplicate astro entry in rules.json (merged tags) - Added missing docker.mdc and vim.mdc files - All rules now include modern patterns and anti-patterns - Updated with framework-specific recommendations for 2025 Technical improvements: - Fixed retry_failed_only logic in generate_mdc_files.py - Improved progress tracking for regeneration scenarios - Ensured proper handling of --refresh-exa flag
This commit is contained in:
+314
-126
@@ -1,146 +1,334 @@
|
||||
---
|
||||
description: This rule provides comprehensive best practices for integrating and utilizing Sentry in your projects. It covers code organization, performance, security, testing, and common pitfalls when using Sentry for error tracking and performance monitoring.
|
||||
globs: *.js,*.jsx,*.ts,*.tsx,*.py,*.java,*.kt,*.swift,*.go,*.rb,*.php,*.cs,*.cpp,*.c,*.m,*.mm,*.clj,*.cljs,*.scala,*.groovy,*.lua,*.erl,*.hrl,*.fs,*.fsi,*.vb,*.vba,*.sh,*.bash,*.zsh,*.ps1,*.psm1,*.sql,*.html,*.htm,*.css,*.scss,*.less,*.graphql,*.gql
|
||||
description: Definitive guidelines for integrating and using Sentry for error tracking and performance monitoring, ensuring optimal setup, performance, and debuggability across all applications.
|
||||
globs: **/*
|
||||
---
|
||||
- Ensure that your codebase is connected to Sentry, with source code management integrations (e.g., GitHub, GitLab, Bitbucket) and source maps properly configured. This enables Sentry to link errors to specific lines of code, dramatically improving debugging efficiency.
|
||||
- Implement custom alerts tailored to your needs, avoiding alert fatigue by prioritizing alerts based on severity or user impact. Set up different notification channels for varying alert priorities (e.g., Slack for low-priority, PagerDuty for high-priority).
|
||||
- Leverage Sentry's performance monitoring capabilities to track application performance metrics and identify slow transactions. Use distributed tracing to visualize request flows and pinpoint performance bottlenecks.
|
||||
- Implement alerts based on session-affected percentages when applicable to handle dynamic traffic.
|
||||
# Sentry Best Practices
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
Sentry is our definitive platform for error tracking and performance monitoring. Proper integration ensures we debug faster, ship more reliably, and maintain high application health. This guide outlines the mandatory best practices for all projects.
|
||||
|
||||
- **Directory Structure:**
|
||||
- Group Sentry-related initialization and configuration files in a dedicated directory (e.g., `sentry/`) for easy management.
|
||||
- Consider separate files for Sentry SDK initialization, custom integrations, and alert configurations.
|
||||
- **File Naming Conventions:**
|
||||
- Use descriptive names for Sentry-related files (e.g., `sentry.init.js`, `sentry.config.py`, `sentry.integrations.ts`).
|
||||
- **Module Organization:**
|
||||
- Encapsulate Sentry-related functionality within dedicated modules or classes to promote code reusability and maintainability.
|
||||
- Avoid direct Sentry SDK calls throughout the application; instead, use an abstraction layer or helper functions.
|
||||
- **Component Architecture:**
|
||||
- When using Sentry in UI frameworks (e.g., React, Vue), wrap key components with error boundaries to catch and report errors gracefully.
|
||||
- Create reusable components or hooks for common Sentry interactions, such as capturing user feedback or breadcrumbs.
|
||||
- **Code Splitting:**
|
||||
- Lazy-load Sentry SDK and related code to minimize initial bundle size and improve application loading times.
|
||||
- Use dynamic imports or similar techniques to load Sentry code only when it's needed.
|
||||
## 1. Code Organization and Initialization
|
||||
|
||||
Always initialize the Sentry SDK early in your application's bootstrap process. This ensures maximum coverage for errors and performance tracing.
|
||||
|
||||
### 1.1. Early and Centralized Initialization
|
||||
|
||||
Initialize Sentry once, as close to your application's entry point as possible. Use environment variables for sensitive data like DSN and for configuration that varies by environment.
|
||||
|
||||
❌ **BAD: Late or Scattered Initialization**
|
||||
```python
|
||||
# app/views.py (Django) or a random module
|
||||
import sentry_sdk
|
||||
|
||||
def my_function():
|
||||
if not sentry_sdk.is_initialized(): # Don't do this, it's too late and prone to race conditions
|
||||
sentry_sdk.init(dsn="YOUR_DSN")
|
||||
# ...
|
||||
```
|
||||
|
||||
✅ **GOOD: Application Bootstrap (Python Example)**
|
||||
```python
|
||||
# app.py or wsgi.py/asgi.py for web apps
|
||||
import os
|
||||
import sentry_sdk
|
||||
from sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration # Example for Lambda
|
||||
|
||||
SENTRY_DSN = os.getenv("SENTRY_DSN")
|
||||
SENTRY_ENVIRONMENT = os.getenv("SENTRY_ENVIRONMENT", "development")
|
||||
SENTRY_RELEASE = os.getenv("SENTRY_RELEASE", "unknown")
|
||||
SENTRY_TRACES_SAMPLE_RATE = float(os.getenv("SENTRY_TRACES_SAMPLE_RATE", "0.0")) # Default to 0.0 in prod
|
||||
|
||||
if SENTRY_DSN:
|
||||
sentry_sdk.init(
|
||||
dsn=SENTRY_DSN,
|
||||
environment=SENTRY_ENVIRONMENT,
|
||||
release=SENTRY_RELEASE,
|
||||
enable_tracing=True, # Always enable tracing, sampling controls overhead
|
||||
traces_sample_rate=SENTRY_TRACES_SAMPLE_RATE,
|
||||
# Add integrations as needed, e.g., for specific frameworks or platforms
|
||||
# integrations=[AwsLambdaIntegration()] if SENTRY_ENVIRONMENT == "aws-lambda" else [],
|
||||
)
|
||||
```
|
||||
|
||||
✅ **GOOD: Application Bootstrap (JavaScript/TypeScript Example)**
|
||||
```typescript
|
||||
// src/index.ts or app.ts
|
||||
import * as Sentry from "@sentry/node"; // or @sentry/browser, @sentry/react, etc.
|
||||
|
||||
const SENTRY_DSN = process.env.SENTRY_DSN;
|
||||
const SENTRY_ENVIRONMENT = process.env.SENTRY_ENVIRONMENT || "development";
|
||||
const SENTRY_RELEASE = process.env.SENTRY_RELEASE || "unknown";
|
||||
const SENTRY_TRACES_SAMPLE_RATE = parseFloat(process.env.SENTRY_TRACES_SAMPLE_RATE || "0.0");
|
||||
|
||||
if (SENTRY_DSN) {
|
||||
Sentry.init({
|
||||
dsn: SENTRY_DSN,
|
||||
environment: SENTRY_ENVIRONMENT,
|
||||
release: SENTRY_RELEASE,
|
||||
integrations: [
|
||||
// Add framework-specific integrations here, e.g., new Sentry.Integrations.Http({ tracing: true })
|
||||
// new Sentry.Integrations.Express(),
|
||||
],
|
||||
tracesSampleRate: SENTRY_TRACES_SAMPLE_RATE,
|
||||
enableTracing: true, // Redundant with tracesSampleRate > 0, but good for clarity
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### 1.2. Environment, Release, and User Context
|
||||
|
||||
Always set `environment` and `release` during initialization. Enrich events with user and other relevant context for faster debugging.
|
||||
|
||||
✅ **GOOD: Setting Context**
|
||||
```python
|
||||
import sentry_sdk
|
||||
|
||||
# ... Sentry init as above ...
|
||||
|
||||
def process_order(user_id: str, order_details: dict):
|
||||
with sentry_sdk.push_scope() as scope: # Use push_scope for temporary context
|
||||
scope.set_user({"id": user_id, "email": "user@example.com"})
|
||||
scope.set_tag("order_type", "premium")
|
||||
scope.set_context("order_details", order_details)
|
||||
try:
|
||||
# ... order processing logic ...
|
||||
raise ValueError("Failed to process payment")
|
||||
except Exception as e:
|
||||
sentry_sdk.capture_exception(e)
|
||||
```
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
- **Design Patterns:**
|
||||
- **Singleton:** Use a singleton pattern for the Sentry client instance to ensure consistent configuration and behavior.
|
||||
- **Observer:** Implement an observer pattern to capture and report application-specific events to Sentry.
|
||||
- **Decorator:** Utilize decorators to automatically capture exceptions or performance metrics for specific functions or methods.
|
||||
- **Recommended Approaches:**
|
||||
- Use breadcrumbs to capture user actions and application state leading up to an error, providing valuable context for debugging.
|
||||
- Set user context (ID, email, username) to associate errors with specific users, facilitating troubleshooting and impact assessment.
|
||||
- Capture release information (version, environment) to track errors across different deployments and environments.
|
||||
- **Anti-patterns:**
|
||||
- Avoid hardcoding sensitive information (DSN, API keys) directly in the code; use environment variables or configuration files.
|
||||
- Do not capture personally identifiable information (PII) without proper anonymization or consent; adhere to privacy regulations.
|
||||
- Refrain from disabling Sentry entirely in production; instead, configure appropriate sampling rates or filters to manage data volume.
|
||||
- **State Management:**
|
||||
- In applications using state management libraries (e.g., Redux, Vuex), integrate Sentry middleware to capture state changes and actions leading up to an error.
|
||||
- Serialize relevant state information and include it in the error context for debugging purposes.
|
||||
- **Error Handling:**
|
||||
- Use try-catch blocks to handle potential errors gracefully and report them to Sentry.
|
||||
- Implement global error handlers to catch uncaught exceptions and unhandled rejections.
|
||||
- Provide informative error messages to users and avoid exposing sensitive implementation details.
|
||||
### 2.1. Performance Tracing with OpenTelemetry
|
||||
|
||||
Leverage OpenTelemetry for distributed tracing. Sentry SDKs integrate seamlessly, allowing end-to-end visibility without rewriting existing instrumentation.
|
||||
|
||||
✅ **GOOD: OpenTelemetry Integration (Python Example)**
|
||||
```python
|
||||
import sentry_sdk
|
||||
from opentelemetry import trace
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
|
||||
from sentry_sdk.integrations.opentelemetry import SentrySpanProcessor
|
||||
|
||||
# Configure OpenTelemetry
|
||||
provider = TracerProvider()
|
||||
provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter())) # For local debugging
|
||||
provider.add_span_processor(SentrySpanProcessor()) # Send spans to Sentry
|
||||
trace.set_tracer_provider(provider)
|
||||
|
||||
# Initialize Sentry (ensure enable_tracing and traces_sample_rate are set)
|
||||
sentry_sdk.init(
|
||||
dsn="YOUR_DSN",
|
||||
enable_tracing=True,
|
||||
traces_sample_rate=1.0, # Adjust for production
|
||||
# ... other config ...
|
||||
)
|
||||
|
||||
# Use OpenTelemetry tracer
|
||||
tracer = trace.get_tracer(__name__)
|
||||
|
||||
def my_traced_function():
|
||||
with tracer.start_as_current_span("my-custom-operation"):
|
||||
print("Executing traced operation...")
|
||||
# ... your code ...
|
||||
```
|
||||
|
||||
### 2.2. Isolated Clients for Shared Environments (JavaScript/TypeScript)
|
||||
|
||||
**NEVER** use `Sentry.init()` in shared environments (e.g., browser extensions, VS Code extensions, third-party widgets). This pollutes global state and leads to data leakage. Create a dedicated client instance manually.
|
||||
|
||||
❌ **BAD: Global Init in Shared Environment**
|
||||
```typescript
|
||||
// browser_extension/background.ts
|
||||
import * as Sentry from "@sentry/browser";
|
||||
|
||||
Sentry.init({ // ❌ DANGER: Do NOT use Sentry.init() in shared environments!
|
||||
dsn: "YOUR_DSN",
|
||||
// ...
|
||||
});
|
||||
```
|
||||
|
||||
✅ **GOOD: Manual Client Setup for Shared Environments**
|
||||
```typescript
|
||||
// browser_extension/background.ts
|
||||
import {
|
||||
BrowserClient,
|
||||
defaultStackParser,
|
||||
getDefaultIntegrations,
|
||||
makeFetchTransport,
|
||||
Scope,
|
||||
} from "@sentry/browser";
|
||||
|
||||
// Filter out integrations that rely on global state
|
||||
const integrations = getDefaultIntegrations({}).filter(
|
||||
(defaultIntegration) =>
|
||||
!["BrowserApiErrors", "Breadcrumbs", "GlobalHandlers"].includes(defaultIntegration.name)
|
||||
);
|
||||
|
||||
const client = new BrowserClient({
|
||||
dsn: "YOUR_DSN",
|
||||
transport: makeFetchTransport,
|
||||
stackParser: defaultStackParser,
|
||||
integrations: integrations,
|
||||
tracesSampleRate: 1.0, // Adjust for production
|
||||
enableTracing: true,
|
||||
});
|
||||
|
||||
const scope = new Scope();
|
||||
scope.setClient(client);
|
||||
client.init(); // Initialize the client after setting it on the scope
|
||||
|
||||
// Manually capture exceptions using the client's scope
|
||||
try {
|
||||
// Your extension code here
|
||||
throw new Error("Example error in extension");
|
||||
} catch (error) {
|
||||
scope.captureException(error);
|
||||
}
|
||||
```
|
||||
|
||||
### 2.3. AWS Lambda Integration
|
||||
|
||||
For serverless functions, use the platform-specific integration.
|
||||
|
||||
✅ **GOOD: AWS Lambda (Python Example)**
|
||||
```python
|
||||
import os
|
||||
import sentry_sdk
|
||||
from sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration
|
||||
|
||||
SENTRY_DSN = os.getenv("SENTRY_DSN")
|
||||
SENTRY_TRACES_SAMPLE_RATE = float(os.getenv("SENTRY_TRACES_SAMPLE_RATE", "0.0"))
|
||||
|
||||
if SENTRY_DSN:
|
||||
sentry_sdk.init(
|
||||
dsn=SENTRY_DSN,
|
||||
integrations=[AwsLambdaIntegration()],
|
||||
traces_sample_rate=SENTRY_TRACES_SAMPLE_RATE,
|
||||
environment=os.getenv("SENTRY_ENVIRONMENT", "production"),
|
||||
release=os.getenv("SENTRY_RELEASE", "unknown"),
|
||||
)
|
||||
|
||||
def lambda_handler(event, context):
|
||||
# Your Lambda function logic
|
||||
print("Processing event...")
|
||||
raise ValueError("Something went wrong in Lambda!")
|
||||
return {"statusCode": 200, "body": "Success"}
|
||||
```
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
- **Optimization Techniques:**
|
||||
- Enable compression for Sentry payloads to reduce network bandwidth and improve transmission speed.
|
||||
- Use Sentry's sampling options to control the number of events captured, balancing data accuracy with performance impact.
|
||||
- Configure Sentry's throttling options to prevent excessive event submission and potential performance bottlenecks.
|
||||
- **Memory Management:**
|
||||
- Be mindful of memory usage when capturing large payloads or attachments; avoid unnecessary data serialization.
|
||||
- Periodically flush the Sentry event queue to release memory and prevent out-of-memory errors.
|
||||
- **Rendering Optimization:**
|
||||
- For UI frameworks, defer Sentry initialization until after the initial render to avoid blocking the user interface.
|
||||
- Optimize breadcrumb and event data collection to minimize performance overhead during rendering.
|
||||
- **Bundle Size Optimization:**
|
||||
- Tree-shake the Sentry SDK to remove unused modules and reduce bundle size.
|
||||
- Use code splitting to load Sentry code only when it's needed.
|
||||
- **Lazy Loading:**
|
||||
- Implement lazy loading for Sentry components and modules to improve initial page load times.
|
||||
- Use dynamic imports or similar techniques to load Sentry code on demand.
|
||||
### 3.1. Configure `traces_sample_rate` Judiciously
|
||||
|
||||
## 4. Security Best Practices
|
||||
`traces_sample_rate` directly impacts performance overhead and Sentry quota usage.
|
||||
|
||||
- **Common Vulnerabilities:**
|
||||
- **Data Leakage:** Ensure that sensitive information (PII, API keys) is not inadvertently exposed in Sentry events or breadcrumbs.
|
||||
- **Cross-Site Scripting (XSS):** Sanitize user-generated content before capturing it in Sentry to prevent XSS attacks.
|
||||
- **Denial of Service (DoS):** Implement rate limiting and throttling to prevent excessive event submission from malicious actors.
|
||||
- **Input Validation:**
|
||||
- Validate user input on both the client and server sides to prevent malicious data from reaching Sentry.
|
||||
- Sanitize and escape user input before capturing it in Sentry events or breadcrumbs.
|
||||
- **Authentication and Authorization:**
|
||||
- Implement strong authentication and authorization mechanisms to protect Sentry API endpoints and data.
|
||||
- Restrict access to Sentry projects and events based on user roles and permissions.
|
||||
- **Data Protection:**
|
||||
- Implement data anonymization and masking techniques to protect sensitive user information in Sentry events.
|
||||
- Comply with data privacy regulations (e.g., GDPR, CCPA) when collecting and processing user data with Sentry.
|
||||
- **Secure API Communication:**
|
||||
- Use HTTPS for all communication with Sentry API endpoints to encrypt data in transit.
|
||||
- Verify the SSL/TLS certificates of Sentry API endpoints to prevent man-in-the-middle attacks.
|
||||
* **Development:** Set to `1.0` to capture all transactions for full visibility.
|
||||
* **Production:** Set to a lower value (e.g., `0.01` to `0.1`) to sample a representative subset of transactions. Adjust based on traffic volume and monitoring needs.
|
||||
|
||||
❌ **BAD: `traces_sample_rate=1.0` in Production**
|
||||
```python
|
||||
sentry_sdk.init(
|
||||
dsn="YOUR_PROD_DSN",
|
||||
traces_sample_rate=1.0, # ❌ This will send ALL traces, potentially incurring high costs and overhead.
|
||||
enable_tracing=True,
|
||||
)
|
||||
```
|
||||
|
||||
✅ **GOOD: Controlled Sampling in Production**
|
||||
```python
|
||||
sentry_sdk.init(
|
||||
dsn="YOUR_PROD_DSN",
|
||||
traces_sample_rate=0.05, # ✅ Sample 5% of transactions in production
|
||||
enable_tracing=True,
|
||||
)
|
||||
```
|
||||
|
||||
## 4. Common Pitfalls and Gotchas
|
||||
|
||||
### 4.1. Missing or Invalid DSN
|
||||
|
||||
Without a valid DSN, Sentry cannot send events. Always verify your DSN is correctly configured, ideally via environment variables.
|
||||
|
||||
❌ **BAD: Hardcoded or Missing DSN**
|
||||
```python
|
||||
sentry_sdk.init(
|
||||
dsn="", # ❌ No DSN means no events
|
||||
# ...
|
||||
)
|
||||
```
|
||||
|
||||
✅ **GOOD: DSN from Environment Variables**
|
||||
```python
|
||||
import os
|
||||
sentry_sdk.init(
|
||||
dsn=os.getenv("SENTRY_DSN"), # ✅ Always load DSN from environment
|
||||
# ...
|
||||
)
|
||||
```
|
||||
|
||||
### 4.2. Unset `environment` and `release`
|
||||
|
||||
Events without `environment` or `release` are significantly harder to triage and correlate. Always set these values.
|
||||
|
||||
❌ **BAD: Omitting Environment/Release**
|
||||
```python
|
||||
sentry_sdk.init(
|
||||
dsn="YOUR_DSN",
|
||||
# No environment or release set ❌
|
||||
)
|
||||
```
|
||||
|
||||
✅ **GOOD: Explicit Environment/Release**
|
||||
```python
|
||||
sentry_sdk.init(
|
||||
dsn="YOUR_DSN",
|
||||
environment=os.getenv("SENTRY_ENVIRONMENT", "development"), # ✅
|
||||
release=os.getenv("SENTRY_RELEASE", "my-app@1.0.0"), # ✅
|
||||
)
|
||||
```
|
||||
|
||||
### 4.3. Ignoring Inbound Filters
|
||||
|
||||
If Sentry events aren't appearing, check your Sentry project's **Project Settings > Inbound Filters**. Ensure you haven't accidentally enabled filters that block events (e.g., "Filter out errors known to be caused by browser extensions" if you're in a shared environment).
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
- **Unit Testing:**
|
||||
- Write unit tests to verify the functionality of Sentry-related modules and components.
|
||||
- Mock or stub Sentry SDK functions to isolate the code under test.
|
||||
- **Integration Testing:**
|
||||
- Perform integration tests to ensure that Sentry is properly integrated with the application and that events are captured correctly.
|
||||
- Use a test Sentry project to capture and verify events during integration testing.
|
||||
- **End-to-End Testing:**
|
||||
- Conduct end-to-end tests to simulate real-world user scenarios and verify that errors are captured and reported to Sentry.
|
||||
- Use a staging environment or test Sentry project for end-to-end testing.
|
||||
- **Test Organization:**
|
||||
- Organize Sentry-related tests in a dedicated directory or module.
|
||||
- Follow a consistent naming convention for Sentry-related test files and functions.
|
||||
- **Mocking and Stubbing:**
|
||||
- Use mocking libraries (e.g., Jest, Sinon) to create mock Sentry SDK objects for testing purposes.
|
||||
- Stub Sentry SDK functions to control their behavior and verify that they are called correctly.
|
||||
### 5.1. Disabling Sentry in Test Environments
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
Prevent test noise and unnecessary Sentry events by disabling the SDK during automated tests.
|
||||
|
||||
- **Frequent Mistakes:**
|
||||
- Forgetting to initialize the Sentry SDK properly.
|
||||
- Capturing sensitive information without proper anonymization.
|
||||
- Overloading Sentry with too many events or attachments.
|
||||
- Ignoring Sentry alerts or dashboards.
|
||||
- **Edge Cases:**
|
||||
- Handling errors during Sentry SDK initialization.
|
||||
- Dealing with network connectivity issues when sending events.
|
||||
- Managing Sentry SDK configuration in different environments.
|
||||
- **Version-Specific Issues:**
|
||||
- Review Sentry SDK release notes for breaking changes and compatibility issues.
|
||||
- Test Sentry SDK upgrades in a staging environment before deploying to production.
|
||||
- **Compatibility Concerns:**
|
||||
- Ensure compatibility between the Sentry SDK and other libraries or frameworks used in the application.
|
||||
- Resolve any conflicts or version mismatches that may arise.
|
||||
- **Debugging Strategies:**
|
||||
- Use Sentry's debug mode to log SDK activity and troubleshoot integration issues.
|
||||
- Inspect Sentry events in the Sentry UI to verify data accuracy and identify potential problems.
|
||||
- Utilize Sentry's breadcrumbs and user context to gain insights into the cause of errors.
|
||||
✅ **GOOD: Conditional Sentry Initialization**
|
||||
```python
|
||||
import os
|
||||
import sentry_sdk
|
||||
|
||||
## 7. Tooling and Environment
|
||||
# Only initialize Sentry if DSN is present AND not in a test environment
|
||||
if os.getenv("SENTRY_DSN") and os.getenv("APP_ENV") != "test":
|
||||
sentry_sdk.init(
|
||||
dsn=os.getenv("SENTRY_DSN"),
|
||||
environment=os.getenv("SENTRY_ENVIRONMENT", "development"),
|
||||
release=os.getenv("SENTRY_RELEASE", "unknown"),
|
||||
traces_sample_rate=float(os.getenv("SENTRY_TRACES_SAMPLE_RATE", "0.0")),
|
||||
enable_tracing=True,
|
||||
)
|
||||
```
|
||||
|
||||
- **Recommended Tools:**
|
||||
- Sentry CLI for managing Sentry projects and releases.
|
||||
- Source code management system (e.g., Git) for version control.
|
||||
- Package manager (e.g., npm, pip) for managing Sentry SDK dependencies.
|
||||
- **Build Configuration:**
|
||||
- Integrate Sentry SDK into the build process to capture build errors and performance metrics.
|
||||
- Use environment variables or configuration files to manage Sentry SDK settings in different environments.
|
||||
- **Linting and Formatting:**
|
||||
- Configure linters (e.g., ESLint, PyLint) to enforce code style and best practices for Sentry code.
|
||||
- Use code formatters (e.g., Prettier, Black) to automatically format Sentry code and ensure consistency.
|
||||
- **Deployment:**
|
||||
- Deploy Sentry SDK and related code as part of the application deployment process.
|
||||
- Configure Sentry SDK to capture deployment information (version, environment) for tracking errors across releases.
|
||||
- **CI/CD Integration:**
|
||||
- Integrate Sentry SDK into the CI/CD pipeline to automate error capture and reporting during testing and deployment.
|
||||
- Use Sentry's release tracking features to associate errors with specific deployments and releases.
|
||||
### 5.2. Manual Error Capture
|
||||
|
||||
By adhering to these best practices, you can effectively leverage Sentry to improve the reliability, performance, and security of your applications.
|
||||
For specific, non-critical errors that you want to report without crashing the application, use `sentry_sdk.capture_message()` or `sentry_sdk.capture_exception()`.
|
||||
|
||||
✅ **GOOD: Manual Capture**
|
||||
```python
|
||||
import sentry_sdk
|
||||
|
||||
def process_data(data: list):
|
||||
if not data:
|
||||
sentry_sdk.capture_message("Received empty data for processing.", level="warning") # ✅ Report non-exception issues
|
||||
return False
|
||||
try:
|
||||
# ... process data ...
|
||||
raise ConnectionError("Database unreachable")
|
||||
except ConnectionError as e:
|
||||
sentry_sdk.capture_exception(e) # ✅ Explicitly capture exceptions
|
||||
return False
|
||||
```
|
||||
Reference in New Issue
Block a user