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 Enhanced Tracing Laravel Package

amarc-sudo/sentry-enhanced-tracing

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require amarc-sudo/sentry-enhanced-tracing lexik/jwt-authentication-bundle
    

    Add to config/bundles.php:

    AmarcSudo\SentryEnhancedTracing\SentryEnhancedTracingBundle::class => ['all' => true],
    Lexik\Bundle\JWTAuthenticationBundle\LexikJWTAuthenticationBundle::class => ['all' => true],
    
  2. Configure Sentry in config/packages/sentry.yaml:

    sentry:
        dsn: '%env(SENTRY_DSN)%'
        options:
            traces_sample_rate: 1.0
            profiles_sample_rate: 1.0
    
  3. First Use Case: Call any API endpoint or trigger a Symfony event. Check Sentry for:

    • Automatic hierarchical spans (e.g., kernel.request, kernel.controller)
    • Nested database/cache/template operations under event phases
    • Enhanced user context (if using JWT auth)

Implementation Patterns

Core Workflows

  1. Automatic Span Capture:

    • Database: Wrap Doctrine DBAL queries in spans under the current event phase.
    • Cache: Trace Redis/APCu operations as child spans.
    • Templates: Measure Twig rendering time.
    • HTTP Clients: Monitor outgoing requests.
    • Example:
      // No manual code needed—spans auto-capture via listeners.
      $user = $em->getRepository(User::class)->find($id); // Auto-traced DB query
      
  2. Event Phase Tracking:

    • Listen to Symfony kernel events (kernel.request, kernel.controller, etc.).
    • Create spans for each phase with execution metrics.
    • Customize tracked events in config/packages/sentry_enhanced_tracing.yaml:
      sentry_enhanced_tracing:
          tracked_events:
              - 'kernel.request'
              - 'kernel.controller'
      
  3. User Context Enrichment:

    • Implement EnhancedUserInterface for richer user data:
      class User implements EnhancedUserInterface {
          public function getEnhancedFirstname(): ?string { return $this->firstname; }
          // ... other methods
      }
      
    • Auto-captures JWT user context via lexik_jwt_authentication.on_jwt_authenticated.
  4. Messenger Queue Monitoring:

    • Producer: Auto-creates queue.publish spans.
    • Consumer: Starts queue.process transactions.
    • Propagate traces/baggage via SentryTraceStamp:
      # config/services.yaml
      parameters:
          sentry_enhanced_tracing.messenger.propagate_user: true
      
  5. Performance Thresholds:

    • Categorize spans as fast/slow based on custom thresholds:
      sentry_enhanced_tracing:
          performance_thresholds:
              kernel.controller: 0.1  # 100ms threshold
      

Integration Tips

  • Debugging: Use Sentry\Tracing\Span methods like setData() to add custom metadata:
    $span->setData(['custom_key', 'value']);
    
  • Sampling: Reduce traces_sample_rate in production (e.g., 0.1).
  • Exclusions: Filter out noisy spans by overriding listener priorities:
    # config/packages/sentry_enhanced_tracing.yaml
    sentry_enhanced_tracing:
        excluded_spans:
            - 'db.query:SELECT * FROM logs'
    

Gotchas and Tips

Pitfalls

  1. Missing Spans:

    • Cause: traces_sample_rate set to 0 or Sentry DSN misconfigured.
    • Fix: Verify sentry.yaml and check Sentry dashboard for transactions.
  2. Performance Overhead:

    • Cause: High traces_sample_rate (e.g., 1.0) in production.
    • Fix: Use sampling (0.1) and monitor with Sentry\PerformanceMonitor.
  3. Broken Hierarchy:

    • Cause: Conflicting Sentry listeners or manual span creation.
    • Fix: Ensure no other packages override Sentry\State\HubInterface.
  4. JWT User Context Missing:

    • Cause: LexikJWTAuthenticationBundle not installed or misconfigured.
    • Fix: Verify JWT auth events fire and user data is populated.
  5. Messenger Traces Not Linked:

    • Cause: SentryTraceStamp not propagated between producer/consumer.
    • Fix: Ensure propagate_user is true and SentryTraceStamp is attached to messages.

Debugging Tips

  • Log Listener Execution: Add debug logs to SentryListenerPhasesTracer to verify event phases:

    $this->logger->debug('Tracking event phase: ' . $eventName);
    
  • Check Span Hierarchy: Use Sentry’s "Transaction Details" to inspect nested spans. Look for:

    • Parent spans (e.g., kernel.controller) with child spans (e.g., db.query).
    • Missing spans may indicate integration gaps (e.g., custom Doctrine types).
  • Override Default Behavior: Extend the bundle’s services to customize span creation:

    # config/services.yaml
    services:
        AmarcSudo\SentryEnhancedTracing\Listener\SentryListenerPhasesTracer:
            arguments:
                $customSpanFactory: '@app.custom.span_factory'
    

Extension Points

  1. Custom Span Factories: Create a service to modify span creation logic:

    class CustomSpanFactory implements SpanFactoryInterface {
        public function createSpan(string $name, ?Span $parent = null): Span {
            $span = parent::createSpan($name, $parent);
            $span->setData(['custom_metadata', 'value']);
            return $span;
        }
    }
    
  2. Event Phase Extensions: Add new event phases by extending SentryListenerPhasesTracer:

    class CustomPhaseTracer extends SentryListenerPhasesTracer {
        protected function getTrackedEvents(): array {
            return array_merge(parent::getTrackedEvents(), ['custom.event']);
        }
    }
    
  3. Messenger Integration: Extend SentryMessengerListener to add custom metadata:

    class CustomMessengerListener extends SentryMessengerListener {
        public function handle(DispatcherInterface $dispatcher, callable $next, Envelope $envelope): Envelope {
            $envelope = parent::handle($dispatcher, $next, $envelope);
            $this->addCustomMetadata($envelope);
            return $envelope;
        }
    }
    

Configuration Quirks

  • Zero-Config Mode: The bundle works out-of-the-box, but explicit config (e.g., tracked_events) may be needed for edge cases.
  • Priority Conflicts: Ensure the bundle’s listeners run before other Sentry listeners (priority 99999 by default).
  • PII Handling: Disable capture_email in user_context if handling sensitive data:
    sentry_enhanced_tracing:
        user_context:
            capture_email: false
    

Performance Optimization

  • Disable in High-Traffic Endpoints: Use a feature flag or environment check to skip tracing:
    if (!$this->isTracingEnabled()) {
        return;
    }
    
  • Breadcrumb Limits: Adjust max_breadcrumbs in Sentry config to reduce payload size:
    sentry:
        options:
            max_breadcrumbs: 50
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor