1<?php declare(strict_types=1); 2 3/* 4 * This file is part of the Monolog package. 5 * 6 * (c) Jordi Boggiano <j.boggiano@seld.be> 7 * 8 * For the full copyright and license information, please view the LICENSE 9 * file that was distributed with this source code. 10 */ 11 12namespace Monolog\Processor; 13 14use Monolog\Utils; 15 16/** 17 * Processes a record's message according to PSR-3 rules 18 * 19 * It replaces {foo} with the value from $context['foo'] 20 * 21 * @author Jordi Boggiano <j.boggiano@seld.be> 22 */ 23class PsrLogMessageProcessor implements ProcessorInterface 24{ 25 public const SIMPLE_DATE = "Y-m-d\TH:i:s.uP"; 26 27 /** @var string|null */ 28 private $dateFormat; 29 30 /** @var bool */ 31 private $removeUsedContextFields; 32 33 /** 34 * @param string|null $dateFormat The format of the timestamp: one supported by DateTime::format 35 * @param bool $removeUsedContextFields If set to true the fields interpolated into message gets unset 36 */ 37 public function __construct(?string $dateFormat = null, bool $removeUsedContextFields = false) 38 { 39 $this->dateFormat = $dateFormat; 40 $this->removeUsedContextFields = $removeUsedContextFields; 41 } 42 43 /** 44 * {@inheritDoc} 45 */ 46 public function __invoke(array $record): array 47 { 48 if (false === strpos($record['message'], '{')) { 49 return $record; 50 } 51 52 $replacements = []; 53 foreach ($record['context'] as $key => $val) { 54 $placeholder = '{' . $key . '}'; 55 if (strpos($record['message'], $placeholder) === false) { 56 continue; 57 } 58 59 if (is_null($val) || is_scalar($val) || (is_object($val) && method_exists($val, "__toString"))) { 60 $replacements[$placeholder] = $val; 61 } elseif ($val instanceof \DateTimeInterface) { 62 if (!$this->dateFormat && $val instanceof \Monolog\DateTimeImmutable) { 63 // handle monolog dates using __toString if no specific dateFormat was asked for 64 // so that it follows the useMicroseconds flag 65 $replacements[$placeholder] = (string) $val; 66 } else { 67 $replacements[$placeholder] = $val->format($this->dateFormat ?: static::SIMPLE_DATE); 68 } 69 } elseif (is_object($val)) { 70 $replacements[$placeholder] = '[object '.Utils::getClass($val).']'; 71 } elseif (is_array($val)) { 72 $replacements[$placeholder] = 'array'.Utils::jsonEncode($val, null, true); 73 } else { 74 $replacements[$placeholder] = '['.gettype($val).']'; 75 } 76 77 if ($this->removeUsedContextFields) { 78 unset($record['context'][$key]); 79 } 80 } 81 82 $record['message'] = strtr($record['message'], $replacements); 83 84 return $record; 85 } 86} 87