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

Tracing Bundle Laravel Package

amashukov/tracing-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require amashukov/tracing-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        AndreyMashukov\TracingBundle\TracingBundle::class => ['all' => true],
    ];
    
  2. Verify Request ID Generation Trigger an HTTP request (e.g., via browser or curl):

    curl -v http://your-app.test
    

    Check the X-Request-Id header in the response and Monolog logs (var/log/dev.log).

  3. First Use Case: Debugging a Request Flow

    • A user reports an issue. Locate the request_id in logs (e.g., extra.request_id).
    • Correlate logs across HTTP, queue (Messenger), and workers using the same ID.

Implementation Patterns

Core Workflow: End-to-End Tracing

  1. HTTP Layer

    • Bundle auto-generates a UUIDv7 X-Request-Id for incoming requests.
    • Inject the RequestId service into controllers/services:
      use AndreyMashukov\TracingBundle\Service\RequestId;
      
      public function __construct(private RequestId $requestId) {}
      
      public function index(): Response
      {
          $requestId = $this->requestId->get(); // e.g., "018a0b..."
          return new Response("Request ID: {$requestId}");
      }
      
  2. Messenger Bridge

    • Sync Handlers: Automatically inherit the request_id from the HTTP context.
    • Async Handlers: Use the RequestIdMiddleware to propagate the ID to queue workers:
      use AndreyMashukov\TracingBundle\Middleware\RequestIdMiddleware;
      
      $bus->addMiddleware(
          new RequestIdMiddleware($requestIdService)
      );
      
    • Dispatch a message:
      $this->bus->dispatch(new YourMessage());
      
  3. Monolog Integration

    • Logs are stamped with extra.request_id automatically. Customize via monolog.yaml:
      handlers:
          main:
              processor: AndreyMashukov\TracingBundle\Processor\RequestIdProcessor
      

Advanced Patterns

  • Custom ID Generation Override the default UUIDv7 generator by binding your own service to AndreyMashukov\TracingBundle\Generator\RequestIdGeneratorInterface.

  • Contextual Logging Attach additional context to logs (e.g., user ID) while preserving the request_id:

    $this->logger->info('Event triggered', [
        'request_id' => $this->requestId->get(),
        'user_id'    => $user->id,
    ]);
    
  • Testing Mock the RequestId service in tests:

    $this->requestId->shouldReceive('get')->andReturn('test-123');
    

Gotchas and Tips

Pitfalls

  1. Missing Headers in Async Workers

    • Issue: Workers may log without request_id if RequestIdMiddleware isn’t configured.
    • Fix: Ensure the middleware is added before your handler middleware in the bus:
      $bus->addMiddleware(new RequestIdMiddleware($requestIdService), 'before' => 'your_handler');
      
  2. UUIDv7 Collisions

    • Risk: UUIDv7 is time-sorted but not globally unique. For distributed systems, combine with a machine ID or use a custom generator.
    • Workaround: Extend the generator to include a process ID:
      class CustomRequestIdGenerator implements RequestIdGeneratorInterface
      {
          public function generate(): string
          {
              return sprintf(
                  '%s-%d',
                  (new \Ramsey\Uuid\Uuid())->uuid7()->toString(),
                  getmypid()
              );
          }
      }
      
  3. Log Processor Conflicts

    • Issue: If another Monolog processor modifies extra, it may overwrite request_id.
    • Fix: Ensure the RequestIdProcessor runs last in the processor chain.
  4. Symfony Messenger Version Mismatch

    • Issue: The bundle assumes Symfony Messenger’s MessageBusInterface. Older versions may need adapter shims.
    • Check: Verify compatibility in composer.json or wrap the middleware in a version check.

Debugging Tips

  • Validate Request ID Propagation Add a debug endpoint to verify the ID flows through all layers:

    public function debug(RequestId $requestId): Response
    {
        return $this->json([
            'request_id' => $requestId->get(),
            'monolog_extra' => $this->logger->getHandlers()[0]->getProcessor()?->__invoke([])['extra'] ?? [],
        ]);
    }
    
  • Log Correlation Use a log viewer (e.g., ELK, Papertrail) with a query for extra.request_id to trace a request’s lifecycle.

Extension Points

  1. Custom Headers Extend the RequestId service to support additional headers (e.g., X-Correlation-Id):

    $this->requestId->setHeaderName('X-Correlation-Id');
    
  2. Database Tracing Bind the request_id to database queries via Doctrine listeners:

    $conn->getConfiguration()->addListener(new RequestIdListener($requestIdService));
    
  3. OpenTelemetry Integration Export the request_id to OpenTelemetry traces for distributed tracing:

    $traceContext = new TraceContext([
        'request_id' => $this->requestId->get(),
    ]);
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
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