From 6038dcb21ce15210decec251066834b44a813b59 Mon Sep 17 00:00:00 2001 From: Gabriel Caruso Date: Wed, 1 Apr 2020 05:03:52 +0200 Subject: [PATCH] JsonFormatter: add option to ignore empty `context` and `extra` fields Similar to efe572cb1074. --- src/Monolog/Formatter/JsonFormatter.php | 17 ++++++++++++++--- tests/Monolog/Formatter/JsonFormatterTest.php | 19 +++++++++++++++++++ 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/src/Monolog/Formatter/JsonFormatter.php b/src/Monolog/Formatter/JsonFormatter.php index 6b6dc6af..454b6976 100644 --- a/src/Monolog/Formatter/JsonFormatter.php +++ b/src/Monolog/Formatter/JsonFormatter.php @@ -28,16 +28,18 @@ class JsonFormatter extends NormalizerFormatter protected $batchMode; protected $appendNewline; + protected $ignoreEmptyContextAndExtra; /** * @var bool */ protected $includeStacktraces = false; - public function __construct(int $batchMode = self::BATCH_MODE_JSON, bool $appendNewline = true) + public function __construct(int $batchMode = self::BATCH_MODE_JSON, bool $appendNewline = true, bool $ignoreEmptyContextAndExtra = false) { $this->batchMode = $batchMode; $this->appendNewline = $appendNewline; + $this->ignoreEmptyContextAndExtra = $ignoreEmptyContextAndExtra; } /** @@ -68,11 +70,20 @@ class JsonFormatter extends NormalizerFormatter public function format(array $record): string { $normalized = $this->normalize($record); + if (isset($normalized['context']) && $normalized['context'] === []) { - $normalized['context'] = new \stdClass; + if ($this->ignoreEmptyContextAndExtra) { + unset($normalized['context']); + } else { + $normalized['context'] = new \stdClass; + } } if (isset($normalized['extra']) && $normalized['extra'] === []) { - $normalized['extra'] = new \stdClass; + if ($this->ignoreEmptyContextAndExtra) { + unset($normalized['extra']); + } else { + $normalized['extra'] = new \stdClass; + } } return $this->toJson($normalized, true) . ($this->appendNewline ? "\n" : ''); diff --git a/tests/Monolog/Formatter/JsonFormatterTest.php b/tests/Monolog/Formatter/JsonFormatterTest.php index afcdb13a..dbc2a08c 100644 --- a/tests/Monolog/Formatter/JsonFormatterTest.php +++ b/tests/Monolog/Formatter/JsonFormatterTest.php @@ -295,4 +295,23 @@ class JsonFormatterTest extends TestCase $this->assertCount(1001, $res['context'][0]); $this->assertEquals('Over 1000 items (2000 total), aborting normalization', $res['context'][0]['...']); } + + public function testEmptyContextAndExtraFieldsCanBeIgnored() + { + $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, true, true); + + $record = $formatter->format(array( + 'level' => 100, + 'level_name' => 'DEBUG', + 'channel' => 'test', + 'message' => 'Testing', + 'context' => array(), + 'extra' => array(), + )); + + $this->assertSame( + '{"level":100,"level_name":"DEBUG","channel":"test","message":"Testing"}'."\n", + $record + ); + } }