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 Symfony Laravel Package

dbannik/sentry-symfony

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require sentry/sentry-symfony
    

    Add to config/bundles.php:

    return [
        // ...
        Sentry\Symfony\SentryBundle::class => ['all' => true],
    ];
    
  2. Configuration: Publish the default config:

    php bin/console config:dump-reference sentry
    

    Update .env with your DSN (e.g., SENTRY_DSN=https://examplePublicKey@...). Minimal config/packages/sentry.yaml:

    sentry:
        dsn: '%env(SENTRY_DSN)%'
        options:
            traces_sample_rate: 1.0
    
  3. First Use Case: Trigger an error in a controller to verify integration:

    use Symfony\Component\HttpFoundation\Response;
    
    public function testSentry(): Response
    {
        throw new \RuntimeException('Test error for Sentry');
        return new Response('This will not be reached');
    }
    

    Check Sentry.io dashboard for the captured event.


Implementation Patterns

Core Workflows

  1. Error Handling:

    • Exceptions: Automatically captured via Symfony’s ErrorListener. No manual wrapping needed.
    • Manual Events:
      use Sentry\Symfony\Facades\Sentry;
      
      Sentry\configureScope(function ($scope) {
          $scope->setTag('user', 'admin');
          $scope->setExtra('custom_data', ['key' => 'value']);
      });
      
      Sentry\captureMessage('This is a manual message');
      Sentry\captureException(new \LogicException('Custom exception'));
      
  2. Request Tracking:

    • Enable in sentry.yaml:
      sentry:
          options:
              send_default_pii: true  # For sensitive data (use cautiously)
      
    • Access request data in scopes:
      Sentry\configureScope(function ($scope) use ($request) {
          $scope->setUser([
              'id' => $request->get('user_id'),
              'email' => $request->get('email'),
          ]);
      });
      
  3. Performance Monitoring:

    • Enable traces in sentry.yaml:
      sentry:
          options:
              traces_sample_rate: 0.1  # Sample 10% of transactions
      
    • Manually start/end transactions:
      $transaction = Sentry\startTransaction('api.endpoint', 'endpoint');
      try {
          // Business logic
          $transaction->setStatus('ok');
      } catch (\Exception $e) {
          $transaction->setStatus('internal_error');
          Sentry\captureException($e);
      } finally {
          $transaction->finish();
      }
      
  4. Middleware Integration:

    • Use Sentry\Symfony\EventListener\ErrorListener to customize error handling:
      // config/services.yaml
      Sentry\Symfony\EventListener\ErrorListener:
          tags:
              - { name: kernel.event_listener, event: kernel.exception, method: onKernelException }
      

Gotchas and Tips

Pitfalls

  1. DSN Configuration:

    • Issue: Events may silently fail if SENTRY_DSN is missing or malformed.
    • Fix: Validate in .env and use SENTRY_DSN_VALIDATION=true to throw exceptions on misconfiguration.
    • Debugging: Check Symfony logs (var/log/dev.log) for transport errors.
  2. Sensitive Data:

    • Issue: Accidentally sending PII (Personally Identifiable Information) in error reports.
    • Fix: Explicitly blacklist sensitive data in sentry.yaml:
      sentry:
          options:
              before_send: [App\Service\SentryDataSanitizer]
      
      Implement before_send callback to filter data:
      public function __invoke($event) {
          unset($event['request']['_token']);
          return $event;
      }
      
  3. Performance Overhead:

    • Issue: Traces/sampled transactions may impact performance.
    • Fix: Adjust traces_sample_rate (e.g., 0.1 for 10% sampling) and avoid manual transactions in hot paths.
  4. Symfony Cache Conflicts:

    • Issue: Sentry’s HTTP client may conflict with Symfony’s cache adapter.
    • Fix: Ensure sentry.yaml uses a dedicated HTTP client:
      sentry:
          http_client:
              max_size: 100  # Adjust as needed
      

Debugging Tips

  1. Local Testing:

    • Use SENTRY_ENVIRONMENT=development to distinguish local events.
    • Enable debug mode in sentry.yaml:
      sentry:
          options:
              debug: true
      
  2. Event Inspection:

    • Dump the full event payload before sending:
      $event = Sentry\configureScope(function () {
          return Sentry\lastEventId(); // Get the last event ID
      });
      file_put_contents('sentry_event.json', json_encode($event, JSON_PRETTY_PRINT));
      
  3. Transport Issues:

    • Test connectivity manually:
      curl -X POST https://your-dsn.sentry.io/api/<project-id>/envelope/ -d @sentry_event.json
      

Extension Points

  1. Custom Integrations:

    • Extend the Sentry\State\Scope to add app-specific context:
      use Sentry\State\Scope;
      
      Sentry\configureScope(function (Scope $scope) {
          $scope->setContext('app', [
              'version' => '1.0.0',
              'user_agent' => $_SERVER['HTTP_USER_AGENT'],
          ]);
      });
      
  2. Event Filters:

    • Implement a global filter to exclude specific exceptions:
      use Sentry\Symfony\EventListener\ErrorListener;
      
      class CustomErrorListener extends ErrorListener
      {
          protected function isCapturable(\Throwable $exception): bool
          {
              return !($exception instanceof \App\Exception\IgnoredException);
          }
      }
      
      Register in services.yaml:
      App\EventListener\CustomErrorListener:
          tags:
              - { name: kernel.event_listener, event: kernel.exception, method: onKernelException }
      
  3. Breadcrumbs:

    • Add manual breadcrumbs for debugging flows:
      Sentry\addBreadcrumb([
          'category' => 'navigation',
          'message' => 'User clicked "Submit"',
          'level' => 'info',
      ]);
      
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui