1
0
mirror of https://github.com/Seldaek/monolog.git synced 2025-08-06 13:16:39 +02:00

Normalize call normalizeRecord if necessary (#1906)

* Normalize call normalizeRecord if necessary

* Update patch to always go through format()

* Update JsonFormatterTest.php

* Fix implementation

* Fix test expectations

* Update JsonFormatter.php

---------

Co-authored-by: Jordi Boggiano <j.boggiano@seld.be>
This commit is contained in:
Jonathan Plantey
2024-11-11 15:34:03 +01:00
committed by GitHub
parent f43e3d5637
commit 5d5da57b81
2 changed files with 31 additions and 18 deletions

View File

@@ -74,22 +74,7 @@ class JsonFormatter extends NormalizerFormatter
*/
public function format(LogRecord $record): string
{
$normalized = parent::format($record);
if (isset($normalized['context']) && $normalized['context'] === []) {
if ($this->ignoreEmptyContextAndExtra) {
unset($normalized['context']);
} else {
$normalized['context'] = new \stdClass;
}
}
if (isset($normalized['extra']) && $normalized['extra'] === []) {
if ($this->ignoreEmptyContextAndExtra) {
unset($normalized['extra']);
} else {
$normalized['extra'] = new \stdClass;
}
}
$normalized = $this->normalizeRecord($record);
return $this->toJson($normalized, true) . ($this->appendNewline ? "\n" : '');
}
@@ -115,6 +100,31 @@ class JsonFormatter extends NormalizerFormatter
return $this;
}
/**
* @return array<array|bool|float|int|stdClass|string|null>
*/
protected function normalizeRecord(LogRecord $record): array
{
$normalized = parent::normalizeRecord($record);
if (isset($normalized['context']) && $normalized['context'] === []) {
if ($this->ignoreEmptyContextAndExtra) {
unset($normalized['context']);
} else {
$normalized['context'] = new \stdClass;
}
}
if (isset($normalized['extra']) && $normalized['extra'] === []) {
if ($this->ignoreEmptyContextAndExtra) {
unset($normalized['extra']);
} else {
$normalized['extra'] = new \stdClass;
}
}
return $normalized;
}
/**
* Return a JSON-encoded array of records.
*
@@ -122,7 +132,9 @@ class JsonFormatter extends NormalizerFormatter
*/
protected function formatBatchJson(array $records): string
{
return $this->toJson($this->normalize($records), true);
$formatted = array_map(fn (LogRecord $record) => $this->normalizeRecord($record), $records);
return $this->toJson($formatted, true);
}
/**

View File

@@ -89,7 +89,8 @@ class JsonFormatterTest extends TestCase
$this->getRecord(Level::Warning),
$this->getRecord(Level::Debug),
];
$this->assertEquals(json_encode($records), $formatter->formatBatch($records));
$expected = array_map(fn (LogRecord $record) => json_encode($record->toArray(), JSON_FORCE_OBJECT), $records);
$this->assertEquals('['.implode(',', $expected).']', $formatter->formatBatch($records));
}
/**