diff --git a/src/Monolog/Handler.php b/src/Monolog/Handler.php index 3e8d52bba..615a62192 100644 --- a/src/Monolog/Handler.php +++ b/src/Monolog/Handler.php @@ -59,7 +59,7 @@ protected function doWrite($record): void $hint = new EventHint(); - if (isset($record['context']['exception']) && $record['context']['exception'] instanceof \Throwable) { + if ($this->hasExceptionContext($record['context'])) { $hint->exception = $record['context']['exception']; } @@ -94,18 +94,12 @@ private function getMonologContextData(array $context): array return []; } - $contextData = []; - - foreach ($context as $key => $value) { - // We skip the `exception` field because it goes in its own context - if ($key === self::CONTEXT_EXCEPTION_KEY) { - continue; - } - - $contextData[$key] = $value; + if ($this->hasExceptionContext($context)) { + // remove the exception from the context, as it's set on the hint + unset($context[self::CONTEXT_EXCEPTION_KEY]); } - return $contextData; + return $context; } /** @@ -127,4 +121,12 @@ private function getMonologExtraData(array $context): array return $extraData; } + + /** + * @param mixed[] $context + */ + private function hasExceptionContext(array $context): bool + { + return isset($context[self::CONTEXT_EXCEPTION_KEY]) && $context[self::CONTEXT_EXCEPTION_KEY] instanceof \Throwable; + } } diff --git a/tests/Monolog/HandlerTest.php b/tests/Monolog/HandlerTest.php index bc1d4dd67..d2668814f 100644 --- a/tests/Monolog/HandlerTest.php +++ b/tests/Monolog/HandlerTest.php @@ -269,6 +269,7 @@ public static function handleDataProvider(): iterable [ 'foo' => 'bar', 'bar' => 'baz', + 'exception' => 'just a message', ], [] ), @@ -280,6 +281,7 @@ public static function handleDataProvider(): iterable 'monolog.context' => [ 'foo' => 'bar', 'bar' => 'baz', + 'exception' => 'just a message', ], ], ];