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

Symfony Trace Bundle Laravel Package

digitalrevolution/symfony-trace-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require digitalrevolution/symfony-trace-bundle
    

    Add to config/bundles.php:

    DR\SymfonyTraceBundle\SymfonyTraceBundle::class => ['all' => true],
    
  2. First Use Case: Inject the TraceContext service into a controller or service:

    use DR\SymfonyTraceBundle\Trace\TraceContext;
    
    public function __construct(private TraceContext $traceContext) {}
    
    public function someAction(): Response
    {
        $traceId = $this->traceContext->getTraceId();
        // Log or use the traceId (e.g., in Monolog)
        return new Response("Trace ID: {$traceId}");
    }
    
  3. Verify in Logs: Ensure Monolog logs now include the trace_id metadata. Check your log handler configuration (e.g., monolog.yaml):

    handlers:
        main:
            type: stream
            path: "%kernel.logs_dir%/%kernel.environment%.log"
            channels: ["!event"]
            process_psr_3_messages: true  # Required for trace_id inclusion
    

Implementation Patterns

Core Workflows

  1. Request-Response Propagation:

    • The bundle auto-injects trace_id into HTTP headers (traceparent for W3C compliance).
    • Access via RequestStack or TraceContext:
      $request = $this->requestStack->getCurrentRequest();
      $traceId = $request->headers->get('X-Trace-Id');
      
  2. Console Commands:

    • Generate trace IDs for CLI workflows:
      use DR\SymfonyTraceBundle\Trace\TraceContext;
      
      public function __construct(private TraceContext $traceContext) {}
      
      public function execute(Command $command): int
      {
          $traceId = $this->traceContext->getTraceId();
          $this->logger->info("Command executed with trace_id: {$traceId}");
          return Command::SUCCESS;
      }
      
  3. Twig Integration:

    • Expose trace ID in templates:
      {{ app.trace_id }}
      
    • Register the Twig extension in services.yaml:
      DR\SymfonyTraceBundle\Twig\TraceExtension:
          tags: ['twig.extension']
      
  4. Messenger Integration:

    • Enable trace propagation for messages:
      # config/packages/messenger.yaml
      framework:
          messenger:
              transports:
                  async: '%env(MESSENGER_TRANSPORT_DSN)%'
              routing:
                  'App\Message\YourMessage': async
              defaults:
                  trace_id: true  # Auto-propagate trace_id
      
  5. HttpClient:

    • Tag clients to auto-propagate trace IDs:
      $client = \Symfony\Contracts\HttpClient\HttpClient::create([
          'trace_id' => true, // Auto-inject trace_id
      ]);
      

Integration Tips

  • Sentry: Enable trace ID in error reports by configuring the Sentry handler:
    # config/packages/monolog.yaml
    handlers:
        sentry:
            type: sentry
            level: error
            trace_id: true  # Include trace_id in reports
    
  • Database Logging: Use trace_id in query logging (e.g., Doctrine):
    $this->logger->info("Query executed", ['trace_id' => $traceId, 'query' => $sql]);
    

Gotchas and Tips

Pitfalls

  1. Header Conflicts:

    • Avoid manually setting traceparent headers if using W3C compliance, as the bundle auto-generates them.
    • Debug: Check Request::headers for duplicates.
  2. Monolog Configuration:

    • Missing process_psr_3_messages: Logs won’t include trace_id unless enabled in handlers.
    • Channel Filtering: Ensure logs are routed to handlers that support PSR-3 (e.g., stream with process_psr_3_messages: true).
  3. Console Trace IDs:

    • CLI trace IDs are not propagated via HTTP by default. Use TraceContext::generateTraceId() for isolated CLI workflows:
      $traceId = $this->traceContext->generateTraceId();
      
  4. HttpClient Tagging:

    • Default Behavior: Only tagged clients propagate trace IDs. Explicitly tag clients:
      $client = \Symfony\Contracts\HttpClient\HttpClient::create([
          'trace_id' => true,
      ]);
      
  5. Messenger Transport:

    • Async Transports: Ensure trace_id is enabled in messenger.yaml for async buses:
      defaults:
          trace_id: true
      

Debugging

  • Trace ID Not Showing?:
    • Verify TraceContext is injected correctly (use dump($traceContext->getTraceId())).
    • Check for middleware conflicts (e.g., custom RequestIdBundle).
    • Enable debug logs:
      # config/packages/dev/monolog.yaml
      handlers:
          main:
              level: debug
      

Extension Points

  1. Custom Trace ID Generation:

    • Override the default generator (e.g., UUIDv7 for timestamps):
      // config/services.yaml
      DR\SymfonyTraceBundle\Trace\TraceContext:
          arguments:
              $traceIdGenerator: '@app.custom_trace_generator'
      
    • Implement DR\SymfonyTraceBundle\Trace\TraceIdGeneratorInterface.
  2. Header Customization:

    • Modify headers via event listeners (e.g., kernel.request):
      public function onKernelRequest(RequestEvent $event): void
      {
          $event->getRequest()->headers->set('X-Custom-Trace', $this->traceContext->getTraceId());
      }
      
  3. Log Formatter:

    • Extend Monolog’s Processor to include trace_id in custom formats:
      use Monolog\Processor\ProcessorInterface;
      
      class TraceIdProcessor implements ProcessorInterface
      {
          public function __invoke(array $record): array
          {
              $record['extra']['trace_id'] = $this->traceContext->getTraceId();
              return $record;
          }
      }
      
      Register in monolog.yaml:
      processors:
          trace_id: ['@app.trace_id_processor']
      
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