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 capture and report unhandled exceptions and performance data to Sentry, with seamless Laravel integration and configuration. Supports modern Laravel versions and includes tooling for monitoring errors in production.

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 in bootstrap/app.php:

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

    use function Sentry\captureException;
    
    try {
        $user = User::findOrFail($id);
    } catch (\Throwable $e) {
        captureException($e);
    }
    

Key First Steps

  • Verify Sentry events appear in your dashboard.
  • Check .env for SENTRY_LARAVEL_DSN and APP_ENV=production (or equivalent).
  • For Laravel 11/12, ensure Integration::handles() is in bootstrap/app.php.

Implementation Patterns

Core Workflows

  1. Exception Handling:

    • Unhandled Exceptions: Automatically captured via Integration::handles().
    • Manual Capture:
      try { ... } catch (\Throwable $e) {
          captureException($e, [
              'user' => auth()->user(),
              'context' => ['key' => 'value']
          ]);
      }
      
    • Logging Exceptions:
      Log::channel('sentry')->error('Failed to process', ['data' => $data]);
      
  2. Performance Monitoring:

    • Transactions:
      use function Sentry\startTransaction;
      
      $transaction = startTransaction('user.profile', 'task');
      try {
          $user = User::find($id);
          $transaction->setStatus('ok');
      } finally {
          $transaction->finish();
      }
      
    • Spans:
      use function Sentry\startSpan;
      
      $span = startSpan('database.query');
      DB::query(...);
      $span->finish();
      
  3. Logging:

    • Structured Logs (Laravel 11+):
      Log::channel('sentry_logs')->info('User {id} logged in', ['id' => $user->id]);
      
    • Auto-Configuration: Set in .env:
      LOG_CHANNEL=stack
      LOG_STACK=single,sentry_logs
      SENTRY_ENABLE_LOGS=true
      
  4. Middleware Integration:

    • Job Sampling:
      use Sentry\Laravel\Middleware\SentryTracesSampleRate;
      
      protected $middleware = [
          SentryTracesSampleRate::class,
      ];
      
  5. User Context:

    • Auto-injected via Sentry\Laravel\Integration:
      // Manually override:
      Sentry\configureScope(function ($scope) {
          $scope->setUser(['id' => 123, 'email' => 'user@example.com']);
      });
      

Integration Tips

  • Laravel Octane: Reset transaction names between requests:
    Sentry\resetTransactionName();
    
  • Feature Flags: Auto-capture Pennant flags (Laravel 12+):
    // Flags are automatically attached to events/spans.
    
  • Metrics:
    Sentry\trace_metrics()->count('api.calls', 1, ['endpoint' => 'users']);
    Sentry\trace_metrics()->gauge('memory.usage', memory_get_usage(), \Sentry\Unit::byte());
    

Gotchas and Tips

Pitfalls

  1. DSN Configuration:

    • Gotcha: Forgetting to set APP_ENV=production may send events to a staging DSN.
    • Fix: Use SENTRY_LARAVEL_DSN environment variable and validate in .env.example.
  2. Transaction Naming:

    • Gotcha: Octane resets transaction names between requests. If not handled, spans may appear misaligned.
    • Fix: Call Sentry\resetTransactionName() in Octane middleware.
  3. Log Levels:

    • Gotcha: SENTRY_LOG_LEVEL overrides LOG_LEVEL for Sentry logs. Set explicitly in .env:
      LOG_LEVEL=debug
      SENTRY_LOG_LEVEL=warning
      
  4. User Context:

    • Gotcha: Non-string email attributes in auth()->user() may break Sentry’s user scope.
    • Fix: Cast to string in AppServiceProvider:
      Sentry\configureScope(function ($scope) {
          $user = auth()->user();
          $scope->setUser([
              'id' => $user->id,
              'email' => (string) $user->email,
          ]);
      });
      
  5. Cache Span Names:

    • Gotcha: Session keys in cache span names may cause duplicates.
    • Fix: Use placeholders (handled automatically in v4.15.2+).
  6. Structured Logs:

    • Gotcha: Forgetting to enable sentry_logs channel or set SENTRY_ENABLE_LOGS=true.
    • Fix: Add to config/logging.php and .env:
      'sentry_logs' => ['driver' => 'sentry_logs', 'level' => env('SENTRY_LOG_LEVEL')],
      
      SENTRY_ENABLE_LOGS=true
      

Debugging

  1. Events Not Appearing:

    • Check SENTRY_LARAVEL_DSN is correct and not empty.
    • Verify APP_ENV is not local (unless testing).
    • Enable debug mode in config/sentry.php:
      'debug' => env('APP_DEBUG', false),
      
  2. Performance Overhead:

    • Tip: Disable in development:
      'enabled' => env('APP_ENV') !== 'local',
      
    • Use Sentry\setTraceSampleRate(0.1) to sample 10% of transactions.
  3. Headers in Requests:

    • Gotcha: sentry-trace and baggage headers may be escaped incorrectly.
    • Fix: Updated in v4.21.0; ensure you’re on the latest version.

Extension Points

  1. Custom Integrations:

    • Extend Sentry\Laravel\Integration to add framework-specific hooks:
      use Sentry\Laravel\Integration as BaseIntegration;
      
      class CustomIntegration extends BaseIntegration {
          public function register()
          {
              $this->registerEventListeners();
              $this->registerMiddleware();
          }
      }
      
  2. Before/After Hooks:

    • Use Sentry\beforeSendEvent and Sentry\beforeSendTransaction:
      Sentry\beforeSendEvent(function ($event) {
          $event['tags']['custom'] = 'value';
          return $event;
      });
      
  3. Log Flushing:

    • Configure log_flush_threshold in config/sentry.php to auto-flush logs:
      'logs' => [
          'flush_threshold' => 50, // Flush after 50 logs
      ],
      
  4. OTLP Integration:

    • Enable OpenTelemetry (OTLP) for distributed tracing:
      'integrations' => [
          \Sentry\Integration\OTLPIntegration::class,
      ],
      

Configuration Quirks

  • Environment Variables:
    • SENTRY_LOGS_LEVEL is deprecated; use SENTRY_LOG_LEVEL.
    • SENTRY_TRACES_SAMPLE_RATE defaults to 1.0 (100% sampling).
  • Strict Trace Continuation:
    • Enable strict_trace_continuation in config/sentry.php to validate org_id in baggage headers:
      'tracing' => [
          'strict_trace_continuation' => true,
      ],
      
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport