2
0
Эх сурвалжийг харах

Serialize exceptions in a minimalistic way in the LineFormatter

Jordi Boggiano 13 жил өмнө
parent
commit
eaf2b07120

+ 4 - 0
src/Monolog/Formatter/LineFormatter.php

@@ -72,6 +72,10 @@ class LineFormatter extends NormalizerFormatter
             return var_export($data, true);
         }
 
+        if ($data instanceof \Exception) {
+            return '[object] ('.get_class($data).': '.$data->getMessage().' at '.$data->getFile().':'.$data->getLine().')';
+        }
+
         return parent::normalize($data);
     }
 

+ 15 - 0
tests/Monolog/Formatter/LineFormatterTest.php

@@ -90,6 +90,21 @@ class LineFormatterTest extends \PHPUnit_Framework_TestCase
         $this->assertEquals('['.date('Y-m-d').'] meh.ERROR: foobar [] {"foo":"[object] (Monolog\\\\Formatter\\\\TestFoo: {\\"foo\\":\\"foo\\"})","bar":"[object] (Monolog\\\\Formatter\\\\TestBar: {})","baz":[],"res":"[resource]"}'."\n", $message);
     }
 
+    public function testDefFormatWithException()
+    {
+        $formatter = new LineFormatter(null, 'Y-m-d');
+        $message = $formatter->format(array(
+            'level_name' => 'CRITICAL',
+            'channel' => 'core',
+            'context' => array('exception' => new \RuntimeException('Foo')),
+            'datetime' => new \DateTime,
+            'extra' => array(),
+            'message' => 'foobar',
+        ));
+
+        $this->assertEquals('['.date('Y-m-d').'] core.CRITICAL: foobar {"exception":"[object] (RuntimeException: Foo at '.substr(json_encode(__FILE__), 1, -1).':'.(__LINE__-6).')"} []'."\n", $message);
+    }
+
     public function testBatchFormat()
     {
         $formatter = new LineFormatter(null, 'Y-m-d');