mirror of
https://github.com/Seldaek/monolog.git
synced 2025-07-31 18:30:15 +02:00
JsonFormatter: add option to ignore empty context
and extra
fields
Similar to efe572cb10
.
This commit is contained in:
@@ -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" : '');
|
||||
|
@@ -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
|
||||
);
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user