diff --git a/src/Util/Logger/AbstractLogger.php b/src/Util/Logger/AbstractLogger.php index 4d653ae9b..110a80687 100644 --- a/src/Util/Logger/AbstractLogger.php +++ b/src/Util/Logger/AbstractLogger.php @@ -103,6 +103,28 @@ abstract class AbstractLogger implements LoggerInterface return strtr($message, $replace); } + /** + * JSON Encodes an complete array including objects with "__toString()" methods + * + * @param array $input an Input Array to encode + * + * @return false|string The json encoded output of the array + */ + protected function jsonEncodeArray(array $input) + { + $output = []; + + foreach ($input as $key => $value) { + if (method_exists($value, '__toString')) { + $output[$key] = $value->__toString(); + } else { + $output[$key] = $value; + } + } + + return @json_encode($output); + } + /** * {@inheritdoc} */ diff --git a/src/Util/Logger/StreamLogger.php b/src/Util/Logger/StreamLogger.php index 035e7ecee..5912e7090 100644 --- a/src/Util/Logger/StreamLogger.php +++ b/src/Util/Logger/StreamLogger.php @@ -161,8 +161,8 @@ class StreamLogger extends AbstractLogger $logMessage .= $this->channel . ' '; $logMessage .= '[' . strtoupper($level) . ']: '; $logMessage .= $this->psrInterpolate($message, $context) . ' '; - $logMessage .= @json_encode($context) . ' - '; - $logMessage .= @json_encode($record); + $logMessage .= $this->jsonEncodeArray($context) . ' - '; + $logMessage .= $this->jsonEncodeArray($record); $logMessage .= PHP_EOL; return $logMessage; diff --git a/src/Util/Logger/SyslogLogger.php b/src/Util/Logger/SyslogLogger.php index 101baad38..ae39ad958 100644 --- a/src/Util/Logger/SyslogLogger.php +++ b/src/Util/Logger/SyslogLogger.php @@ -195,8 +195,8 @@ class SyslogLogger extends AbstractLogger $logMessage .= $this->channel . ' '; $logMessage .= '[' . $this->logToString[$level] . ']: '; $logMessage .= $this->psrInterpolate($message, $context) . ' '; - $logMessage .= @json_encode($context) . ' - '; - $logMessage .= @json_encode($record); + $logMessage .= $this->jsonEncodeArray($context) . ' - '; + $logMessage .= $this->jsonEncodeArray($record); return $logMessage; } diff --git a/tests/src/Util/Logger/AbstractLoggerTest.php b/tests/src/Util/Logger/AbstractLoggerTest.php index 33bf23561..e9f183081 100644 --- a/tests/src/Util/Logger/AbstractLoggerTest.php +++ b/tests/src/Util/Logger/AbstractLoggerTest.php @@ -159,4 +159,23 @@ abstract class AbstractLoggerTest extends MockedTest self::assertContains(@json_encode($context), $text); } + + /** + * Test a message with an exception + */ + public function testExceptionHandling() + { + $e = new \Exception("Test String", 123); + $eFollowUp = new \Exception("FollowUp", 456, $e); + + $assertion = $eFollowUp->__toString(); + + $logger = $this->getInstance(); + $logger->alert('test', ['e' => $eFollowUp]); + $text = $this->getContent(); + + self::assertLogline($text); + + self::assertContains(@json_encode($assertion), $this->getContent()); + } }