diff --git a/src/State/Scope.php b/src/State/Scope.php index d10e39025..546072f4e 100644 --- a/src/State/Scope.php +++ b/src/State/Scope.php @@ -378,9 +378,12 @@ public function applyToEvent(Event $event, ?EventHint $hint = null, ?Options $op /** * Apply the trace context to errors if there is a Span on the Scope. * Else fallback to the propagation context. + * But do not override a trace context already present. */ if ($this->span !== null) { - $event->setContext('trace', $this->span->getTraceContext()); + if (!\array_key_exists('trace', $event->getContexts())) { + $event->setContext('trace', $this->span->getTraceContext()); + } // Apply the dynamic sampling context to errors if there is a Transaction on the Scope $transaction = $this->span->getTransaction(); @@ -388,7 +391,9 @@ public function applyToEvent(Event $event, ?EventHint $hint = null, ?Options $op $event->setSdkMetadata('dynamic_sampling_context', $transaction->getDynamicSamplingContext()); } } else { - $event->setContext('trace', $this->propagationContext->getTraceContext()); + if (!\array_key_exists('trace', $event->getContexts())) { + $event->setContext('trace', $this->propagationContext->getTraceContext()); + } $dynamicSamplingContext = $this->propagationContext->getDynamicSamplingContext(); if ($dynamicSamplingContext === null && $options !== null) { diff --git a/tests/State/HubTest.php b/tests/State/HubTest.php index f3949bf04..a2d014648 100644 --- a/tests/State/HubTest.php +++ b/tests/State/HubTest.php @@ -851,4 +851,33 @@ public function testGetTransactionReturnsNullIfNoTransactionIsSetOnTheScope(): v $this->assertNull($hub->getTransaction()); } + + public function testEventTraceContextIsAlwaysFilled(): void + { + $hub = new Hub(); + + $event = Event::createEvent(); + + $hub->configureScope(function (Scope $scope) use ($event): void { + $event = $scope->applyToEvent($event); + + $this->assertNotEmpty($event->getContexts()['trace']); + }); + } + + public function testEventTraceContextIsNotOverridenWhenPresent(): void + { + $hub = new Hub(); + + $traceContext = ['foo' => 'bar']; + + $event = Event::createEvent(); + $event->setContext('trace', $traceContext); + + $hub->configureScope(function (Scope $scope) use ($event, $traceContext): void { + $event = $scope->applyToEvent($event); + + $this->assertEquals($event->getContexts()['trace'], $traceContext); + }); + } }