diff --git a/src/Monolog/Formatter/JsonFormatter.php b/src/Monolog/Formatter/JsonFormatter.php index 238039f4e..35bcc1679 100644 --- a/src/Monolog/Formatter/JsonFormatter.php +++ b/src/Monolog/Formatter/JsonFormatter.php @@ -74,22 +74,7 @@ public function isAppendingNewlines(): bool */ 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 @@ public function includeStacktraces(bool $include = true): self return $this; } + /** + * @return array + */ + 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 @@ public function includeStacktraces(bool $include = true): self */ 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); } /** diff --git a/tests/Monolog/Formatter/JsonFormatterTest.php b/tests/Monolog/Formatter/JsonFormatterTest.php index 9ce91c696..3e1cee28c 100644 --- a/tests/Monolog/Formatter/JsonFormatterTest.php +++ b/tests/Monolog/Formatter/JsonFormatterTest.php @@ -89,7 +89,8 @@ public function testFormatBatch() $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)); } /**