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

Request Id Bundle Laravel Package

chrisguitarguy/request-id-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require chrisguitarguy/request-id-bundle
    

    Add the bundle to config/bundles.php (Symfony 4+):

    return [
        // ...
        Chrisguitarguy\RequestId\ChrisguitarguyRequestIdBundle::class => ['all' => true],
    ];
    
  2. Basic Usage Inject the RequestId service into a controller or service:

    use Chrisguitarguy\RequestId\RequestId;
    
    public function someAction(RequestId $requestId)
    {
        $id = $requestId->getId(); // Get current request ID
        return new Response("Request ID: {$id}");
    }
    
  3. First Use Case Log the request ID in exceptions or user-facing errors:

    try {
        // Risky operation
    } catch (\Exception $e) {
        \Log::error("Error in request {$requestId->getId()}: " . $e->getMessage());
        return new Response("Error occurred. Request ID: {$requestId->getId()}");
    }
    

Implementation Patterns

Core Workflows

  1. Request ID Propagation

    • Use the RequestId service to fetch the ID in any context (controllers, services, listeners):
      public function logEvent(RequestId $requestId, EventDispatcherInterface $dispatcher)
      {
          $dispatcher->dispatch(new LogEvent($requestId->getId()));
      }
      
    • Automatically included in responses via the Request-Id header (configurable).
  2. Custom Header Handling Override default headers in config/packages/chrisguitarguy_request_id.yaml:

    chrisguitarguy_request_id:
        request_header: 'X-Request-ID'  # Incoming header
        response_header: 'X-Request-ID' # Outgoing header
        trust_request_header: false     # Generate ID regardless of header
    
  3. Middleware Integration Extend the bundle’s middleware to add logic (e.g., validate IDs):

    use Chrisguitarguy\RequestId\EventListener\RequestIdSubscriber;
    
    class CustomRequestIdSubscriber extends RequestIdSubscriber
    {
        public function onKernelRequest(GetResponseForExceptionEvent $event)
        {
            $requestId = $this->requestId->getId();
            if (!preg_match('/^[a-f0-9]{8,}$/', $requestId)) {
                throw new \RuntimeException("Invalid request ID format");
            }
        }
    }
    

    Register in config/services.yaml:

    services:
        App\EventListener\CustomRequestIdSubscriber:
            tags:
                - { name: kernel.event_subscriber }
    
  4. Logging and Monitoring Use the ID in Monolog handlers or APM tools (e.g., New Relic, Sentry):

    $logger->info("User action", [
        'request_id' => $requestId->getId(),
        'user_id' => $user->id,
    ]);
    

Gotchas and Tips

Pitfalls

  1. Header Trust Misconfiguration

    • If trust_request_header: true, malicious users could inject IDs (e.g., for log poisoning).
    • Fix: Set trust_request_header: false in production unless IDs are validated server-side.
  2. ID Generation Collisions

    • Default UUID generation is low-collision, but custom generators (e.g., sequential) may clash.
    • Tip: Use Ramsey\Uuid\Uuid for high-cardinality IDs if extending the generator.
  3. Symfony 5+ Kernel Changes

    • The bundle assumes AppKernel. For Symfony 5+, ensure the bundle is listed in config/bundles.php before FrameworkBundle to avoid autowiring conflicts.
  4. Response Header Overrides

    • Some frameworks (e.g., API Platform) may override response headers. Explicitly set the header in your response:
      $response->headers->set('X-Request-ID', $requestId->getId());
      

Debugging

  • Missing IDs in Logs: Ensure the RequestId service is injected into your logger or listener. For Monolog, use a processor:

    $processor = new \Monolog\Processor\PsrLogMessageProcessor();
    $processor->__invoke(['request_id' => $requestId->getId()]);
    
  • ID Not in Response: Verify the response_header config matches the header name in your logs/monitoring tools.

Extension Points

  1. Custom ID Generators Implement Chrisguitarguy\RequestId\Generator\RequestIdGeneratorInterface:

    class CustomIdGenerator implements RequestIdGeneratorInterface
    {
        public function generate(): string
        {
            return bin2hex(random_bytes(8)); // 16-char hex
        }
    }
    

    Register in config/services.yaml:

    services:
        Chrisguitarguy\RequestId\Generator\RequestIdGeneratorInterface: '@App\Generator\CustomIdGenerator'
    
  2. Event-Based Extensions Listen to chrisguitarguy.request_id.generated to modify IDs dynamically:

    use Chrisguitarguy\RequestId\Event\RequestIdGeneratedEvent;
    
    $eventDispatcher->addListener(RequestIdGeneratedEvent::class, function (RequestIdGeneratedEvent $event) {
        $event->setId(strtoupper($event->getId())); // Example: Force uppercase
    });
    
  3. Database Storage Store IDs in sessions or databases for traceability:

    $session->set('request_id', $requestId->getId());
    // Later:
    $requestId = $session->get('request_id');
    
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
andydefer/laravel-cluster
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