From a0406bf8dd17b7acf537a2da3e52dcb08c651665 Mon Sep 17 00:00:00 2001 From: Piers Warmers Date: Tue, 14 Mar 2017 18:07:57 +1100 Subject: [PATCH] Handle DateTime objects in formatted messages (#940) * Handle DateTime objects in formatted meessages * Use interface to catch both DateTime and DateTimeImmutable * Maintain formatting standards. * Visibility to private. --- .../Processor/PsrLogMessageProcessor.php | 14 ++++++++++++++ .../Processor/PsrLogMessageProcessorTest.php | 17 +++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/src/Monolog/Processor/PsrLogMessageProcessor.php b/src/Monolog/Processor/PsrLogMessageProcessor.php index b9a00a40..80784038 100644 --- a/src/Monolog/Processor/PsrLogMessageProcessor.php +++ b/src/Monolog/Processor/PsrLogMessageProcessor.php @@ -20,6 +20,18 @@ namespace Monolog\Processor; */ class PsrLogMessageProcessor { + const SIMPLE_DATE = "Y-m-d\TH:i:sP"; + + private $dateFormat; + + /** + * @param string $dateFormat The format of the timestamp: one supported by DateTime::format + */ + public function __construct(string $dateFormat = null) + { + $this->dateFormat = null === $dateFormat ? static::SIMPLE_DATE : $dateFormat; + } + /** * @param array $record * @return array @@ -34,6 +46,8 @@ class PsrLogMessageProcessor foreach ($record['context'] as $key => $val) { if (is_null($val) || is_scalar($val) || (is_object($val) && method_exists($val, "__toString"))) { $replacements['{'.$key.'}'] = $val; + } elseif ($val instanceof \DateTimeInterface) { + $replacements['{'.$key.'}'] = $val->format($this->dateFormat); } elseif (is_object($val)) { $replacements['{'.$key.'}'] = '[object '.get_class($val).']'; } else { diff --git a/tests/Monolog/Processor/PsrLogMessageProcessorTest.php b/tests/Monolog/Processor/PsrLogMessageProcessorTest.php index 77db8425..884c9a1e 100644 --- a/tests/Monolog/Processor/PsrLogMessageProcessorTest.php +++ b/tests/Monolog/Processor/PsrLogMessageProcessorTest.php @@ -27,8 +27,24 @@ class PsrLogMessageProcessorTest extends \PHPUnit_Framework_TestCase $this->assertEquals($expected, $message['message']); } + public function testCustomDateFormat() + { + $format = "Y-m-d"; + $date = new \DateTime(); + + $proc = new PsrLogMessageProcessor($format); + + $message = $proc([ + 'message' => '{foo}', + 'context' => ['foo' => $date], + ]); + $this->assertEquals($date->format($format), $message['message']); + } + public function getPairs() { + $date = new \DateTime(); + return [ ['foo', 'foo'], ['3', '3'], @@ -36,6 +52,7 @@ class PsrLogMessageProcessorTest extends \PHPUnit_Framework_TestCase [null, ''], [true, '1'], [false, ''], + [$date, $date->format(PsrLogMessageProcessor::SIMPLE_DATE)], [new \stdClass, '[object stdClass]'], [[], '[array]'], ];