NormalizerFormatter.php 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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\Formatter;
  11. use Monolog\DateTimeImmutable;
  12. use Monolog\Utils;
  13. use Throwable;
  14. /**
  15. * Normalizes incoming records to remove objects/resources so it's easier to dump to various targets
  16. *
  17. * @author Jordi Boggiano <j.boggiano@seld.be>
  18. */
  19. class NormalizerFormatter implements FormatterInterface
  20. {
  21. public const SIMPLE_DATE = "Y-m-d\TH:i:sP";
  22. protected $dateFormat;
  23. protected $maxNormalizeDepth = 9;
  24. protected $maxNormalizeItemCount = 1000;
  25. private $jsonEncodeOptions = Utils::DEFAULT_JSON_FLAGS;
  26. /**
  27. * @param string|null $dateFormat The format of the timestamp: one supported by DateTime::format
  28. */
  29. public function __construct(?string $dateFormat = null)
  30. {
  31. $this->dateFormat = null === $dateFormat ? static::SIMPLE_DATE : $dateFormat;
  32. if (!function_exists('json_encode')) {
  33. throw new \RuntimeException('PHP\'s json extension is required to use Monolog\'s NormalizerFormatter');
  34. }
  35. }
  36. /**
  37. * {@inheritdoc}
  38. */
  39. public function format(array $record)
  40. {
  41. return $this->normalize($record);
  42. }
  43. /**
  44. * {@inheritdoc}
  45. */
  46. public function formatBatch(array $records)
  47. {
  48. foreach ($records as $key => $record) {
  49. $records[$key] = $this->format($record);
  50. }
  51. return $records;
  52. }
  53. /**
  54. * The maximum number of normalization levels to go through
  55. */
  56. public function getMaxNormalizeDepth(): int
  57. {
  58. return $this->maxNormalizeDepth;
  59. }
  60. public function setMaxNormalizeDepth(int $maxNormalizeDepth): self
  61. {
  62. $this->maxNormalizeDepth = $maxNormalizeDepth;
  63. return $this;
  64. }
  65. /**
  66. * The maximum number of items to normalize per level
  67. */
  68. public function getMaxNormalizeItemCount(): int
  69. {
  70. return $this->maxNormalizeItemCount;
  71. }
  72. public function setMaxNormalizeItemCount(int $maxNormalizeItemCount): self
  73. {
  74. $this->maxNormalizeItemCount = $maxNormalizeItemCount;
  75. return $this;
  76. }
  77. /**
  78. * Enables `json_encode` pretty print.
  79. */
  80. public function setJsonPrettyPrint(bool $enable): self
  81. {
  82. if ($enable) {
  83. $this->jsonEncodeOptions |= JSON_PRETTY_PRINT;
  84. } else {
  85. $this->jsonEncodeOptions ^= JSON_PRETTY_PRINT;
  86. }
  87. return $this;
  88. }
  89. /**
  90. * @param mixed $data
  91. * @return int|bool|string|null|array
  92. */
  93. protected function normalize($data, int $depth = 0)
  94. {
  95. if ($depth > $this->maxNormalizeDepth) {
  96. return 'Over ' . $this->maxNormalizeDepth . ' levels deep, aborting normalization';
  97. }
  98. if (null === $data || is_scalar($data)) {
  99. if (is_float($data)) {
  100. if (is_infinite($data)) {
  101. return ($data > 0 ? '' : '-') . 'INF';
  102. }
  103. if (is_nan($data)) {
  104. return 'NaN';
  105. }
  106. }
  107. return $data;
  108. }
  109. if (is_array($data)) {
  110. $normalized = [];
  111. $count = 1;
  112. foreach ($data as $key => $value) {
  113. if ($count++ > $this->maxNormalizeItemCount) {
  114. $normalized['...'] = 'Over ' . $this->maxNormalizeItemCount . ' items ('.count($data).' total), aborting normalization';
  115. break;
  116. }
  117. $normalized[$key] = $this->normalize($value, $depth + 1);
  118. }
  119. return $normalized;
  120. }
  121. if ($data instanceof \DateTimeInterface) {
  122. return $this->formatDate($data);
  123. }
  124. if (is_object($data)) {
  125. if ($data instanceof Throwable) {
  126. return $this->normalizeException($data, $depth);
  127. }
  128. if ($data instanceof \JsonSerializable) {
  129. $value = $data->jsonSerialize();
  130. } elseif (method_exists($data, '__toString')) {
  131. $value = $data->__toString();
  132. } else {
  133. // the rest is normalized by json encoding and decoding it
  134. $encoded = $this->toJson($data, true);
  135. if ($encoded === false) {
  136. $value = 'JSON_ERROR';
  137. } else {
  138. $value = json_decode($encoded, true);
  139. }
  140. }
  141. return [Utils::getClass($data) => $value];
  142. }
  143. if (is_resource($data)) {
  144. return sprintf('[resource(%s)]', get_resource_type($data));
  145. }
  146. return '[unknown('.gettype($data).')]';
  147. }
  148. /**
  149. * @return array
  150. */
  151. protected function normalizeException(Throwable $e, int $depth = 0)
  152. {
  153. if ($e instanceof \JsonSerializable) {
  154. return (array) $e->jsonSerialize();
  155. }
  156. $data = [
  157. 'class' => Utils::getClass($e),
  158. 'message' => $e->getMessage(),
  159. 'code' => (int) $e->getCode(),
  160. 'file' => $e->getFile().':'.$e->getLine(),
  161. ];
  162. if ($e instanceof \SoapFault) {
  163. if (isset($e->faultcode)) {
  164. $data['faultcode'] = $e->faultcode;
  165. }
  166. if (isset($e->faultactor)) {
  167. $data['faultactor'] = $e->faultactor;
  168. }
  169. if (isset($e->detail)) {
  170. if (is_string($e->detail)) {
  171. $data['detail'] = $e->detail;
  172. } elseif (is_object($e->detail) || is_array($e->detail)) {
  173. $data['detail'] = $this->toJson($e->detail, true);
  174. }
  175. }
  176. }
  177. $trace = $e->getTrace();
  178. foreach ($trace as $frame) {
  179. if (isset($frame['file'])) {
  180. $data['trace'][] = $frame['file'].':'.$frame['line'];
  181. }
  182. }
  183. if ($previous = $e->getPrevious()) {
  184. $data['previous'] = $this->normalizeException($previous, $depth + 1);
  185. }
  186. return $data;
  187. }
  188. /**
  189. * Return the JSON representation of a value
  190. *
  191. * @param mixed $data
  192. * @throws \RuntimeException if encoding fails and errors are not ignored
  193. * @return string if encoding fails and ignoreErrors is true 'null' is returned
  194. */
  195. protected function toJson($data, bool $ignoreErrors = false): string
  196. {
  197. return Utils::jsonEncode($data, $this->jsonEncodeOptions, $ignoreErrors);
  198. }
  199. protected function formatDate(\DateTimeInterface $date)
  200. {
  201. // in case the date format isn't custom then we defer to the custom DateTimeImmutable
  202. // formatting logic, which will pick the right format based on whether useMicroseconds is on
  203. if ($this->dateFormat === self::SIMPLE_DATE && $date instanceof DateTimeImmutable) {
  204. return (string) $date;
  205. }
  206. return $date->format($this->dateFormat);
  207. }
  208. public function addJsonEncodeOption($option)
  209. {
  210. $this->jsonEncodeOptions |= $option;
  211. }
  212. public function removeJsonEncodeOption($option)
  213. {
  214. $this->jsonEncodeOptions ^= $option;
  215. }
  216. }