Skip to content

Commit 05c6b18

Browse files
Fix json formatter does not catch to string exceptions (#1968)
* fix: JsonFormatter does not catch toString exceptions * test: test JsonFormatter toString handling --------- Co-authored-by: Adrien SIMON <asimon@worldia.com>
1 parent daa0aca commit 05c6b18

2 files changed

Lines changed: 32 additions & 1 deletion

File tree

src/Monolog/Formatter/JsonFormatter.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,11 @@ protected function normalize(mixed $data, int $depth = 0): mixed
195195
}
196196

197197
if ($data instanceof Stringable) {
198-
return $data->__toString();
198+
try {
199+
return $data->__toString();
200+
} catch (Throwable) {
201+
return $data::class;
202+
}
199203
}
200204

201205
if (\get_class($data) === '__PHP_Incomplete_Class') {

tests/Monolog/Formatter/JsonFormatterTest.php

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
namespace Monolog\Formatter;
1313

14+
use Exception;
1415
use Monolog\Level;
1516
use Monolog\LogRecord;
1617
use JsonSerializable;
@@ -338,6 +339,24 @@ public function testFormatObjects()
338339
$record
339340
);
340341
}
342+
343+
public function testNormalizeHandleExceptionInToString(): void
344+
{
345+
$formatter = new JsonFormatter();
346+
347+
$res = $formatter->format($this->getRecord(
348+
Level::Critical,
349+
'bar',
350+
datetime: new \DateTimeImmutable('2025-05-19 00:00:00'),
351+
channel: 'test',
352+
context: ['object' => new TestJsonNormWithFailingToString],
353+
));
354+
355+
$this->assertSame(
356+
'{"message":"bar","context":{"object":"Monolog\\\\Formatter\\\\TestJsonNormWithFailingToString"},"level":500,"level_name":"CRITICAL","channel":"test","datetime":"2025-05-19T00:00:00+00:00","extra":{}}'."\n",
357+
$res,
358+
);
359+
}
341360
}
342361

343362
class TestJsonNormPublic
@@ -370,3 +389,11 @@ public function __toString()
370389
return 'stringified';
371390
}
372391
}
392+
393+
class TestJsonNormWithFailingToString
394+
{
395+
public function __toString()
396+
{
397+
throw new Exception('Whatever');
398+
}
399+
}

0 commit comments

Comments
 (0)