Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Sentry Laravel Laravel Package

sentry/sentry-laravel

Official Sentry SDK for Laravel. Automatically captures unhandled exceptions, performance data, and context from your app, sending issues and traces to Sentry for faster debugging and monitoring. Supports modern Laravel versions with simple Composer install.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require sentry/sentry-laravel
    
  2. Configure DSN:

    php artisan sentry:publish --dsn=YOUR_DSN_HERE
    

    This generates config/sentry.php and adds SENTRY_LARAVEL_DSN to .env.

  3. Enable Exception Handling (Laravel 11/12): Update bootstrap/app.php:

    ->withExceptions(function (Exceptions $exceptions) {
        \Sentry\Laravel\Integration::handles($exceptions);
    })
    
  4. First Use Case: Capture an exception in a controller:

    use function Sentry\captureException;
    
    try {
        // Risky operation
    } catch (\Throwable $e) {
        captureException($e);
    }
    

Key Configuration

  • Check config/sentry.php for:
    • dsn (required)
    • breadcrumbs (enable/disable)
    • tracing (enable performance monitoring)
    • logs (enable structured logging)
  • Environment variables:
    • SENTRY_TRACES_SAMPLE_RATE (default: 1.0 for 100% sampling)
    • SENTRY_ENVIRONMENT (e.g., production, staging)

Implementation Patterns

Core Workflows

  1. Exception Handling:

    • Unhandled Exceptions: Automatically captured via Integration::handles().
    • Manual Capture:
      // For exceptions
      captureException($e);
      
      // For messages
      captureMessage("User {$user->id} failed to checkout");
      
  2. Performance Monitoring:

    • Transactions: Wrap routes or logic in transactions:
      use function Sentry\startTransaction;
      
      $transaction = startTransaction('checkout.process', 'checkout');
      try {
          // Business logic
      } finally {
          $transaction->finish();
      }
      
    • Middleware: Use SentryTransactionMiddleware for automatic route transactions:
      // In app/Http/Kernel.php
      protected $middlewareGroups = [
          'web' => [
              // ...
              \Sentry\Laravel\Middleware\SentryTransactionMiddleware::class,
          ],
      ];
      
  3. Structured Logging:

    • Configure sentry_logs channel in config/logging.php:
      'sentry_logs' => [
          'driver' => 'sentry_logs',
          'level' => env('SENTRY_LOG_LEVEL', 'info'),
      ],
      
    • Log with context:
      \Log::info('Order processed', [
          'order_id' => $order->id,
          'user_id' => auth()->id(),
      ]);
      
  4. User Context:

    • Auto-populate user data from Laravel’s auth:
      // In AppServiceProvider boot()
      \Sentry\configureScope(function (\Sentry\State\Scope $scope) {
          $scope->setUser([
              'id' => auth()->id(),
              'email' => auth()->user()->email,
          ]);
      });
      
  5. Custom Integrations:

    • Database Queries: Enable via config/sentry.php:
      'integrations' => [
          \Sentry\Laravel\Integration\Database::class,
      ],
      
    • Cache: Auto-instrument cache spans (enabled by default).
  6. Feature Flags:

    • Pennant integration (Laravel 12+):
      // Flags are automatically attached to events/spans
      if (feature('new_ui')->isEnabled()) {
          // ...
      }
      

Advanced Patterns

  • Sampling: Control trace sampling per route/job:
    // For jobs
    \Sentry\Laravel\Middleware\SentryTracesSampleRate::class => ['rate' => 0.1],
    
  • Metrics: Track custom metrics:
    \Sentry\trace_metrics()->gauge('api_latency', $durationMs, [], \Sentry\Unit::millisecond());
    
  • OTLP Integration: Export traces to OpenTelemetry:
    'integrations' => [
        \Sentry\Laravel\Integration\OTLPIntegration::class,
    ],
    

Gotchas and Tips

