PsrLogMessageProcessor.php 2.8 KB

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