From 2ae044482cd301d95fcd1565667259f94e833e87 Mon Sep 17 00:00:00 2001 From: Jordi Boggiano Date: Mon, 6 Feb 2023 14:33:41 +0100 Subject: [PATCH] Fix serializability of Logger class, fixes #1792 --- src/Monolog/Logger.php | 30 ++++++++++++++++++++++++++++++ tests/Monolog/LoggerTest.php | 8 +++++++- 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/src/Monolog/Logger.php b/src/Monolog/Logger.php index 775d7cf1f..5186f576b 100644 --- a/src/Monolog/Logger.php +++ b/src/Monolog/Logger.php @@ -722,4 +722,34 @@ protected function handleException(Throwable $e, array $record): void ($this->exceptionHandler)($e, $record); } + + public function __serialize(): array + { + return [ + 'name' => $this->name, + 'handlers' => $this->handlers, + 'processors' => $this->processors, + 'microsecondTimestamps' => $this->microsecondTimestamps, + 'timezone' => $this->timezone, + 'exceptionHandler' => $this->exceptionHandler, + 'logDepth' => $this->logDepth, + 'detectCycles' => $this->detectCycles, + ]; + } + + public function __unserialize(array $data): void + { + foreach (['name', 'handlers', 'processors', 'microsecondTimestamps', 'timezone', 'exceptionHandler', 'logDepth', 'detectCycles'] as $property) { + if (isset($data[$property])) { + $this->$property = $data; + } + } + + if (\PHP_VERSION_ID >= 80100) { + // Local variable for phpstan, see https://github.com/phpstan/phpstan/issues/6732#issuecomment-1111118412 + /** @var \WeakMap<\Fiber, int> $fiberLogDepth */ + $fiberLogDepth = new \WeakMap(); + $this->fiberLogDepth = $fiberLogDepth; + } + } } diff --git a/tests/Monolog/LoggerTest.php b/tests/Monolog/LoggerTest.php index a0ec74054..60c04a4fb 100644 --- a/tests/Monolog/LoggerTest.php +++ b/tests/Monolog/LoggerTest.php @@ -697,6 +697,12 @@ public function testCustomHandleException() $logger->info('test'); } + public function testSerializable() + { + $logger = new Logger(__METHOD__); + self::assertInstanceOf(Logger::class, unserialize(serialize($logger))); + } + public function testReset() { $logger = new Logger('app'); @@ -901,4 +907,4 @@ public function handleBatch(array $records): void public function close(): void { } -} \ No newline at end of file +}