chrisguitarguy/request-id-bundle
Installation
composer require chrisguitarguy/request-id-bundle
Add the bundle to config/bundles.php (Symfony 4+):
return [
// ...
Chrisguitarguy\RequestId\ChrisguitarguyRequestIdBundle::class => ['all' => true],
];
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}");
}
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()}");
}
Request ID Propagation
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()));
}
Request-Id header (configurable).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
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 }
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,
]);
Header Trust Misconfiguration
trust_request_header: true, malicious users could inject IDs (e.g., for log poisoning).trust_request_header: false in production unless IDs are validated server-side.ID Generation Collisions
Ramsey\Uuid\Uuid for high-cardinality IDs if extending the generator.Symfony 5+ Kernel Changes
AppKernel. For Symfony 5+, ensure the bundle is listed in config/bundles.php before FrameworkBundle to avoid autowiring conflicts.Response Header Overrides
$response->headers->set('X-Request-ID', $requestId->getId());
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.
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'
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
});
Database Storage Store IDs in sessions or databases for traceability:
$session->set('request_id', $requestId->getId());
// Later:
$requestId = $session->get('request_id');
How can I help you explore Laravel packages today?