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

sentry/sentry-symfony

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require sentry/sentry-symfony
    

    Add to .env:

    ###> sentry/sentry-symfony ###
    SENTRY_DSN="https://<key>@<project>.ingest.sentry.io/<id>"
    ###< sentry/sentry-symfony ###
    
  2. First Use Case: Capture an exception in a controller:

    use function Sentry\captureException;
    
    try {
        $result = $this->riskyOperation();
    } catch (\Throwable $e) {
        captureException($e);
        throw $e; // Re-throw if needed
    }
    
  3. Auto-Instrumentation: The bundle automatically captures:

    • HTTP requests (status, headers, body)
    • Database queries (Doctrine, DBAL)
    • Cache operations (Symfony Cache)
    • CLI commands (exit codes, arguments)

Where to Look First

  • Configuration: config/packages/sentry.yaml (auto-generated)
  • Documentation: Sentry Symfony Docs
  • Key Classes:
    • Sentry\SentryBundle\SentryBundle (main bundle)
    • Sentry\SentryBundle\EventListener\ExceptionListener (exception handling)
    • Sentry\SentryBundle\EventListener\RequestListener (HTTP instrumentation)

Implementation Patterns

Core Workflows

1. Exception Handling

// Manual capture (recommended for business logic errors)
use function Sentry\captureException;
use function Sentry\captureMessage;

try {
    $user = User::findOrFail($id);
} catch (\InvalidArgumentException $e) {
    captureMessage('Invalid user ID format', ['user_id' => $id]);
    throw $e;
}

// Auto-capture (for framework exceptions)
public function __invoke(Request $request, $id)
{
    // No try-catch needed; exceptions bubble up to Sentry
    return $this->userService->get($id);
}

2. Transaction Tracing

use function Sentry\trace;

trace('user.profile', function () use ($userId) {
    $user = User::find($userId);
    $orders = $user->orders()->limit(10)->get();
    return ['user' => $user, 'orders' => $orders];
});

3. Metrics Collection

use function Sentry\trace_metrics;

trace_metrics()->count('api.calls', 1, ['endpoint' => 'users']);
trace_metrics()->gauge('queue.size', $queue->count(), ['queue' => 'orders']);
trace_metrics()->distribution('response.time', $durationMs, ['unit' => 'ms']);

4. Structured Logging

# config/packages/monolog.yaml
monolog:
    handlers:
        sentry:
            type: service
            id: Sentry\SentryBundle\Monolog\LogsHandler
            arguments:
                - !php/const Monolog\Logger::DEBUG
$this->logger->info('User logged in', [
    'user_id' => $user->id,
    'ip' => $request->getClientIp(),
    'metadata' => ['device' => $deviceType]
]);

Integration Patterns

Doctrine DBAL

# config/packages/sentry.yaml
sentry:
    options:
        integrations:
            - Sentry\Integration\Doctrine\DoctrineIntegration

Symfony Messenger

sentry:
    messenger:
        isolate_context_by_message: true  # Prevents scope leakage

Custom Integrations

services:
    App\Sentry\CustomIntegration:
        tags: ['sentry.integration']

sentry:
    options:
        integrations: ['App\Sentry\CustomIntegration']

Middleware for API Requests

use Sentry\State\Scope;

public function __invoke(Request $request, Response $response, callable $next): Response
{
    $scope = Scope::getCurrentScope();
    $scope->setTag('api_version', $request->headers->get('X-API-Version'));

    return $next($request, $response);
}

Configuration Patterns

Environment-Specific DSN

# config/packages/sentry.yaml
sentry:
    dsn: "%env(SENTRY_DSN)%"
    options:
        traces_sample_rate: "%env(float::SENTRY_TRACES_SAMPLE_RATE)%"

Conditional Instrumentation

sentry:
    options:
        integrations:
            %kernel.debug% ? [] : ['Sentry\Integration\Doctrine\DoctrineIntegration']

Custom Error Ignoring

sentry:
    options:
        ignore_exceptions:
            - Symfony\Component\HttpKernel\Exception\HttpExceptionInterface
            - App\Exception\ValidationException

Gotchas and Tips

Common Pitfalls

  1. DSN Validation:

    • Gotcha: Forgetting to set SENTRY_DSN in .env causes silent failures.
    • Fix: Use SENTRY_DSN="https://invalid@localhost" in dev to test error handling.
  2. Performance Overhead:

    • Gotcha: Tracing every request in high-traffic apps can slow down responses.
    • Fix: Adjust traces_sample_rate (default: 1.0):
      sentry:
          options:
              traces_sample_rate: 0.1  # 10% sampling
      
  3. Sensitive Data in Errors:

    • Gotcha: Accidentally sending passwords or tokens in error payloads.
    • Fix: Use before_send callback to scrub data:
      Sentry\configureScope(function (Scope $scope) {
          $scope->setBeforeSendCallback(function ($event) {
              unset($event['extra']['password']);
              return $event;
          });
      });
      
  4. Messenger Context Leakage:

    • Gotcha: Breadcrumbs/logs from one message appearing in another.
    • Fix: Enable isolation:
      sentry:
          messenger:
              isolate_context_by_message: true
      
  5. Cache Instrumentation:

    • Gotcha: NamespacedPoolInterface caches breaking instrumentation.
    • Fix: Use TraceableCacheAdapterForV3 (v5.3+):
      $cache = new TraceableCacheAdapterForV3($pool);
      

Debugging Tips

  1. Local Testing:

    • Use SENTRY_DSN="http://localhost:3000" with Sentry Mock Server.
    • Enable debug logs:
      sentry:
          options:
              logger: 'sentry.logger'
      services:
          sentry.logger:
              class: 'Sentry\Logger\DebugFileLogger'
              arguments:
                  $filePath: '%kernel.logs_dir%/sentry.log'
      
  2. Event Inspection:

    • Capture events to a file for debugging:
      Sentry\configureScope(function (Scope $scope) {
          $scope->setBeforeSendCallback(function ($event) {
              file_put_contents(
                  __DIR__.'/sentry_event.json',
                  json_encode($event, JSON_PRETTY_PRINT)
              );
              return null; // Prevent sending
          });
      });
      
  3. Performance Profiling:

    • Check sentry-performance metrics in Sentry dashboard.
    • Use X-Sentry-Trace header to correlate requests:
      $scope->setTag('sentry.trace_id', $request->headers->get('X-Sentry-Trace'));
      

Configuration Quirks

  1. max_breadcrumbs:

    • Default: 100 (no upper limit in v5.6+).
    • Tip: Increase for long-running processes:
      sentry:
          options:
              max_breadcrumbs: 500
      
  2. ignore_errors vs ignore_exceptions:

    • ignore_errors: Catches set_error_handler errors (legacy).
    • ignore_exceptions: Uses is_a() for type matching (recommended).
  3. Monolog Levels:

    • Accepts strings ('info'), PSR constants (Psr\Log\LogLevel::INFO), or Monolog constants (Monolog\Level::INFO).
  4. OTLP Integration:

    • Requires sentry-php v4.23+:
      sentry:
          options:
              integrations:
                  - Sentry\Integration\OTLPIntegration
      

Extension Points

  1. Custom Integrations:
    • Implement Sentry\IntegrationInterface:
      class MyIntegration implements IntegrationInterface {
          public function setupOnce(): void {
              // One-time setup (e.g., register error handler)
          }
      
          public function setup(): void {
              // Per-request setup (e.g., add breadcrumbs
      
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle