Skip to content

Commit

Permalink
Fix serializability of Logger class, fixes #1792
Browse files Browse the repository at this point in the history
  • Loading branch information
Seldaek committed Feb 6, 2023
1 parent e1c0ae1 commit 2ae0444
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
30 changes: 30 additions & 0 deletions src/Monolog/Logger.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

This comment has been minimized.

Copy link
@stof

stof Feb 6, 2023

Contributor

shouldn't this be data[$property] ?

This comment has been minimized.

Copy link
@Seldaek

Seldaek Feb 6, 2023

Author Owner

Yes it was fixed in the next commit after I realized my mistake when merging to main branch (which caught it thanks to property types, but PHPStan would've complained too)

}
}

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;
}
}
}
8 changes: 7 additions & 1 deletion tests/Monolog/LoggerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -901,4 +907,4 @@ public function handleBatch(array $records): void
public function close(): void
{
}
}
}

0 comments on commit 2ae0444

Please sign in to comment.