Просмотр исходного кода

Store native BSON types as-is in the MongoDB formatter (#1620)

Gemma Lynn 3 лет назад
Родитель
Сommit
b39a394c05

+ 2 - 1
src/Monolog/Formatter/MongoDBFormatter.php

@@ -11,6 +11,7 @@
 
 namespace Monolog\Formatter;
 
+use MongoDB\BSON\Type;
 use MongoDB\BSON\UTCDateTime;
 use Monolog\Utils;
 
@@ -85,7 +86,7 @@ class MongoDBFormatter implements FormatterInterface
                 $array[$name] = $this->formatException($value, $nestingLevel + 1);
             } elseif (is_array($value)) {
                 $array[$name] = $this->formatArray($value, $nestingLevel + 1);
-            } elseif (is_object($value)) {
+            } elseif (is_object($value) && !$value instanceof Type) {
                 $array[$name] = $this->formatObject($value, $nestingLevel + 1);
             }
         }

+ 30 - 0
tests/Monolog/Formatter/MongoDBFormatterTest.php

@@ -11,6 +11,9 @@
 
 namespace Monolog\Formatter;
 
+use MongoDB\BSON\ObjectId;
+use MongoDB\BSON\Regex;
+use MongoDB\BSON\UTCDateTime;
 use Monolog\Logger;
 
 /**
@@ -259,4 +262,31 @@ class MongoDBFormatterTest extends \PHPUnit\Framework\TestCase
         $this->assertEquals(987, $formattedRecord['context']['nest2']['code']);
         $this->assertEquals('[...]', $formattedRecord['context']['nest2']['trace']);
     }
+
+    public function testBsonTypes()
+    {
+        $record = [
+            'message' => 'some log message',
+            'context' => [
+                'objectid' => new ObjectId(),
+                'nest' => [
+                    'timestamp' => new UTCDateTime(),
+                    'regex' => new Regex('pattern'),
+                ],
+            ],
+            'level' => Logger::WARNING,
+            'level_name' => Logger::getLevelName(Logger::WARNING),
+            'channel' => 'test',
+            'datetime' => new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'),
+            'extra' => [],
+        ];
+
+        $formatter = new MongoDBFormatter();
+        $formattedRecord = $formatter->format($record);
+
+        $this->assertInstanceOf(ObjectId::class, $formattedRecord['context']['objectid']);
+        $this->assertInstanceOf(UTCDateTime::class, $formattedRecord['context']['nest']['timestamp']);
+        $this->assertInstanceOf(Regex::class, $formattedRecord['context']['nest']['regex']);
+
+    }
 }