Add Sentry integration for error monitoring and performance tracking 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
parent
48adb23ab0
commit
e01095f52d
7 changed files with 2331 additions and 5 deletions
149
README-sentry.md
Normal file
149
README-sentry.md
Normal file
|
|
@ -0,0 +1,149 @@
|
|||
# Sentry Integration
|
||||
|
||||
This document explains how to configure and use Sentry for error monitoring and performance tracking in the Continue CLI.
|
||||
|
||||
## Setup
|
||||
|
||||
### Environment Variables
|
||||
|
||||
To enable Sentry, set the following environment variables:
|
||||
|
||||
```bash
|
||||
# Required: Sentry DSN (Data Source Name)
|
||||
export SENTRY_DSN="https://your-dsn@sentry.io/project-id"
|
||||
|
||||
# Optional: Environment name (defaults to NODE_ENV or "development")
|
||||
export SENTRY_ENVIRONMENT="production"
|
||||
|
||||
# Optional: Sample rates (defaults to 1.0 for all)
|
||||
export SENTRY_SAMPLE_RATE="1.0" # Error sampling rate
|
||||
export SENTRY_PROFILES_SAMPLE_RATE="1.0" # Performance profiling rate
|
||||
export SENTRY_TRACES_SAMPLE_RATE="1.0" # Performance tracing rate
|
||||
```
|
||||
|
||||
### Disabling Sentry
|
||||
|
||||
To completely disable Sentry, you can:
|
||||
|
||||
1. **Not set `SENTRY_DSN`** - Sentry will be disabled automatically
|
||||
2. **Explicitly disable**: `export SENTRY_ENABLED="false"`
|
||||
|
||||
## What Gets Monitored
|
||||
|
||||
### Automatic Error Capture
|
||||
|
||||
- **Unhandled Promise Rejections**: Global promise rejections are captured
|
||||
- **Uncaught Exceptions**: Global uncaught exceptions are captured
|
||||
- **Logger Errors**: All `logger.error()` and `logger.warn()` calls are sent to Sentry
|
||||
- **Command Errors**: Errors in chat commands and other CLI operations
|
||||
|
||||
### Performance Monitoring
|
||||
|
||||
- **Profiling**: CPU and memory profiling data (when enabled)
|
||||
- **Performance Traces**: Request timing and performance metrics
|
||||
|
||||
### Context Information
|
||||
|
||||
Sentry automatically includes:
|
||||
- Application version
|
||||
- Environment (development/production)
|
||||
- Node.js version and platform
|
||||
- Error stack traces
|
||||
- Custom context for each error (when available)
|
||||
|
||||
## Usage in Code
|
||||
|
||||
The Sentry service is automatically initialized and available throughout the application. You can use it directly:
|
||||
|
||||
```typescript
|
||||
import sentryService from "./sentry.js";
|
||||
|
||||
// Capture an exception with context
|
||||
try {
|
||||
// some code
|
||||
} catch (error) {
|
||||
sentryService.captureException(error, {
|
||||
context: "my_operation",
|
||||
userId: "12345",
|
||||
});
|
||||
}
|
||||
|
||||
// Capture a message
|
||||
sentryService.captureMessage("Something important happened", "info", {
|
||||
customData: "value"
|
||||
});
|
||||
|
||||
// Set user context
|
||||
sentryService.setUser({
|
||||
id: "user123",
|
||||
email: "user@example.com"
|
||||
});
|
||||
|
||||
// Add breadcrumbs for debugging
|
||||
sentryService.addBreadcrumb({
|
||||
message: "User performed action",
|
||||
category: "user",
|
||||
level: "info",
|
||||
data: { action: "click_button" }
|
||||
});
|
||||
```
|
||||
|
||||
## Testing the Integration
|
||||
|
||||
### Test Error Capture
|
||||
|
||||
```bash
|
||||
# Set up Sentry (replace with your actual DSN)
|
||||
export SENTRY_DSN="https://your-dsn@sentry.io/project-id"
|
||||
|
||||
# Run the CLI and trigger an error to test
|
||||
cn "this should work normally"
|
||||
```
|
||||
|
||||
### Test Disabled State
|
||||
|
||||
```bash
|
||||
# Disable Sentry
|
||||
export SENTRY_ENABLED="false"
|
||||
# or simply don't set SENTRY_DSN
|
||||
|
||||
# Run the CLI - no Sentry data should be sent
|
||||
cn "this will run without Sentry"
|
||||
```
|
||||
|
||||
### Verify Configuration
|
||||
|
||||
The application logs will show when Sentry is initialized:
|
||||
|
||||
```
|
||||
DEBUG: Sentry initialized { environment: 'development', release: '0.0.0-dev' }
|
||||
```
|
||||
|
||||
If Sentry is disabled, you won't see this log message.
|
||||
|
||||
## Privacy and Security
|
||||
|
||||
- Sentry only captures error information and performance metrics
|
||||
- No user prompts or sensitive data are sent to Sentry by default
|
||||
- All data transmission is encrypted (HTTPS)
|
||||
- You control what environment and sampling rates to use
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Sentry Not Working
|
||||
|
||||
1. **Check DSN**: Ensure `SENTRY_DSN` is set correctly
|
||||
2. **Check Network**: Ensure your environment can reach sentry.io
|
||||
3. **Check Logs**: Look for Sentry initialization messages in debug logs
|
||||
4. **Check Sampling**: Ensure sample rates are > 0
|
||||
|
||||
### Too Much Data
|
||||
|
||||
1. **Reduce Sample Rates**: Lower `SENTRY_SAMPLE_RATE`, `SENTRY_PROFILES_SAMPLE_RATE`, or `SENTRY_TRACES_SAMPLE_RATE`
|
||||
2. **Use Environment Filtering**: Set different configurations for dev vs prod
|
||||
|
||||
### No Data in Sentry Dashboard
|
||||
|
||||
1. **Check Project Settings**: Ensure the DSN matches your Sentry project
|
||||
2. **Check Filters**: Verify no filters are blocking your data
|
||||
3. **Wait**: It can take a few minutes for data to appear in Sentry
|
||||
1991
package-lock.json
generated
1991
package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
|
@ -43,6 +43,8 @@
|
|||
"@opentelemetry/resources": "^2.0.1",
|
||||
"@opentelemetry/sdk-node": "^0.203.0",
|
||||
"@opentelemetry/semantic-conventions": "^1.36.0",
|
||||
"@sentry/node": "^9.43.0",
|
||||
"@sentry/profiling-node": "^9.43.0",
|
||||
"@types/express": "^5.0.3",
|
||||
"@types/react": "^19.1.8",
|
||||
"@types/turndown": "^5.0.5",
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ import { ModelServiceState, SERVICE_NAMES } from "../services/types.js";
|
|||
import { loadSession, saveSession } from "../session.js";
|
||||
import { streamChatResponse } from "../streamChatResponse.js";
|
||||
import { constructSystemMessage } from "../systemMessage.js";
|
||||
import sentryService from "../sentry.js";
|
||||
import { posthogService } from "../telemetry/posthogService.js";
|
||||
import telemetryService from "../telemetry/telemetryService.js";
|
||||
import { startTUIChat } from "../ui/index.js";
|
||||
|
|
@ -123,7 +124,13 @@ async function processMessage(
|
|||
// Save session after each successful response
|
||||
saveSession(chatHistory);
|
||||
} catch (e: any) {
|
||||
logger.error(`\n${chalk.red(`Error: ${formatError(e)}`)}`);
|
||||
const error = e instanceof Error ? e : new Error(String(e));
|
||||
logger.error(`\n${chalk.red(`Error: ${formatError(error)}`)}`);
|
||||
sentryService.captureException(error, {
|
||||
context: "chat_response",
|
||||
isHeadless,
|
||||
chatHistoryLength: chatHistory.length,
|
||||
});
|
||||
if (!isHeadless) {
|
||||
logger.info(
|
||||
chalk.dim(`Chat history:\n${JSON.stringify(chatHistory, null, 2)}`)
|
||||
|
|
@ -230,8 +237,13 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
|
|||
// Run headless mode
|
||||
await runHeadlessMode(prompt, options);
|
||||
} catch (error: any) {
|
||||
const err = error instanceof Error ? error : new Error(String(error));
|
||||
// Use headless-aware error logging to ensure fatal errors are shown in headless mode
|
||||
logging.error(chalk.red(`Fatal error: ${formatError(error)}`));
|
||||
logging.error(chalk.red(`Fatal error: ${formatError(err)}`));
|
||||
sentryService.captureException(err, {
|
||||
context: "chat_command_fatal",
|
||||
headless: options.headless,
|
||||
});
|
||||
process.exit(1);
|
||||
} finally {
|
||||
// Stop active time tracking
|
||||
|
|
|
|||
19
src/index.ts
19
src/index.ts
|
|
@ -7,6 +7,7 @@ import { logout } from "./commands/logout.js";
|
|||
import { remoteTest } from "./commands/remote-test.js";
|
||||
import { remote } from "./commands/remote.js";
|
||||
import { serve } from "./commands/serve.js";
|
||||
import sentryService from "./sentry.js";
|
||||
import { addCommonOptions, mergeParentOptions } from "./shared-options.js";
|
||||
import { configureConsoleForHeadless } from "./util/consoleOverride.js";
|
||||
import logger from "./util/logger.js";
|
||||
|
|
@ -16,11 +17,15 @@ import { getVersion } from "./version.js";
|
|||
// Add global error handlers to prevent uncaught errors from crashing the process
|
||||
process.on("unhandledRejection", (reason, promise) => {
|
||||
logger.error("Unhandled Rejection at:", { promise, reason });
|
||||
sentryService.captureException(reason instanceof Error ? reason : new Error(String(reason)), {
|
||||
promise: String(promise),
|
||||
});
|
||||
// Don't exit the process, just log the error
|
||||
});
|
||||
|
||||
process.on("uncaughtException", (error) => {
|
||||
logger.error("Uncaught Exception:", error);
|
||||
sentryService.captureException(error);
|
||||
// Don't exit the process, just log the error
|
||||
});
|
||||
|
||||
|
|
@ -178,5 +183,17 @@ try {
|
|||
program.parse();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
sentryService.captureException(error instanceof Error ? error : new Error(String(error)));
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// Graceful shutdown - flush Sentry data
|
||||
process.on("SIGINT", async () => {
|
||||
await sentryService.flush();
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
process.on("SIGTERM", async () => {
|
||||
await sentryService.flush();
|
||||
process.exit(0);
|
||||
});
|
||||
150
src/sentry.ts
Normal file
150
src/sentry.ts
Normal file
|
|
@ -0,0 +1,150 @@
|
|||
import * as Sentry from "@sentry/node";
|
||||
import { nodeProfilingIntegration } from "@sentry/profiling-node";
|
||||
import logger from "./util/logger.js";
|
||||
import { getVersion } from "./version.js";
|
||||
|
||||
interface SentryConfig {
|
||||
enabled: boolean;
|
||||
dsn?: string;
|
||||
environment: string;
|
||||
release: string;
|
||||
sampleRate: number;
|
||||
profilesSampleRate: number;
|
||||
tracesSampleRate: number;
|
||||
}
|
||||
|
||||
class SentryService {
|
||||
private config: SentryConfig;
|
||||
private initialized = false;
|
||||
|
||||
constructor() {
|
||||
this.config = this.loadConfig();
|
||||
if (this.config.enabled) {
|
||||
this.initialize();
|
||||
}
|
||||
}
|
||||
|
||||
private loadConfig(): SentryConfig {
|
||||
const enabled = process.env.SENTRY_ENABLED !== "false" && !!process.env.SENTRY_DSN;
|
||||
|
||||
return {
|
||||
enabled,
|
||||
dsn: process.env.SENTRY_DSN,
|
||||
environment: process.env.SENTRY_ENVIRONMENT || process.env.NODE_ENV || "development",
|
||||
release: getVersion(),
|
||||
sampleRate: parseFloat(process.env.SENTRY_SAMPLE_RATE || "1.0"),
|
||||
profilesSampleRate: parseFloat(process.env.SENTRY_PROFILES_SAMPLE_RATE || "1.0"),
|
||||
tracesSampleRate: parseFloat(process.env.SENTRY_TRACES_SAMPLE_RATE || "1.0"),
|
||||
};
|
||||
}
|
||||
|
||||
private initialize() {
|
||||
if (this.initialized || !this.config.dsn) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
Sentry.init({
|
||||
dsn: this.config.dsn,
|
||||
environment: this.config.environment,
|
||||
release: this.config.release,
|
||||
sampleRate: this.config.sampleRate,
|
||||
profilesSampleRate: this.config.profilesSampleRate,
|
||||
tracesSampleRate: this.config.tracesSampleRate,
|
||||
integrations: [
|
||||
nodeProfilingIntegration(),
|
||||
],
|
||||
beforeSend(event) {
|
||||
// Filter out certain error types if needed
|
||||
if (event.exception?.values?.[0]?.type === "AbortError") {
|
||||
return null;
|
||||
}
|
||||
return event;
|
||||
},
|
||||
});
|
||||
|
||||
this.initialized = true;
|
||||
logger.debug("Sentry initialized", {
|
||||
environment: this.config.environment,
|
||||
release: this.config.release,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error("Failed to initialize Sentry", error);
|
||||
}
|
||||
}
|
||||
|
||||
public isEnabled(): boolean {
|
||||
return this.config.enabled && this.initialized;
|
||||
}
|
||||
|
||||
public captureException(error: Error, context?: Record<string, any>) {
|
||||
if (!this.isEnabled()) return;
|
||||
|
||||
Sentry.withScope((scope) => {
|
||||
if (context) {
|
||||
Object.entries(context).forEach(([key, value]) => {
|
||||
scope.setContext(key, value);
|
||||
});
|
||||
}
|
||||
Sentry.captureException(error);
|
||||
});
|
||||
}
|
||||
|
||||
public captureMessage(message: string, level: "info" | "warning" | "error" | "debug" | "fatal" = "info", context?: Record<string, any>) {
|
||||
if (!this.isEnabled()) return;
|
||||
|
||||
Sentry.withScope((scope) => {
|
||||
if (context) {
|
||||
Object.entries(context).forEach(([key, value]) => {
|
||||
scope.setContext(key, value);
|
||||
});
|
||||
}
|
||||
Sentry.captureMessage(message, level);
|
||||
});
|
||||
}
|
||||
|
||||
public setUser(user: { id?: string; email?: string; username?: string }) {
|
||||
if (!this.isEnabled()) return;
|
||||
|
||||
Sentry.setUser(user);
|
||||
}
|
||||
|
||||
public setTag(key: string, value: string) {
|
||||
if (!this.isEnabled()) return;
|
||||
|
||||
Sentry.setTag(key, value);
|
||||
}
|
||||
|
||||
public setContext(key: string, context: Record<string, any>) {
|
||||
if (!this.isEnabled()) return;
|
||||
|
||||
Sentry.setContext(key, context);
|
||||
}
|
||||
|
||||
public addBreadcrumb(breadcrumb: { message: string; category?: string; level?: "fatal" | "error" | "warning" | "log" | "info" | "debug"; data?: Record<string, any> }) {
|
||||
if (!this.isEnabled()) return;
|
||||
|
||||
Sentry.addBreadcrumb(breadcrumb);
|
||||
}
|
||||
|
||||
public startSpan(name: string, op?: string) {
|
||||
if (!this.isEnabled()) return null;
|
||||
|
||||
return Sentry.startSpan({ name, op }, (span) => span);
|
||||
}
|
||||
|
||||
public async flush(timeout = 2000): Promise<boolean> {
|
||||
if (!this.isEnabled()) return true;
|
||||
|
||||
return await Sentry.flush(timeout);
|
||||
}
|
||||
|
||||
public async close(timeout = 2000): Promise<boolean> {
|
||||
if (!this.isEnabled()) return true;
|
||||
|
||||
return await Sentry.close(timeout);
|
||||
}
|
||||
}
|
||||
|
||||
export const sentryService = new SentryService();
|
||||
export default sentryService;
|
||||
|
|
@ -3,6 +3,7 @@ import path from 'path';
|
|||
import os from 'os';
|
||||
import fs from 'fs';
|
||||
import crypto from 'crypto';
|
||||
import sentryService from '../sentry.js';
|
||||
|
||||
const { combine, timestamp, printf, errors } = winston.format;
|
||||
|
||||
|
|
@ -72,14 +73,20 @@ export function setLogLevel(level: string) {
|
|||
export default {
|
||||
debug: (message: string, meta?: any) => logger.debug(message, meta),
|
||||
info: (message: string, meta?: any) => logger.info(message, meta),
|
||||
warn: (message: string, meta?: any) => logger.warn(message, meta),
|
||||
warn: (message: string, meta?: any) => {
|
||||
logger.warn(message, meta);
|
||||
sentryService.captureMessage(message, "warning", meta);
|
||||
},
|
||||
error: (message: string, error?: Error | any, meta?: any) => {
|
||||
if (error instanceof Error) {
|
||||
logger.error(message, { ...meta, error: error.message, stack: error.stack });
|
||||
sentryService.captureException(error, { message, ...meta });
|
||||
} else if (error) {
|
||||
logger.error(message, { ...meta, error });
|
||||
sentryService.captureMessage(`${message}: ${String(error)}`, "error", meta);
|
||||
} else {
|
||||
logger.error(message, meta);
|
||||
sentryService.captureMessage(message, "error", meta);
|
||||
}
|
||||
},
|
||||
setLevel: setLogLevel,
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue