Skip to main content

error tracking

Error Tracking in GitLab

Overview

GitLab provides comprehensive error tracking capabilities to help teams identify, prioritize, and resolve application errors efficiently. Error tracking aggregates similar errors, provides context for debugging, and integrates seamlessly with GitLab's issue management.

What is Error Tracking?

Error tracking enables you to:

  • Aggregate errors: Group similar errors together
  • Prioritize issues: Focus on high-impact errors
  • Debug faster: Access stack traces and context
  • Track trends: Monitor error rates over time
  • Automate triage: Create issues automatically

Core Features

1. Error Aggregation

GitLab automatically groups similar errors:

  • Same error message and type
  • Same stack trace fingerprint
  • Same affected code location

Benefits:

  • Reduce noise from repeated errors
  • Focus on unique issues
  • Track error frequency

2. Error Grouping Algorithms

GitLab uses intelligent fingerprinting:

Error Fingerprint = hash(
  error_type +
  error_message +
  stack_trace_structure
)

Example:

// These errors get grouped together throw new Error('User not found: 123'); throw new Error('User not found: 456'); throw new Error('User not found: 789'); // Grouped as: "User not found: <id>" // Count: 3 occurrences

3. Error Details

Each error capture includes:

  • Stack trace: Full call stack
  • Context: Request details, user info
  • Environment: Browser, OS, device
  • Breadcrumbs: Events leading to error
  • Custom data: Application-specific metadata

Integration Methods

Native GitLab Error Tracking

GitLab provides built-in error tracking for frontend applications.

Frontend Error Tracking

Enable error tracking in your project settings:

Settings Monitor Error Tracking Enable Error Tracking

JavaScript Integration

// Install GitLab Error Tracking SDK // npm install @gitlab/error-tracking import { initErrorTracking } from '@gitlab/error-tracking'; initErrorTracking({ dsn: 'https://your-project.gitlab.io/error-tracking', environment: process.env.NODE_ENV, release: process.env.APP_VERSION, }); // Errors are automatically captured throw new Error('Something went wrong'); // Manual error reporting try { riskyOperation(); } catch (error) { captureException(error, { user: { id: userId, email: userEmail }, tags: { feature: 'checkout' }, }); }

Sentry Integration

GitLab integrates with Sentry for advanced error tracking.

Setup Sentry Integration

  1. Create Sentry Account

  2. Configure in GitLab

    • Navigate to Settings Monitor Error Tracking
    • Select Sentry
    • Enter your Sentry DSN
    • Save configuration
  3. Install Sentry SDK

// Node.js const Sentry = require('@sentry/node'); Sentry.init({ dsn: process.env.SENTRY_DSN, environment: process.env.NODE_ENV, release: process.env.GIT_COMMIT, tracesSampleRate: 1.0, }); // Python import sentry_sdk sentry_sdk.init( dsn=os.environ["SENTRY_DSN"], environment=os.environ["NODE_ENV"], release=os.environ["GIT_COMMIT"], traces_sample_rate=1.0, ) // Go import "github.com/getsentry/sentry-go" sentry.Init(sentry.ClientOptions{ Dsn: os.Getenv("SENTRY_DSN"), Environment: os.Getenv("NODE_ENV"), Release: os.Getenv("GIT_COMMIT"), TracesSampleRate: 1.0, })

Error Triage Workflow

1. Error Detection

Errors are automatically captured and sent to GitLab:

Application  Error Occurs  SDK Captures  GitLab Processes  Groups Errors

2. Viewing Errors

Access error tracking:

  1. Navigate to Monitor Error Tracking
  2. View error list with:
    • Error message
    • Frequency
    • First seen / Last seen
    • Affected users
    • Status

3. Error Details

Click on an error to see:

## Error: TypeError: Cannot read property 'id' of undefined **First Seen:** 2026-01-08 10:23:45 **Last Seen:** 2026-01-08 14:30:12 **Frequency:** 47 occurrences **Affected Users:** 23 users ### Stack Trace ```javascript at getUserProfile (src/services/user.js:42:18) at async handleRequest (src/api/routes.js:89:12) at async Server.<anonymous> (node_modules/express/lib/router/index.js:284:7)

Request Details

  • URL: /api/users/profile
  • Method: GET
  • User-Agent: Mozilla/5.0...
  • User ID: 12345
  1. User clicked "View Profile" button
  2. API request initiated
  3. Database query executed
  4. Error thrown

### 4. Error Status Management

Manage error lifecycle:
- **Unresolved**: New error requiring attention
- **Resolved**: Error fixed, monitoring for recurrence
- **Ignored**: Known issue, not requiring immediate action
- **In Progress**: Actively being worked on

### 5. Creating Issues from Errors

Automatically create GitLab issues:
1. Click **Create Issue** on error details
2. Issue is pre-populated with:
   - Error description
   - Stack trace
   - Reproduction steps
   - Environment details
3. Assign to team member
4. Link to related errors

## Error Alerting

### Alert Configuration

Set up alerts for critical errors:

#### 1. Error Rate Threshold
```yaml
# Alert when error rate > 5% of requests
alert:
  type: error_rate
  threshold: 5
  window: 5m
  notification:
    - slack: #alerts
    - email: team@example.com

2. New Error Detection

# Alert on first occurrence of new error type alert: type: new_error notification: - slack: #engineering

3. Error Spike Detection

# Alert when error count increases 200% over baseline alert: type: error_spike threshold: 200 baseline_window: 1h notification: - pagerduty: oncall

Notification Channels

Configure notification destinations:

  • Slack: Real-time team notifications
  • Email: Digest and critical alerts
  • PagerDuty: On-call escalation
  • Webhooks: Custom integrations

Error Context and Breadcrumbs

Adding Context

Enrich errors with application context:

// JavaScript Sentry.setContext('user', { id: user.id, email: user.email, subscription: user.subscription_tier, }); Sentry.setContext('order', { id: order.id, total: order.total, items: order.items.length, });
# Python sentry_sdk.set_context("user", { "id": user.id, "email": user.email, "subscription": user.subscription_tier })
// Go sentry.ConfigureScope(func(scope *sentry.Scope) { scope.SetContext("user", map[string]interface{}{ "id": user.ID, "email": user.Email, }) })

Recording Breadcrumbs

Track events leading to errors:

// Automatic breadcrumbs // - HTTP requests // - Console logs // - DOM events // - Navigation // Manual breadcrumbs Sentry.addBreadcrumb({ category: 'auth', message: 'User login attempted', level: 'info', }); Sentry.addBreadcrumb({ category: 'api', message: 'Payment API called', level: 'debug', data: { amount: 99.99, currency: 'USD', }, });

Error Filtering and Sampling

Client-Side Filtering

Ignore expected errors:

Sentry.init({ dsn: process.env.SENTRY_DSN, beforeSend(event, hint) { // Ignore network errors if (event.exception && event.exception.values) { const error = event.exception.values[0]; if (error.type === 'NetworkError') { return null; // Don't send } } // Ignore errors from browser extensions if (event.request && event.request.url) { if (event.request.url.includes('chrome-extension://')) { return null; } } return event; }, });

Server-Side Filtering

Configure inbound filters in GitLab/Sentry settings:

  • Legacy browsers: Ignore old browser errors
  • Known issues: Filter resolved errors
  • Web crawlers: Exclude bot traffic
  • Localhost: Ignore development errors

Sampling Strategy

Control error volume:

// Sample 100% of errors in production // Sample 10% in staging const sampleRate = process.env.NODE_ENV === 'production' ? 1.0 : 0.1; Sentry.init({ dsn: process.env.SENTRY_DSN, sampleRate: sampleRate, });

Monitoring Error Patterns

Track error metrics over time:

  • Error rate: Errors per request/transaction
  • Unique errors: New error types
  • Error frequency: Most common errors
  • Affected users: User impact analysis
  • Error resolution time: MTTR for errors

Trend Visualization

View error trends:

Error Rate Over Time
100                     
 90                  
 80               
 70            
 60         
 50      
 40   
 30 
    
     Mon  Tue  Wed  Thu  Fri

Error Correlation

Identify patterns:

  • Release correlation: Errors after deployments
  • Feature correlation: Errors in specific features
  • User segment correlation: Errors for specific user groups
  • Time correlation: Errors during peak hours

Production Best Practices

1. Meaningful Error Messages

Write descriptive errors:

// Bad: Generic message throw new Error('Invalid input'); // Good: Specific, actionable message throw new Error(`User ID ${userId} not found in database`);

2. Error Boundaries (React)

Catch component errors:

import * as Sentry from '@sentry/react'; class ErrorBoundary extends React.Component { componentDidCatch(error, errorInfo) { Sentry.captureException(error, { contexts: { react: { componentStack: errorInfo.componentStack, }, }, }); } render() { return this.props.children; } } // Wrap your app <ErrorBoundary> <App /> </ErrorBoundary>

3. Async Error Handling

Catch promise rejections:

// Global handler window.addEventListener('unhandledrejection', (event) => { Sentry.captureException(event.reason); }); // Proper async/await async function fetchData() { try { return await api.getData(); } catch (error) { Sentry.captureException(error, { tags: { operation: 'fetch_data' }, }); throw error; // Re-throw for upstream handling } }

4. Rate Limiting

Prevent error flooding:

Sentry.init({ dsn: process.env.SENTRY_DSN, // Limit to 100 events per second beforeSend(event) { // Implement custom rate limiting if (rateLimiter.isExceeded()) { return null; } return event; }, });

5. PII Scrubbing

Protect sensitive data:

Sentry.init({ dsn: process.env.SENTRY_DSN, beforeSend(event) { // Scrub sensitive data if (event.request && event.request.headers) { delete event.request.headers['Authorization']; delete event.request.headers['Cookie']; } return event; }, });

Debugging with Error Tracking

Source Maps

Enable source maps for readable stack traces:

// webpack.config.js module.exports = { devtool: 'source-map', plugins: [ new SentryWebpackPlugin({ authToken: process.env.SENTRY_AUTH_TOKEN, org: 'my-org', project: 'my-project', include: './dist', ignore: ['node_modules', 'webpack.config.js'], }), ], };

Release Tracking

Track errors by release:

Sentry.init({ dsn: process.env.SENTRY_DSN, release: `${process.env.APP_NAME}@${process.env.GIT_COMMIT}`, });

Benefits:

  • Compare error rates between releases
  • Identify problematic deployments
  • Correlate errors with code changes

User Feedback

Collect user reports:

Sentry.showReportDialog({ eventId: event.event_id, user: { email: user.email, name: user.name, }, });

Performance Impact

Minimizing Overhead

Best practices to reduce performance impact:

  1. Async submission: Errors sent asynchronously
  2. Sampling: Capture subset of errors
  3. Rate limiting: Prevent error storms
  4. Lazy loading: Load SDK only when needed
// Lazy load Sentry if (process.env.NODE_ENV === 'production') { import('@sentry/browser').then((Sentry) => { Sentry.init({ dsn: process.env.SENTRY_DSN, }); }); }

Monitoring SDK Impact

Track error tracking overhead:

  • Monitor SDK initialization time
  • Track network requests to error tracking service
  • Measure memory usage
  • Profile CPU impact

Integration with CI/CD

Automated Error Monitoring

Monitor errors in CI/CD pipeline:

# .gitlab-ci.yml test: stage: test script: - npm test after_script: # Check error rate before deployment - ./scripts/check-error-rate.sh only: - merge_requests deploy: stage: deploy script: - npm run deploy after_script: # Create Sentry release - sentry-cli releases new "$CI_COMMIT_SHA" - sentry-cli releases set-commits "$CI_COMMIT_SHA" --auto - sentry-cli releases finalize "$CI_COMMIT_SHA"

Pre-Deployment Checks

Validate error rates before deployment:

#!/bin/bash # check-error-rate.sh ERROR_RATE=$(curl -s "https://sentry.io/api/0/projects/my-org/my-project/stats/" \ -H "Authorization: Bearer $SENTRY_AUTH_TOKEN" \ | jq '.error_rate') if (( $(echo "$ERROR_RATE > 0.05" | bc -l) )); then echo "Error rate too high: $ERROR_RATE" exit 1 fi

Cost Optimization

Strategies to Reduce Costs

  1. Smart sampling: Sample based on error type
  2. Filter noise: Exclude known non-critical errors
  3. Archive old errors: Retain recent data only
  4. Use error budgets: Limit errors per month

Example: Tiered Sampling

Sentry.init({ dsn: process.env.SENTRY_DSN, beforeSend(event, hint) { const error = hint.originalException; // Always capture critical errors if (error.severity === 'fatal') { return event; } // Sample 50% of errors if (error.severity === 'error') { return Math.random() < 0.5 ? event : null; } // Sample 10% of warnings if (error.severity === 'warning') { return Math.random() < 0.1 ? event : null; } return event; }, });

Compliance and Privacy

GDPR Considerations

Protect user privacy:

  • PII scrubbing: Remove personal data
  • Data retention: Limit error storage duration
  • User consent: Obtain consent for error tracking
  • Data deletion: Support user data deletion requests

Example: PII Scrubbing

Sentry.init({ dsn: process.env.SENTRY_DSN, beforeSend(event) { // Remove email addresses if (event.user && event.user.email) { event.user.email = '***@***.***'; } // Remove IP addresses if (event.user && event.user.ip_address) { event.user.ip_address = '0.0.0.0'; } // Scrub sensitive fields from extra data if (event.extra) { delete event.extra.creditCard; delete event.extra.ssn; delete event.extra.password; } return event; }, });

References

  • Tracing - Distributed tracing and performance
  • Logs - Log aggregation and analysis
  • APM - Application performance monitoring
  • Alerting - Alert configuration and management
  • Dashboards - Visualization and reporting