Common Pitfalls

  1. DSN Configuration:

    • Gotcha: Forgetting to set SENTRY_LARAVEL_DSN in .env or using a private DSN in production.
    • Fix: Use php artisan sentry:publish and verify the DSN in .env.
  2. Performance Overhead:

    • Gotcha: Enabling tracing without sampling (SENTRY_TRACES_SAMPLE_RATE < 1.0) can bloat your Sentry quota.
    • Fix: Start with 0.1 (10% sampling) and adjust based on volume.
  3. Structured Logging:

    • Gotcha: Logs won’t appear in Sentry if SENTRY_ENABLE_LOGS is missing or LOG_CHANNEL isn’t set to stack with sentry_logs.
    • Fix:
      LOG_CHANNEL=stack
      LOG_STACK=single,sentry_logs
      SENTRY_ENABLE_LOGS=true
      
  4. User Context:

    • Gotcha: Non-string email fields (e.g., Carbon instances) may break Sentry’s user scope.
    • Fix: Cast values explicitly:
      $scope->setUser([
          'email' => (string) auth()->user()->email,
      ]);
      
  5. Cache Instrumentation:

    • Gotcha: Recursive loops in session key detection (fixed in v4.25.1).
    • Fix: Update to the latest version if using Laravel’s session cache.
  6. Transactions in Octane:

    • Gotcha: Transaction names may persist between Octane requests.
    • Fix: Updated in v4.22.0; ensure you’re on the latest version.
  7. Environment Variables:

    • Gotcha: SENTRY_LOGS_LEVEL is deprecated; use SENTRY_LOG_LEVEL.
    • Fix: Update .env and config to use the new variable.

Debugging Tips

  • Verify SDK Initialization:
    if (!\Sentry\getClient()) {
        throw new \RuntimeException("Sentry client not initialized!");
    }
    
  • Check Breadcrumbs: Enable debug breadcrumbs to trace execution flow:
    \Sentry\configureScope(function (\Sentry\State\Scope $scope) {
        $scope->setDebug(true);
    });
    
  • Log Flushing:
    • Issue: Logs not appearing? Ensure log_flush_threshold is set (default: 50).
    • Fix: Adjust in config/sentry.php or set SENTRY_LOG_FLUSH_THRESHOLD=10.

Extension Points

  1. Custom Integrations:

    • Extend \Sentry\Integration to add custom instrumentation (e.g., for third-party services).
    • Example:
      class MyServiceIntegration extends \Sentry\Integration
      {
          public function __construct() {
              $this->name = 'my-service';
          }
      
          public function setupOnce(): void {
              // Hook into Laravel events or services
          }
      }
      
    • Register in config/sentry.php:
      'integrations' => [
          \App\Integrations\MyServiceIntegration::class,
      ],
      
  2. Scope Modifiers:

    • Override user/context data dynamically:
      \Sentry\configureScope(function (\Sentry\State\Scope $scope) {
          $scope->setTag('custom_tag', 'value');
          $scope->setExtra('dynamic_data', ['key' => 'value']);
      });
      
  3. Before/After Hooks:

    • Use Sentry\beforeCapture and Sentry\afterCapture to modify events:
      \Sentry\beforeCapture(function (\Sentry\Event $event) {
          $event->setLevel(\Sentry\Severity::warning());
      });
      
  4. Testing:

    • Mock Sentry in tests:
      \Sentry\init(['dsn' => '___MOCK_DSN___']);
      \Sentry\setCaptureExceptionCallback(function () {
          // Custom logic for tests
      });
      

Configuration Quirks

  • Tracing Sample Rate:

    • Set globally in .env:
      SENTRY_TRACES_SAMPLE_RATE=0.5
      
    • Override per route/job via middleware:
      \Sentry\Laravel\Middleware\SentryTracesSampleRate::class => ['rate' => 0.2],
      
  • Strict Trace Continuation:

    • Enable to validate trace continuity:
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope