1
0
Fork 0

Fix object handling inside log arrays

This commit is contained in:
Philipp Holzer 2021-03-28 21:50:32 +02:00
parent cefeb02517
commit b61b3cb182
No known key found for this signature in database
GPG key ID: 9A28B7D4FF5667BD
4 changed files with 45 additions and 4 deletions

View file

@ -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}
*/

View file

@ -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;

View file

@ -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;
}

View file

@ -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());
}
}