Przeglądaj źródła

JsonFormatter: add option to ignore empty `context` and `extra` fields

Similar to efe572cb1074.
Gabriel Caruso 5 lat temu
rodzic
commit
6038dcb21c

+ 14 - 3
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" : '');

+ 19 - 0
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
+        );
+    }
 }