Skip to content

Commit

Permalink
Do not overwrite trace context if already present (#1668)
Browse files Browse the repository at this point in the history
  • Loading branch information
stayallive authored Dec 21, 2023
1 parent c3e68c4 commit 4f703f9
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
9 changes: 7 additions & 2 deletions src/State/Scope.php
Original file line number Diff line number Diff line change
Expand Up @@ -378,17 +378,22 @@ 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();
if ($transaction !== null) {
$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) {
Expand Down
29 changes: 29 additions & 0 deletions tests/State/HubTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
}
}

0 comments on commit 4f703f9

Please sign in to comment.