PHP code example of scau009 / deferred-logger-bundle
1. Go to this page and download the library: Download scau009/deferred-logger-bundle library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
// Service A: Making a request to Service B
$traceId = DeferredLogger::getTraceId();
$response = $httpClient->request('POST', 'https://service-b/api/endpoint', [
'headers' => [
'X-Trace-ID' => $traceId, // Pass trace ID to downstream service
],
]);
// In your HTTP controller (Request A)
use Symfony\Component\Messenger\MessageBusInterface;
public function processOrder(MessageBusInterface $bus): Response
{
// Current trace_id: 550e8400-e29b-41d4-a716-446655440000
// Current span_id: 7f3a9e4c6b2d8f1a
DeferredLogger::contextInfo('Dispatching order processing');
// Dispatch async message - trace context is AUTOMATICALLY attached
$bus->dispatch(new ProcessOrderMessage($orderId));
return new JsonResponse(['status' => 'queued']);
}
// In your Message Handler (Async Worker)
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
#[AsMessageHandler]
class ProcessOrderHandler
{
public function __invoke(ProcessOrderMessage $message): void
{
// Trace context is AUTOMATICALLY restored!
// trace_id: 550e8400-e29b-41d4-a716-446655440000 (SAME as parent)
// span_id: a1b2c3d4e5f6g7h8 (NEW child span)
// parent_span_id: 7f3a9e4c6b2d8f1a (points to parent)
DeferredLogger::contextInfo('Processing order in async worker');
// All logs here will have the SAME trace_id as the original request!
}
}
#[AsMessageHandler]
class MyHandler
{
public function __invoke(MyMessage $message): void
{
$traceId = DeferredLogger::getTraceId();
// Make external API call with trace propagation
$this->httpClient->request('POST', 'https://external-api.com', [
'headers' => ['X-Trace-ID' => $traceId],
]);
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.