2
0

NormalizerFormatter.php 7.7 KB

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