NormalizerFormatter.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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 Throwable;
  12. use Monolog\DateTimeImmutable;
  13. use Monolog\Utils;
  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. const SIMPLE_DATE = "Y-m-d\TH:i:sP";
  22. protected $dateFormat;
  23. protected $maxNormalizeDepth = 9;
  24. protected $maxNormalizeItemCount = 1000;
  25. /**
  26. * @param ?string $dateFormat The format of the timestamp: one supported by DateTime::format
  27. */
  28. public function __construct(?string $dateFormat = null)
  29. {
  30. $this->dateFormat = null === $dateFormat ? static::SIMPLE_DATE : $dateFormat;
  31. if (!function_exists('json_encode')) {
  32. throw new \RuntimeException('PHP\'s json extension is required to use Monolog\'s NormalizerFormatter');
  33. }
  34. }
  35. /**
  36. * {@inheritdoc}
  37. */
  38. public function format(array $record)
  39. {
  40. return $this->normalize($record);
  41. }
  42. /**
  43. * {@inheritdoc}
  44. */
  45. public function formatBatch(array $records)
  46. {
  47. foreach ($records as $key => $record) {
  48. $records[$key] = $this->format($record);
  49. }
  50. return $records;
  51. }
  52. /**
  53. * The maximum number of normalization levels to go through
  54. */
  55. public function getMaxNormalizeDepth(): int
  56. {
  57. return $this->maxNormalizeDepth;
  58. }
  59. public function setMaxNormalizeDepth(int $maxNormalizeDepth): self
  60. {
  61. $this->maxNormalizeDepth = $maxNormalizeDepth;
  62. return $this;
  63. }
  64. /**
  65. * The maximum number of items to normalize per level
  66. */
  67. public function getMaxNormalizeItemCount(): int
  68. {
  69. return $this->maxNormalizeItemCount;
  70. }
  71. public function setMaxNormalizeItemCount(int $maxNormalizeItemCount): self
  72. {
  73. $this->maxNormalizeItemCount = $maxNormalizeItemCount;
  74. return $this;
  75. }
  76. /**
  77. * @param mixed $data
  78. * @return int|bool|string|null|array
  79. */
  80. protected function normalize($data, int $depth = 0)
  81. {
  82. if ($depth > $this->maxNormalizeDepth) {
  83. return 'Over ' . $this->maxNormalizeDepth . ' levels deep, aborting normalization';
  84. }
  85. if (null === $data || is_scalar($data)) {
  86. if (is_float($data)) {
  87. if (is_infinite($data)) {
  88. return ($data > 0 ? '' : '-') . 'INF';
  89. }
  90. if (is_nan($data)) {
  91. return 'NaN';
  92. }
  93. }
  94. return $data;
  95. }
  96. if (is_array($data)) {
  97. $normalized = [];
  98. $count = 1;
  99. foreach ($data as $key => $value) {
  100. if ($count++ > $this->maxNormalizeItemCount) {
  101. $normalized['...'] = 'Over ' . $this->maxNormalizeItemCount . ' items ('.count($data).' total), aborting normalization';
  102. break;
  103. }
  104. $normalized[$key] = $this->normalize($value, $depth + 1);
  105. }
  106. return $normalized;
  107. }
  108. if ($data instanceof \DateTimeInterface) {
  109. return $this->formatDate($data);
  110. }
  111. if (is_object($data)) {
  112. if ($data instanceof Throwable) {
  113. return $this->normalizeException($data, $depth);
  114. }
  115. if ($data instanceof \JsonSerializable) {
  116. $value = $data->jsonSerialize();
  117. } elseif (method_exists($data, '__toString')) {
  118. $value = $data->__toString();
  119. } else {
  120. // the rest is normalized by json encoding and decoding it
  121. $encoded = $this->toJson($data, true);
  122. if ($encoded === false) {
  123. $value = 'JSON_ERROR';
  124. } else {
  125. $value = json_decode($encoded, true);
  126. }
  127. }
  128. return [Utils::getClass($data) => $value];
  129. }
  130. if (is_resource($data)) {
  131. return sprintf('[resource(%s)]', get_resource_type($data));
  132. }
  133. return '[unknown('.gettype($data).')]';
  134. }
  135. /**
  136. * @return array
  137. */
  138. protected function normalizeException(Throwable $e, int $depth = 0)
  139. {
  140. $data = [
  141. 'class' => Utils::getClass($e),
  142. 'message' => $e->getMessage(),
  143. 'code' => $e->getCode(),
  144. 'file' => $e->getFile().':'.$e->getLine(),
  145. ];
  146. if ($e instanceof \SoapFault) {
  147. if (isset($e->faultcode)) {
  148. $data['faultcode'] = $e->faultcode;
  149. }
  150. if (isset($e->faultactor)) {
  151. $data['faultactor'] = $e->faultactor;
  152. }
  153. if (isset($e->detail)) {
  154. $data['detail'] = $e->detail;
  155. }
  156. }
  157. $trace = $e->getTrace();
  158. foreach ($trace as $frame) {
  159. if (isset($frame['file'])) {
  160. $data['trace'][] = $frame['file'].':'.$frame['line'];
  161. } elseif (isset($frame['function']) && $frame['function'] === '{closure}') {
  162. // Simplify closures handling
  163. $data['trace'][] = $frame['function'];
  164. } else {
  165. if (isset($frame['args'])) {
  166. // Make sure that objects present as arguments are not serialized nicely but rather only
  167. // as a class name to avoid any unexpected leak of sensitive information
  168. $frame['args'] = array_map(function ($arg) {
  169. if (is_object($arg) && !$arg instanceof \DateTimeInterface) {
  170. return sprintf("[object] (%s)", Utils::getClass($arg));
  171. }
  172. return $arg;
  173. }, $frame['args']);
  174. }
  175. // We should again normalize the frames, because it might contain invalid items
  176. $data['trace'][] = $this->toJson($this->normalize($frame, $depth + 1), true);
  177. }
  178. }
  179. if ($previous = $e->getPrevious()) {
  180. $data['previous'] = $this->normalizeException($previous, $depth + 1);
  181. }
  182. return $data;
  183. }
  184. /**
  185. * Return the JSON representation of a value
  186. *
  187. * @param mixed $data
  188. * @throws \RuntimeException if encoding fails and errors are not ignored
  189. * @return string|bool
  190. */
  191. protected function toJson($data, bool $ignoreErrors = false)
  192. {
  193. // suppress json_encode errors since it's twitchy with some inputs
  194. if ($ignoreErrors) {
  195. return @$this->jsonEncode($data);
  196. }
  197. $json = $this->jsonEncode($data);
  198. if ($json === false) {
  199. $json = $this->handleJsonError(json_last_error(), $data);
  200. }
  201. return $json;
  202. }
  203. /**
  204. * @param mixed $data
  205. * @return string|bool JSON encoded data or false on failure
  206. */
  207. private function jsonEncode($data)
  208. {
  209. return json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRESERVE_ZERO_FRACTION);
  210. }
  211. /**
  212. * Handle a json_encode failure.
  213. *
  214. * If the failure is due to invalid string encoding, try to clean the
  215. * input and encode again. If the second encoding attempt fails, the
  216. * initial error is not encoding related or the input can't be cleaned then
  217. * raise a descriptive exception.
  218. *
  219. * @param int $code return code of json_last_error function
  220. * @param mixed $data data that was meant to be encoded
  221. * @throws \RuntimeException if failure can't be corrected
  222. * @return string JSON encoded data after error correction
  223. */
  224. private function handleJsonError(int $code, $data): string
  225. {
  226. if ($code !== JSON_ERROR_UTF8) {
  227. $this->throwEncodeError($code, $data);
  228. }
  229. if (is_string($data)) {
  230. $this->detectAndCleanUtf8($data);
  231. } elseif (is_array($data)) {
  232. array_walk_recursive($data, [$this, 'detectAndCleanUtf8']);
  233. } else {
  234. $this->throwEncodeError($code, $data);
  235. }
  236. $json = $this->jsonEncode($data);
  237. if ($json === false) {
  238. $this->throwEncodeError(json_last_error(), $data);
  239. }
  240. return $json;
  241. }
  242. /**
  243. * Throws an exception according to a given code with a customized message
  244. *
  245. * @param int $code return code of json_last_error function
  246. * @param mixed $data data that was meant to be encoded
  247. * @throws \RuntimeException
  248. */
  249. private function throwEncodeError(int $code, $data)
  250. {
  251. switch ($code) {
  252. case JSON_ERROR_DEPTH:
  253. $msg = 'Maximum stack depth exceeded';
  254. break;
  255. case JSON_ERROR_STATE_MISMATCH:
  256. $msg = 'Underflow or the modes mismatch';
  257. break;
  258. case JSON_ERROR_CTRL_CHAR:
  259. $msg = 'Unexpected control character found';
  260. break;
  261. case JSON_ERROR_UTF8:
  262. $msg = 'Malformed UTF-8 characters, possibly incorrectly encoded';
  263. break;
  264. default:
  265. $msg = 'Unknown error';
  266. }
  267. throw new \RuntimeException('JSON encoding failed: '.$msg.'. Encoding: '.var_export($data, true));
  268. }
  269. /**
  270. * Detect invalid UTF-8 string characters and convert to valid UTF-8.
  271. *
  272. * Valid UTF-8 input will be left unmodified, but strings containing
  273. * invalid UTF-8 codepoints will be reencoded as UTF-8 with an assumed
  274. * original encoding of ISO-8859-15. This conversion may result in
  275. * incorrect output if the actual encoding was not ISO-8859-15, but it
  276. * will be clean UTF-8 output and will not rely on expensive and fragile
  277. * detection algorithms.
  278. *
  279. * Function converts the input in place in the passed variable so that it
  280. * can be used as a callback for array_walk_recursive.
  281. *
  282. * @param mixed &$data Input to check and convert if needed
  283. * @private
  284. */
  285. public function detectAndCleanUtf8(&$data)
  286. {
  287. if (is_string($data) && !preg_match('//u', $data)) {
  288. $data = preg_replace_callback(
  289. '/[\x80-\xFF]+/',
  290. function ($m) {
  291. return utf8_encode($m[0]);
  292. },
  293. $data
  294. );
  295. $data = str_replace(
  296. ['¤', '¦', '¨', '´', '¸', '¼', '½', '¾'],
  297. ['€', 'Š', 'š', 'Ž', 'ž', 'Œ', 'œ', 'Ÿ'],
  298. $data
  299. );
  300. }
  301. }
  302. protected function formatDate(\DateTimeInterface $date)
  303. {
  304. // in case the date format isn't custom then we defer to the custom DateTimeImmutable
  305. // formatting logic, which will pick the right format based on whether useMicroseconds is on
  306. if ($this->dateFormat === self::SIMPLE_DATE && $date instanceof DateTimeImmutable) {
  307. return (string) $date;
  308. }
  309. return $date->format($this->dateFormat);
  310. }
  311. }