The only tool you need to know what is happening and how to fix it.
Go alertingexception-trackerissue-trackinglogsmetricsmonitoringobservability-platformopen-telemetryotelsession-replaytelemetrytraces
docs and devtesting-symfony update v1
ddux18351baf2696
diff --git a/docs/pages/client/symfony/exceptions.mdx b/docs/pages/client/symfony/exceptions.mdxindex b4660031..195851b6 100644--- a/docs/pages/client/symfony/exceptions.mdx+++ b/docs/pages/client/symfony/exceptions.mdx@@ -1,23 +1,22 @@# Exceptions-The OTel auto-instrumentation captures unhandled exceptions automatically. To report caught exceptions or add context to errors, use the OpenTelemetry PHP API directly.+The bundle automatically captures unhandled exceptions and records them on the request span. To report caught exceptions or add context to errors, use the OpenTelemetry PHP API directly.## Recording an Exception on the Current SpanWhen you catch an error but want it reported to Traceway, record it as an event on the active span:```php-use OpenTelemetry\API\Globals;+use OpenTelemetry\API\Trace\Span;use OpenTelemetry\API\Trace\StatusCode;try {$this->paymentGateway->charge($order);} catch (\Throwable $e) {- $span = OpenTelemetry\API\Trace\Span::getCurrent();+ $span = Span::getCurrent();$span->recordException($e);$span->setStatus(StatusCode::STATUS_ERROR, $e->getMessage());- // Handle gracefully or re-throwthrow $e;}```@@ -81,40 +80,6 @@ class PaymentService}```-## Symfony Event Listener--To capture all exceptions globally (including ones handled by Symfony's error system), register an event listener:--```php-// src/EventListener/ExceptionListener.php-namespace App\EventListener;--use OpenTelemetry\API\Trace\Span;-use OpenTelemetry\API\Trace\StatusCode;-use Symfony\Component\HttpKernel\Event\ExceptionEvent;--class ExceptionListener-{- public function onKernelException(ExceptionEvent $event): void- {- $span = Span::getCurrent();- $exception = $event->getThrowable();-- $span->recordException($exception);- $span->setStatus(StatusCode::STATUS_ERROR, $exception->getMessage());- }-}-```--Register it in `config/services.yaml`:--```yaml-services:- App\EventListener\ExceptionListener:- tags:- - { name: kernel.event_listener, event: kernel.exception }-```-## Custom Error TypesCustom exception classes work the same way. The exception type name appears in the Traceway dashboard:@@ -131,7 +96,6 @@ class InsufficientFundsException extends \RuntimeException}}-// When caught and recorded, Traceway shows "InsufficientFundsException" as the typetry {$this->withdraw($accountId, $amount);} catch (InsufficientFundsException $e) {diff --git a/docs/pages/client/symfony/index.mdx b/docs/pages/client/symfony/index.mdxindex d0275e56..17b893a7 100644--- a/docs/pages/client/symfony/index.mdx+++ b/docs/pages/client/symfony/index.mdx@@ -1,37 +1,30 @@# Symfony-Symfony integrates with Traceway via [OpenTelemetry](https://opentelemetry.io/). The PHP OTel extension auto-instruments your Symfony application and exports traces and metrics to Traceway's OTLP endpoints — no manual instrumentation needed.+The `traceway/opentelemetry-symfony` bundle automatically instruments your Symfony application and exports traces to Traceway's OTLP endpoints — no manual instrumentation needed.## Prerequisites- PHP 8.1++- Symfony 6.4+- Composer- A Traceway project (create one in the dashboard)-## Step 1: Install the PHP OTel Extension--The OpenTelemetry PHP extension provides auto-instrumentation:+## Step 1: Install Packages```bash-pecl install opentelemetry-```--Enable it in your `php.ini`:--```ini-extension=opentelemetry.so+composer require traceway/opentelemetry-symfony open-telemetry/sdk open-telemetry/exporter-otlp php-http/guzzle7-adapter```-## Step 2: Install Composer Packages--```bash-composer require open-telemetry/sdk open-telemetry/exporter-otlp-```+## Step 2: Register the Bundle-For automatic Symfony instrumentation, also install:+If Symfony Flex doesn't register it automatically, add it to `config/bundles.php`:-```bash-composer require open-telemetry/opentelemetry-auto-symfony+```php+// config/bundles.php+return [+ // ...+ Traceway\OpenTelemetryBundle\OpenTelemetryBundle::class => ['all' => true],+];```## Step 3: Configure Environment Variables@@ -52,14 +45,9 @@ Your Traceway dashboard includes a **Connection** page with a ready-made config> **Note:** Use `http/json` instead of `http/protobuf`. The protobuf encoder has known deprecation warnings on PHP 8.4+ that can cause noisy logs.-## Step 4: Update Your Front Controller--The `opentelemetry-auto-symfony` package has two issues that need a workaround in your `public/index.php`:--1. **Endpoint names** — `http.route` is set to the internal Symfony route name (e.g., `app_user_show`) instead of the URL path template (`/users/{id}`)-2. **500 errors not exported** — when Symfony renders an error page via a sub-request, the sub-request's OTel scope shadows the main request's scope, causing the main span to never be ended or exported+## Step 4: Initialize the SDK-Register this hook **after** the OTel autoloader to fix both issues:+Add the SDK autoloader to your `public/index.php`, after the Composer autoload:```php<?php@@ -71,50 +59,6 @@ require_once dirname(__DIR__) . '/vendor/autoload.php';\OpenTelemetry\SDK\SdkAutoloader::autoload();-// Fixes for Symfony's OTel auto-instrumentation:-// 1. Corrects http.route from internal route name to URL path template-// 2. Cleans up sub-request scopes so 500 error spans are exported-\OpenTelemetry\Instrumentation\hook(- \Symfony\Component\HttpKernel\HttpKernel::class,- 'handle',- post: static function (- \Symfony\Component\HttpKernel\HttpKernel $kernel,- array $params,- mixed $returnValue,- ?\Throwable $exception- ): void {- $request = ($params[0] instanceof \Symfony\Component\HttpFoundation\Request) ? $params[0] : null;- if (null === $request) return;-- $type = $params[1] ?? \Symfony\Component\HttpKernel\HttpKernelInterface::MAIN_REQUEST;-- // Sub-requests (e.g., error page rendering) push an extra OTel scope- // that shadows the main request. Clean up immediately.- if ($type === \Symfony\Component\HttpKernel\HttpKernelInterface::SUB_REQUEST) {- $scope = \OpenTelemetry\Context\Context::storage()->scope();- if (null !== $scope) {- $span = \OpenTelemetry\API\Trace\Span::fromContext($scope->context());- $scope->detach();- $span->end();- }- return;- }-- // For main requests: fix route name to path template- $routeParams = $request->attributes->get('_route_params', []);- $path = $request->getPathInfo();- if (\is_array($routeParams)) {- foreach ($routeParams as $name => $value) {- if (\is_string($value) && '' !== $value) {- $path = str_replace($value, '{' . $name . '}', $path);- }- }- }-- $request->attributes->set('_route', $path);- }-);-$kernel = new Kernel($_SERVER['APP_ENV'] ?? 'dev', (bool) ($_SERVER['APP_DEBUG'] ?? true));$request = \Symfony\Component\HttpFoundation\Request::createFromGlobals();$response = $kernel->handle($request);@@ -124,12 +68,30 @@ $kernel->terminate($request, $response);## What Gets Captured-Once configured, the OTel auto-instrumentation captures:+Once configured, the bundle automatically captures:-- **Endpoints** — every HTTP request handled by Symfony (method, route, duration)+- **Endpoints** — every HTTP request with method and route template (e.g., `GET /users/{id}`)- **Status codes** — 2xx, 4xx, 5xx responses-- **Exceptions** — unhandled errors and exceptions with stack traces-- **Metrics** — request count, duration histograms+- **Exceptions** — unhandled errors with stack traces+- **Client IP, body size, user agent** — standard HTTP attributes+- **Doctrine queries** — if `doctrine/dbal` is installed+- **Console commands** — Symfony CLI commands+- **Messenger jobs** — dispatched and consumed messages (see [Tasks](/client/symfony/tasks))++## Configuration (Optional)++Create `config/packages/open_telemetry.yaml` to customize behavior:++```yaml+open_telemetry:+ excluded_paths:+ - /_profiler+ - /_wdt+ - /health+ record_client_ip: true # default: true (set false for GDPR)+ error_status_threshold: 500 # HTTP status >= this marked as error+ messenger_root_spans: true # tasks appear as independent jobs in Traceway+```## Test Your Integration@@ -158,5 +120,6 @@ Visit `/testing` in your browser, then check the Traceway dashboard — the exce- [Exceptions](/client/symfony/exceptions) — manually capture caught exceptions with context- [Spans](/client/symfony/spans) — create custom spans to measure sub-operations+- [Tasks](/client/symfony/tasks) — trace Symfony Messenger background jobs- [Metrics](/client/symfony/metrics) — track custom counters, histograms, and gauges- [OpenTelemetry docs](/client/otel) — how OTel traces and metrics map to Tracewaydiff --git a/docs/pages/client/symfony/spans.mdx b/docs/pages/client/symfony/spans.mdxindex 9d6f9460..2a648a5f 100644--- a/docs/pages/client/symfony/spans.mdx+++ b/docs/pages/client/symfony/spans.mdx@@ -1,81 +1,78 @@# Spans-The OTel auto-instrumentation creates spans for HTTP requests automatically. To measure sub-operations like database queries, API calls, or business logic, create spans manually using the OpenTelemetry PHP API.+The bundle creates spans for HTTP requests automatically. To measure sub-operations like database queries, API calls, or business logic, create spans using the bundle's `TracingInterface` helper or the OpenTelemetry PHP API directly.-## Creating a Span+## Using TracingInterface-Use the tracer to start and end spans:+The bundle provides a `TracingInterface` service you can inject into any service or controller. It handles span creation, activation, error recording, and cleanup:```php-use OpenTelemetry\API\Globals;+use Traceway\OpenTelemetryBundle\TracingInterface;-$tracer = Globals::tracerProvider()->getTracer('app');+class OrderService+{+ public function __construct(+ private readonly TracingInterface $tracing,+ ) {}-$span = $tracer->spanBuilder('process-order')->startSpan();-try {- $this->processOrder($orderId);-} finally {- $span->end();+ public function processOrder(int $orderId): void+ {+ $this->tracing->trace('order.validate', function () use ($orderId) {+ $this->validateOrder($orderId);+ });++ $this->tracing->trace('order.charge', function () use ($orderId) {+ $this->chargePayment($orderId);+ });+ }}```-Always end spans in a `finally` block to ensure they are closed even if an exception is thrown.--## Activating a Span--To make a span the current active span (so child spans and exceptions are linked to it), activate it with a scope:+### With Attributes and Span Kind```php-use OpenTelemetry\API\Globals;+use OpenTelemetry\API\Trace\SpanKind;++$result = $this->tracing->trace(+ 'stripe.charge',+ fn () => $this->stripe->charge($amount),+ attributes: ['payment.amount' => $amount, 'payment.currency' => 'usd'],+ kind: SpanKind::KIND_CLIENT,+);+```-$tracer = Globals::tracerProvider()->getTracer('app');+### Nested Spans-$span = $tracer->spanBuilder('checkout')->startSpan();-$scope = $span->activate();-try {- // Any spans created here become children of "checkout"- $this->validateCart($cart);- $this->processPayment($payment);- $this->sendConfirmation($order);-} finally {- $scope->detach();- $span->end();-}+Child spans are automatically linked to the active parent span:++```php+$this->tracing->trace('order.fulfill', function () {+ $this->tracing->trace('inventory.reserve', fn () => $this->reserve());+ $this->tracing->trace('payment.charge', fn () => $this->charge());+ $this->tracing->trace('email.send', fn () => $this->notify());+});```-## Nested Spans+## Using the OpenTelemetry API Directly-Create child spans to break down an operation into sub-steps:+For advanced use cases (span events, manual status codes, lazy attributes), use the tracer directly:```phpuse OpenTelemetry\API\Globals;$tracer = Globals::tracerProvider()->getTracer('app');-$parentSpan = $tracer->spanBuilder('create-order')->startSpan();-$parentScope = $parentSpan->activate();+$span = $tracer->spanBuilder('process-order')->startSpan();+$scope = $span->activate();try {- // Child span: validate- $validateSpan = $tracer->spanBuilder('validate-items')->startSpan();- $this->validateItems($items);- $validateSpan->end();-- // Child span: inventory check- $inventorySpan = $tracer->spanBuilder('check-inventory')->startSpan();- $this->checkInventory($items);- $inventorySpan->end();-- // Child span: payment- $paymentSpan = $tracer->spanBuilder('process-payment')->startSpan();- $this->processPayment($paymentInfo);- $paymentSpan->end();+ $this->processOrder($orderId);} finally {- $parentScope->detach();- $parentSpan->end();+ $scope->detach();+ $span->end();}```-Child spans are automatically linked to the active parent span.+Always end spans in a `finally` block to ensure they are closed even if an exception is thrown.## Adding Attributes@@ -119,72 +116,3 @@ Use descriptive names that indicate the operation type:| `stripe.charge` | `api` || `s3.upload-image` | `upload` || `email.send-welcome` | `send` |--## Database Wrapper Example--```php-use OpenTelemetry\API\Globals;--class TracedRepository-{- private $tracer;-- public function __construct(- private readonly Connection $connection,- ) {- $this->tracer = Globals::tracerProvider()->getTracer('app');- }-- public function query(string $sql, array $params = []): array- {- $span = $this->tracer->spanBuilder('db.query')->startSpan();- $span->setAttribute('db.statement', $sql);- try {- $result = $this->connection->fetchAllAssociative($sql, $params);- $span->setAttribute('db.row_count', count($result));- return $result;- } catch (\Throwable $e) {- $span->recordException($e);- $span->setStatus(\OpenTelemetry\API\Trace\StatusCode::STATUS_ERROR, $e->getMessage());- throw $e;- } finally {- $span->end();- }- }-}-```--## HTTP Client Wrapper Example--```php-use OpenTelemetry\API\Globals;--class TracedHttpClient-{- private $tracer;-- public function __construct(- private readonly HttpClientInterface $client,- ) {- $this->tracer = Globals::tracerProvider()->getTracer('app');- }-- public function request(string $method, string $url, array $options = []): ResponseInterface- {- $span = $this->tracer->spanBuilder("http.{$method}")->startSpan();- $span->setAttribute('http.method', $method);- $span->setAttribute('http.url', $url);- try {- $response = $this->client->request($method, $url, $options);- $span->setAttribute('http.status_code', $response->getStatusCode());- return $response;- } catch (\Throwable $e) {- $span->recordException($e);- $span->setStatus(\OpenTelemetry\API\Trace\StatusCode::STATUS_ERROR, $e->getMessage());- throw $e;- } finally {- $span->end();- }- }-}-```diff --git a/docs/pages/client/symfony/tasks.mdx b/docs/pages/client/symfony/tasks.mdxindex 8feea3fe..8eea0fa0 100644--- a/docs/pages/client/symfony/tasks.mdx+++ b/docs/pages/client/symfony/tasks.mdx@@ -1,250 +1,35 @@# Tasks-OpenTelemetry PHP does not have auto-instrumentation for Symfony Messenger. To trace background tasks consumed by your workers, you need to instrument them manually. There are two approaches: creating spans directly in each handler, or using a Messenger middleware that handles it automatically.+The bundle automatically traces Symfony Messenger messages. Each consumed message appears as a task in Traceway with its duration, status, and any child spans.-## Manual Setup+## Setup-The simplest approach is to create a root span directly inside each message handler.+Add `messenger_root_spans: true` to your bundle config so consumed messages appear as independent tasks (not children of the HTTP request that dispatched them):-### Basic Handler--Create a tracer, build a root span with `setParent(false)` and `KIND_CONSUMER`, activate it, and always end the span in a `finally` block:--```php-use OpenTelemetry\API\Globals;-use OpenTelemetry\API\Trace\SpanKind;-use OpenTelemetry\API\Trace\StatusCode;--#[AsMessageHandler]-class EmailSendHandler-{- public function __invoke(EmailSendMessage $message): void- {- $tracer = Globals::tracerProvider()->getTracer('app');- $span = $tracer->spanBuilder('email.send')- ->setParent(false)- ->setSpanKind(SpanKind::KIND_CONSUMER)- ->startSpan();- $scope = $span->activate();-- try {- $span->setAttribute('email.to', $message->to);- $span->setAttribute('email.subject', $message->subject);-- $this->mailer->send($message);- } catch (\Throwable $e) {- $span->recordException($e);- $span->setStatus(StatusCode::STATUS_ERROR, $e->getMessage());- throw $e;- } finally {- $scope->detach();- $span->end();- }- }-}-```--Key points:-- **`setParent(false)`** makes this a new trace root, not a child of the HTTP request that dispatched the message-- **`activate()`** sets the span as the current active span so child spans (manual or auto-instrumented) nest correctly under it-- **`try/catch/finally`** ensures errors are recorded and the span is always ended and scope detached--### Handler with Child Spans--For handlers with distinct sub-operations, create child spans using the tracer. They automatically nest under the activated root span:--```php-use OpenTelemetry\API\Globals;-use OpenTelemetry\API\Trace\SpanKind;-use OpenTelemetry\API\Trace\StatusCode;--#[AsMessageHandler]-class PaymentProcessorHandler-{- public function __invoke(PaymentProcessorMessage $message): void- {- $tracer = Globals::tracerProvider()->getTracer('app');- $span = $tracer->spanBuilder('payment.processor')- ->setParent(false)- ->setSpanKind(SpanKind::KIND_CONSUMER)- ->startSpan();- $scope = $span->activate();-- try {- // Child span for validation- $validateSpan = $tracer->spanBuilder('validate.payment')- ->setSpanKind(SpanKind::KIND_INTERNAL)- ->startSpan();- $validateSpan->setAttribute('payment.amount', $message->amount);- $validateSpan->setAttribute('payment.currency', $message->currency);- $this->validate($message);- $validateSpan->end();-- // Child span for gateway call- $chargeSpan = $tracer->spanBuilder('charge.gateway')- ->setSpanKind(SpanKind::KIND_CLIENT)- ->startSpan();- try {- $this->chargeGateway($message);- } catch (\Throwable $e) {- $chargeSpan->setStatus(StatusCode::STATUS_ERROR, $e->getMessage());- $chargeSpan->recordException($e);- throw $e;- } finally {- $chargeSpan->end();- }- } catch (\Throwable $e) {- $span->recordException($e);- $span->setStatus(StatusCode::STATUS_ERROR, $e->getMessage());- throw $e;- } finally {- $scope->detach();- $span->end();- }- }-}-```--import { Callout } from 'nextra/components'--<Callout type="warning">-If you forget to call `activate()` on the root span, child spans will not nest under it — they will be created as separate traces instead.-</Callout>--## Automatic Setup with Middleware--For a cleaner approach, use a Symfony Messenger middleware that wraps every consumed message in a root span automatically. This eliminates the boilerplate from each handler.--### Step 1: Create the Middleware--```php filename="src/Messenger/TracingMiddleware.php"-<?php--namespace App\Messenger;--use OpenTelemetry\API\Globals;-use OpenTelemetry\API\Trace\SpanKind;-use OpenTelemetry\API\Trace\StatusCode;-use Symfony\Component\Messenger\Envelope;-use Symfony\Component\Messenger\Middleware\MiddlewareInterface;-use Symfony\Component\Messenger\Middleware\StackInterface;-use Symfony\Component\Messenger\Stamp\ReceivedStamp;--class TracingMiddleware implements MiddlewareInterface-{- public function handle(Envelope $envelope, StackInterface $stack): Envelope- {- // Only trace on the consumer side- if (!$envelope->last(ReceivedStamp::class)) {- return $stack->next()->handle($envelope, $stack);- }-- $message = $envelope->getMessage();- $spanName = $this->resolveSpanName($message);-- $tracer = Globals::tracerProvider()->getTracer('app');- $span = $tracer->spanBuilder($spanName)- ->setParent(false)- ->setSpanKind(SpanKind::KIND_CONSUMER)- ->startSpan();- $scope = $span->activate();-- try {- $envelope = $stack->next()->handle($envelope, $stack);- } catch (\Throwable $e) {- $span->recordException($e);- $span->setStatus(StatusCode::STATUS_ERROR, $e->getMessage());- throw $e;- } finally {- $span->end();- $scope->detach();- }-- return $envelope;- }-- private function resolveSpanName(object $message): string- {- if ($message instanceof TracedMessage) {- return $message->getSpanName();- }-- // Strip "Message" suffix, convert PascalCase -> dot.separated- $class = (new \ReflectionClass($message))->getShortName();- $class = preg_replace('/Message$/', '', $class);- $name = preg_replace('/([a-z])([A-Z])/', '$1.$2', $class);- return strtolower($name);- }-}-```--The middleware:-- **Only traces on the consumer side** — checks for `ReceivedStamp` so dispatching is not affected-- **Creates a detached root span** — `setParent(false)` ensures the task span is a new trace, not a child of the HTTP request that dispatched it-- **Activates scope** — so child spans (manual or auto-instrumented) nest correctly under the root-- **Handles errors** — records the exception and sets error status, then re-throws so Messenger's retry/failure handling works normally--### Step 2: Create the TracedMessage Interface--For custom span names, create an optional interface that message classes can implement:--```php filename="src/Messenger/TracedMessage.php"-<?php--namespace App\Messenger;--interface TracedMessage-{- public function getSpanName(): string;-}+```yaml filename="config/packages/open_telemetry.yaml"+open_telemetry:+ messenger_root_spans: true```-```php filename="src/Message/OrderFulfillmentMessage.php"-use App\Messenger\TracedMessage;+That's it — every consumed message is now traced automatically.-class OrderFulfillmentMessage implements TracedMessage-{- public function __construct(- public readonly string $orderId,- ) {}+## What Gets Captured- public function getSpanName(): string- {- return 'orders.fulfill';- }-}-```--### Step 3: Register the Middleware+For each consumed message, the bundle records:-Add the middleware to your bus configuration:--```yaml filename="config/packages/messenger.yaml"-framework:- messenger:- buses:- messenger.bus.default:- middleware:- - 'App\Messenger\TracingMiddleware'-```+- **Span name** — the message class name (e.g., `EmailSendMessage process`)+- **Duration** — total handler execution time+- **Transport** — which transport delivered the message (e.g., `async`)+- **Errors** — exceptions are recorded with stack traces and the span is marked as failed+- **Child spans** — any spans created inside the handler nest under the task span-### Span Name Resolution+## Adding Attributes in Handlers-By default, the middleware derives the span name from the message class name — it strips the `Message` suffix and converts PascalCase to dot-separated lowercase:--| Message Class | Span Name |-|---|---|-| `EmailSendMessage` | `email.send` |-| `UserDataSyncMessage` | `user.data.sync` |-| `DataProcessorMessage` | `data.processor` |-| `PaymentProcessorMessage` | `payment.processor` |--### Accessing the Root Span in Handlers--Since the middleware activates the span, handlers can access it via `Span::getCurrent()` to add attributes:+Since the bundle activates the task span before your handler runs, use `Span::getCurrent()` to add custom attributes:```phpuse OpenTelemetry\API\Trace\Span;+use Symfony\Component\Messenger\Attribute\AsMessageHandler;#[AsMessageHandler]class EmailSendHandler@@ -261,53 +46,35 @@ class EmailSendHandler}```-### Adding Child Spans+## Child Spans in Handlers-For handlers with distinct sub-operations, create child spans using the tracer. They automatically nest under the middleware's root span:+For handlers with distinct sub-operations, inject `TracingInterface` to create child spans. They automatically nest under the task's root span:```php-use OpenTelemetry\API\Globals;-use OpenTelemetry\API\Trace\Span;use OpenTelemetry\API\Trace\SpanKind;-use OpenTelemetry\API\Trace\StatusCode;+use Symfony\Component\Messenger\Attribute\AsMessageHandler;+use Traceway\OpenTelemetryBundle\TracingInterface;#[AsMessageHandler]class PaymentProcessorHandler{+ public function __construct(+ private readonly TracingInterface $tracing,+ ) {}+public function __invoke(PaymentProcessorMessage $message): void{- $tracer = Globals::tracerProvider()->getTracer('app');-- // Child span for validation- $validateSpan = $tracer->spanBuilder('validate.payment')- ->setSpanKind(SpanKind::KIND_INTERNAL)- ->startSpan();- $validateSpan->setAttribute('payment.amount', $message->amount);- $validateSpan->setAttribute('payment.currency', $message->currency);- $this->validate($message);- $validateSpan->end();+ $this->tracing->trace('validate.payment', function () use ($message) {+ $this->validate($message);+ }, ['payment.amount' => $message->amount, 'payment.currency' => $message->currency]);- // Child span for gateway call- $chargeSpan = $tracer->spanBuilder('charge.gateway')- ->setSpanKind(SpanKind::KIND_CLIENT)- ->startSpan();- try {+ $this->tracing->trace('charge.gateway', function () use ($message) {$this->chargeGateway($message);- } catch (\Throwable $e) {- $chargeSpan->setStatus(StatusCode::STATUS_ERROR, $e->getMessage());- $chargeSpan->recordException($e);-- // Propagate error to the root span- $rootSpan = Span::getCurrent();- $rootSpan->setStatus(StatusCode::STATUS_ERROR, $e->getMessage());- $rootSpan->recordException($e);- } finally {- $chargeSpan->end();- }+ }, kind: SpanKind::KIND_CLIENT);}}```-## Auto-Instrumentation+## Dispatch Tracing-If you have `opentelemetry-auto-pdo` installed (see [Quick Start](/client/symfony)), database operations in your handlers automatically create child spans under the root span. No additional code is needed — any PDO calls made during message handling will appear as nested spans in Traceway.+The bundle also traces the dispatch side — when your controller or service dispatches a message, a PRODUCER span is created. W3C trace context is injected into the message envelope so the consumer span links back to the dispatching trace (unless `messenger_root_spans` is `true`, in which case the consumer creates an independent root span).diff --git a/testing/devtesting-symfony/composer.json b/testing/devtesting-symfony/composer.jsonindex 8e7b394d..6432062c 100644--- a/testing/devtesting-symfony/composer.json+++ b/testing/devtesting-symfony/composer.json@@ -2,6 +2,12 @@"name": "traceway/devtesting-symfony","description": "Symfony test application for Traceway via OpenTelemetry","type": "project",+ "repositories": [+ {+ "type": "path",+ "url": "/Users/dusanstanojevic/Documents/workspace/opentelemetry-symfony-bundle"+ }+ ],"require": {"php": ">=8.2","symfony/framework-bundle": "^7.0",@@ -10,10 +16,8 @@"symfony/yaml": "^7.0","open-telemetry/sdk": "^1.0","open-telemetry/exporter-otlp": "^1.0",- "open-telemetry/opentelemetry-auto-symfony": "^1.0",- "open-telemetry/opentelemetry-auto-pdo": "^0.0","php-http/guzzle7-adapter": "^1.0",- "google/protobuf": "^4.0",+ "traceway/opentelemetry-symfony": "@dev","symfony/string": "^7.0","symfony/messenger": "^8.0","symfony/doctrine-messenger": "^8.0",diff --git a/testing/devtesting-symfony/config/bundles.php b/testing/devtesting-symfony/config/bundles.phpindex dcac3c31..be931d50 100644--- a/testing/devtesting-symfony/config/bundles.php+++ b/testing/devtesting-symfony/config/bundles.php@@ -3,4 +3,5 @@return [Symfony\Bundle\FrameworkBundle\FrameworkBundle::class => ['all' => true],Doctrine\Bundle\DoctrineBundle\DoctrineBundle::class => ['all' => true],+ Traceway\OpenTelemetryBundle\OpenTelemetryBundle::class => ['all' => true],];diff --git a/testing/devtesting-symfony/config/packages/messenger.yaml b/testing/devtesting-symfony/config/packages/messenger.yamlindex af0df487..23327505 100644--- a/testing/devtesting-symfony/config/packages/messenger.yaml+++ b/testing/devtesting-symfony/config/packages/messenger.yaml@@ -1,10 +1,5 @@framework:messenger:- buses:- messenger.bus.default:- middleware:- - 'App\Messenger\TracingMiddleware'-transports:async:dsn: 'doctrine://default'diff --git a/testing/devtesting-symfony/config/packages/open_telemetry.yaml b/testing/devtesting-symfony/config/packages/open_telemetry.yamlnew file mode 100644index 00000000..de0ea9a0--- /dev/null+++ b/testing/devtesting-symfony/config/packages/open_telemetry.yaml@@ -0,0 +1,5 @@+open_telemetry:+ messenger_root_spans: true+ excluded_paths:+ - /_profiler+ - /_wdtdiff --git a/testing/devtesting-symfony/public/index.php b/testing/devtesting-symfony/public/index.phpindex b001a996..bbcecc5b 100644--- a/testing/devtesting-symfony/public/index.php+++ b/testing/devtesting-symfony/public/index.php@@ -8,58 +8,6 @@ require_once dirname(__DIR__) . '/vendor/autoload.php';(new Dotenv())->loadEnv(dirname(__DIR__) . '/.env');\OpenTelemetry\SDK\SdkAutoloader::autoload();-// Fix 1: Symfony's OTel auto-instrumentation sets http.route to the-// internal route name (e.g., "app_test_testparam") instead of the-// path template. This hook modifies _route on the request so Symfony's-// own terminate hook reads the corrected path.-//-// Fix 2: When a 500 occurs, Symfony renders the error page via a-// sub-request, which creates an extra OTel scope. The terminate hook-// then picks up the sub-request scope instead of the main request's,-// leaving the main span orphaned (never ended, never exported).-// We clean up sub-request scopes immediately to prevent this.-\OpenTelemetry\Instrumentation\hook(- \Symfony\Component\HttpKernel\HttpKernel::class,- 'handle',- post: static function (- \Symfony\Component\HttpKernel\HttpKernel $kernel,- array $params,- mixed $returnValue,- ?\Throwable $exception- ): void {- $request = ($params[0] instanceof \Symfony\Component\HttpFoundation\Request) ? $params[0] : null;- if (null === $request) return;-- $type = $params[1] ?? \Symfony\Component\HttpKernel\HttpKernelInterface::MAIN_REQUEST;-- // Sub-requests (e.g., error page rendering) push an extra scope- // that prevents the main request's span from being exported.- // Clean up sub-request scopes immediately.- if ($type === \Symfony\Component\HttpKernel\HttpKernelInterface::SUB_REQUEST) {- $scope = \OpenTelemetry\Context\Context::storage()->scope();- if (null !== $scope) {- $span = \OpenTelemetry\API\Trace\Span::fromContext($scope->context());- $scope->detach();- $span->end();- }- return;- }-- // For main requests: fix route name from internal name to path template- $routeParams = $request->attributes->get('_route_params', []);- $path = $request->getPathInfo();- if (\is_array($routeParams)) {- foreach ($routeParams as $name => $value) {- if (\is_string($value) && '' !== $value) {- $path = str_replace($value, '{' . $name . '}', $path);- }- }- }-- $request->attributes->set('_route', $path);- }-);-$kernel = new Kernel('dev', true);$request = \Symfony\Component\HttpFoundation\Request::createFromGlobals();$response = $kernel->handle($request);diff --git a/testing/devtesting-symfony/src/Controller/TestController.php b/testing/devtesting-symfony/src/Controller/TestController.phpindex 4f50b82d..6ff370cb 100644--- a/testing/devtesting-symfony/src/Controller/TestController.php+++ b/testing/devtesting-symfony/src/Controller/TestController.php@@ -10,9 +10,14 @@ use Symfony\Component\HttpFoundation\JsonResponse;use Symfony\Component\HttpFoundation\Request;use Symfony\Component\HttpFoundation\Response;use Symfony\Component\Routing\Attribute\Route;+use Traceway\OpenTelemetryBundle\TracingInterface;class TestController{+ public function __construct(+ private readonly TracingInterface $tracing,+ ) {}+#[Route('/test-ok', methods: ['GET'])]public function testOk(): JsonResponse{@@ -35,33 +40,19 @@ class TestController#[Route('/test-spans', methods: ['GET'])]public function testSpans(): JsonResponse{- $tracer = Globals::tracerProvider()->getTracer('devtesting-symfony');-- $dbAndCacheSpan = $tracer->spanBuilder('db.and.cache')- ->setSpanKind(SpanKind::KIND_INTERNAL)- ->startSpan();- $dbAndCacheScope = $dbAndCacheSpan->activate();-- $dbSpan = $tracer->spanBuilder('db.query')- ->setSpanKind(SpanKind::KIND_INTERNAL)- ->startSpan();- usleep((50 + random_int(0, 100)) * 1000);- $dbSpan->end();-- $cacheSpan = $tracer->spanBuilder('cache.set')- ->setSpanKind(SpanKind::KIND_INTERNAL)- ->startSpan();- usleep((10 + random_int(0, 30)) * 1000);- $cacheSpan->end();-- $httpSpan = $tracer->spanBuilder('http.external_api')- ->setSpanKind(SpanKind::KIND_CLIENT)- ->startSpan();- usleep((100 + random_int(0, 200)) * 1000);- $httpSpan->end();-- $dbAndCacheSpan->end();- $dbAndCacheScope->detach();+ $this->tracing->trace('db.and.cache', function () {+ $this->tracing->trace('db.query', function () {+ usleep((50 + random_int(0, 100)) * 1000);+ });++ $this->tracing->trace('cache.set', function () {+ usleep((10 + random_int(0, 30)) * 1000);+ });++ $this->tracing->trace('http.external_api', function () {+ usleep((100 + random_int(0, 200)) * 1000);+ }, kind: SpanKind::KIND_CLIENT);+ });return new JsonResponse(['status' => 'ok', 'message' => 'Spans captured']);}diff --git a/testing/devtesting-symfony/src/MessageHandler/DataProcessorHandler.php b/testing/devtesting-symfony/src/MessageHandler/DataProcessorHandler.phpindex a376d678..5dc12c8e 100644--- a/testing/devtesting-symfony/src/MessageHandler/DataProcessorHandler.php+++ b/testing/devtesting-symfony/src/MessageHandler/DataProcessorHandler.php@@ -3,24 +3,23 @@namespace App\MessageHandler;use App\Message\DataProcessorMessage;-use OpenTelemetry\API\Globals;use OpenTelemetry\API\Trace\Span;-use OpenTelemetry\API\Trace\SpanKind;use OpenTelemetry\API\Trace\StatusCode;use Symfony\Component\Messenger\Attribute\AsMessageHandler;+use Traceway\OpenTelemetryBundle\TracingInterface;#[AsMessageHandler]class DataProcessorHandler{+ public function __construct(+ private readonly TracingInterface $tracing,+ ) {}+public function __invoke(DataProcessorMessage $message): void{- $tracer = Globals::tracerProvider()->getTracer('devtesting-symfony');-- $loadSpan = $tracer->spanBuilder('loading data')- ->setSpanKind(SpanKind::KIND_INTERNAL)- ->startSpan();- usleep(random_int(100, 2000) * 1000);- $loadSpan->end();+ $this->tracing->trace('loading data', function () {+ usleep(random_int(100, 2000) * 1000);+ });$rootSpan = Span::getCurrent();diff --git a/testing/devtesting-symfony/src/MessageHandler/PaymentProcessorHandler.php b/testing/devtesting-symfony/src/MessageHandler/PaymentProcessorHandler.phpindex 4d45d068..e5f763bb 100644--- a/testing/devtesting-symfony/src/MessageHandler/PaymentProcessorHandler.php+++ b/testing/devtesting-symfony/src/MessageHandler/PaymentProcessorHandler.php@@ -3,39 +3,34 @@namespace App\MessageHandler;use App\Message\PaymentProcessorMessage;-use OpenTelemetry\API\Globals;use OpenTelemetry\API\Trace\Span;use OpenTelemetry\API\Trace\SpanKind;use OpenTelemetry\API\Trace\StatusCode;use Symfony\Component\Messenger\Attribute\AsMessageHandler;+use Traceway\OpenTelemetryBundle\TracingInterface;#[AsMessageHandler]class PaymentProcessorHandler{+ public function __construct(+ private readonly TracingInterface $tracing,+ ) {}+public function __invoke(PaymentProcessorMessage $message): void{- $tracer = Globals::tracerProvider()->getTracer('devtesting-symfony');-- $validateSpan = $tracer->spanBuilder('validate.payment')- ->setSpanKind(SpanKind::KIND_INTERNAL)- ->startSpan();- $validateSpan->setAttribute('payment.amount', $message->amount);- $validateSpan->setAttribute('payment.currency', $message->currency);- usleep(random_int(20, 100) * 1000);- $validateSpan->end();-- $chargeSpan = $tracer->spanBuilder('charge.gateway')- ->setSpanKind(SpanKind::KIND_CLIENT)- ->startSpan();- usleep(random_int(100, 500) * 1000);-- $err = new \RuntimeException('gateway timeout: payment provider unreachable');- $chargeSpan->setStatus(StatusCode::STATUS_ERROR, $err->getMessage());- $chargeSpan->recordException($err);- $chargeSpan->end();+ $this->tracing->trace('validate.payment', function () use ($message) {+ usleep(random_int(20, 100) * 1000);+ }, ['payment.amount' => $message->amount, 'payment.currency' => $message->currency]);- $rootSpan = Span::getCurrent();- $rootSpan->setStatus(StatusCode::STATUS_ERROR, $err->getMessage());- $rootSpan->recordException($err);+ try {+ $this->tracing->trace('charge.gateway', function () {+ usleep(random_int(100, 500) * 1000);+ throw new \RuntimeException('gateway timeout: payment provider unreachable');+ }, kind: SpanKind::KIND_CLIENT);+ } catch (\RuntimeException $e) {+ $rootSpan = Span::getCurrent();+ $rootSpan->setStatus(StatusCode::STATUS_ERROR, $e->getMessage());+ $rootSpan->recordException($e);+ }}}diff --git a/testing/devtesting-symfony/src/Messenger/TracedMessage.php b/testing/devtesting-symfony/src/Messenger/TracedMessage.phpdeleted file mode 100644index b82a9483..00000000--- a/testing/devtesting-symfony/src/Messenger/TracedMessage.php+++ /dev/null@@ -1,8 +0,0 @@-<?php--namespace App\Messenger;--interface TracedMessage-{- public function getSpanName(): string;-}diff --git a/testing/devtesting-symfony/src/Messenger/TracingMiddleware.php b/testing/devtesting-symfony/src/Messenger/TracingMiddleware.phpdeleted file mode 100644index 9a978486..00000000--- a/testing/devtesting-symfony/src/Messenger/TracingMiddleware.php+++ /dev/null@@ -1,58 +0,0 @@-<?php--namespace App\Messenger;--use OpenTelemetry\API\Globals;-use OpenTelemetry\API\Trace\SpanKind;-use OpenTelemetry\API\Trace\StatusCode;-use Symfony\Component\Messenger\Envelope;-use Symfony\Component\Messenger\Middleware\MiddlewareInterface;-use Symfony\Component\Messenger\Middleware\StackInterface;-use Symfony\Component\Messenger\Stamp\ReceivedStamp;--class TracingMiddleware implements MiddlewareInterface-{- public function handle(Envelope $envelope, StackInterface $stack): Envelope- {- if (!$envelope->last(ReceivedStamp::class)) {- return $stack->next()->handle($envelope, $stack);- }-- $message = $envelope->getMessage();- $spanName = $this->resolveSpanName($message);-- $tracer = Globals::tracerProvider()->getTracer('devtesting-symfony');- $span = $tracer->spanBuilder($spanName)- ->setParent(false)- ->setSpanKind(SpanKind::KIND_CONSUMER)- ->startSpan();- $scope = $span->activate();-- try {- $envelope = $stack->next()->handle($envelope, $stack);- } catch (\Throwable $e) {- $span->recordException($e);- $span->setStatus(StatusCode::STATUS_ERROR, $e->getMessage());- throw $e;- } finally {- $span->end();- $scope->detach();- }-- return $envelope;- }-- private function resolveSpanName(object $message): string- {- if ($message instanceof TracedMessage) {- return $message->getSpanName();- }-- $class = (new \ReflectionClass($message))->getShortName();- $class = preg_replace('/Message$/', '', $class);-- // PascalCase → dot.separated lowercase- $name = preg_replace('/([a-z])([A-Z])/', '$1.$2', $class);- return strtolower($name);- }-}