NormalizerFormatter.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. <?php
  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 Exception;
  12. use Monolog\Utils;
  13. /**
  14. * Normalizes incoming records to remove objects/resources so it's easier to dump to various targets
  15. *
  16. * @author Jordi Boggiano <j.boggiano@seld.be>
  17. */
  18. class NormalizerFormatter implements FormatterInterface
  19. {
  20. const SIMPLE_DATE = "Y-m-d H:i:s";
  21. protected $dateFormat;
  22. /**
  23. * @param string $dateFormat The format of the timestamp: one supported by DateTime::format
  24. */
  25. public function __construct($dateFormat = null)
  26. {
  27. $this->dateFormat = $dateFormat ?: static::SIMPLE_DATE;
  28. if (!function_exists('json_encode')) {
  29. throw new \RuntimeException('PHP\'s json extension is required to use Monolog\'s NormalizerFormatter');
  30. }
  31. }
  32. /**
  33. * {@inheritdoc}
  34. */
  35. public function format(array $record)
  36. {
  37. return $this->normalize($record);
  38. }
  39. /**
  40. * {@inheritdoc}
  41. */
  42. public function formatBatch(array $records)
  43. {
  44. foreach ($records as $key => $record) {
  45. $records[$key] = $this->format($record);
  46. }
  47. return $records;
  48. }
  49. protected function normalize($data, $depth = 0)
  50. {
  51. if ($depth > 9) {
  52. return 'Over 9 levels deep, aborting normalization';
  53. }
  54. if (null === $data || is_scalar($data)) {
  55. if (is_float($data)) {
  56. if (is_infinite($data)) {
  57. return ($data > 0 ? '' : '-') . 'INF';
  58. }
  59. if (is_nan($data)) {
  60. return 'NaN';
  61. }
  62. }
  63. return $data;
  64. }
  65. if (is_array($data)) {
  66. $normalized = array();
  67. $count = 1;
  68. foreach ($data as $key => $value) {
  69. if ($count++ > 1000) {
  70. $normalized['...'] = 'Over 1000 items ('.count($data).' total), aborting normalization';
  71. break;
  72. }
  73. $normalized[$key] = $this->normalize($value, $depth+1);
  74. }
  75. return $normalized;
  76. }
  77. if ($data instanceof \DateTime) {
  78. return $data->format($this->dateFormat);
  79. }
  80. if (is_object($data)) {
  81. // TODO 2.0 only check for Throwable
  82. if ($data instanceof Exception || (PHP_VERSION_ID > 70000 && $data instanceof \Throwable)) {
  83. return $this->normalizeException($data);
  84. }
  85. // non-serializable objects that implement __toString stringified
  86. if (method_exists($data, '__toString') && !$data instanceof \JsonSerializable) {
  87. $value = $data->__toString();
  88. } else {
  89. // the rest is json-serialized in some way
  90. $value = $this->toJson($data, true);
  91. }
  92. return sprintf("[object] (%s: %s)", Utils::getClass($data), $value);
  93. }
  94. if (is_resource($data)) {
  95. return sprintf('[resource] (%s)', get_resource_type($data));
  96. }
  97. return '[unknown('.gettype($data).')]';
  98. }
  99. protected function normalizeException($e)
  100. {
  101. // TODO 2.0 only check for Throwable
  102. if (!$e instanceof Exception && !$e instanceof \Throwable) {
  103. throw new \InvalidArgumentException('Exception/Throwable expected, got '.gettype($e).' / '.Utils::getClass($e));
  104. }
  105. $data = array(
  106. 'class' => Utils::getClass($e),
  107. 'message' => $e->getMessage(),
  108. 'code' => $e->getCode(),
  109. 'file' => $e->getFile().':'.$e->getLine(),
  110. );
  111. if ($e instanceof \SoapFault) {
  112. if (isset($e->faultcode)) {
  113. $data['faultcode'] = $e->faultcode;
  114. }
  115. if (isset($e->faultactor)) {
  116. $data['faultactor'] = $e->faultactor;
  117. }
  118. if (isset($e->detail)) {
  119. $data['detail'] = $e->detail;
  120. }
  121. }
  122. $trace = $e->getTrace();
  123. foreach ($trace as $frame) {
  124. if (isset($frame['file'])) {
  125. $data['trace'][] = $frame['file'].':'.$frame['line'];
  126. } else {
  127. $data['trace'][] = (!empty($frame['class']) ? $frame['class'].$frame['type'] : '').$frame['function'];
  128. }
  129. }
  130. if ($previous = $e->getPrevious()) {
  131. $data['previous'] = $this->normalizeException($previous);
  132. }
  133. return $data;
  134. }
  135. /**
  136. * Return the JSON representation of a value
  137. *
  138. * @param mixed $data
  139. * @param bool $ignoreErrors
  140. * @throws \RuntimeException if encoding fails and errors are not ignored
  141. * @return string
  142. */
  143. protected function toJson($data, $ignoreErrors = false)
  144. {
  145. // suppress json_encode errors since it's twitchy with some inputs
  146. if ($ignoreErrors) {
  147. return @$this->jsonEncode($data);
  148. }
  149. $json = $this->jsonEncode($data);
  150. if ($json === false) {
  151. $json = $this->handleJsonError(json_last_error(), $data);
  152. }
  153. return $json;
  154. }
  155. /**
  156. * @param mixed $data
  157. * @return string JSON encoded data or null on failure
  158. */
  159. private function jsonEncode($data)
  160. {
  161. if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
  162. return json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
  163. }
  164. return json_encode($data);
  165. }
  166. /**
  167. * Handle a json_encode failure.
  168. *
  169. * If the failure is due to invalid string encoding, try to clean the
  170. * input and encode again. If the second encoding attempt fails, the
  171. * inital error is not encoding related or the input can't be cleaned then
  172. * raise a descriptive exception.
  173. *
  174. * @param int $code return code of json_last_error function
  175. * @param mixed $data data that was meant to be encoded
  176. * @throws \RuntimeException if failure can't be corrected
  177. * @return string JSON encoded data after error correction
  178. */
  179. private function handleJsonError($code, $data)
  180. {
  181. if ($code !== JSON_ERROR_UTF8) {
  182. $this->throwEncodeError($code, $data);
  183. }
  184. if (is_string($data)) {
  185. $this->detectAndCleanUtf8($data);
  186. } elseif (is_array($data)) {
  187. array_walk_recursive($data, array($this, 'detectAndCleanUtf8'));
  188. } else {
  189. $this->throwEncodeError($code, $data);
  190. }
  191. $json = $this->jsonEncode($data);
  192. if ($json === false) {
  193. $this->throwEncodeError(json_last_error(), $data);
  194. }
  195. return $json;
  196. }
  197. /**
  198. * Throws an exception according to a given code with a customized message
  199. *
  200. * @param int $code return code of json_last_error function
  201. * @param mixed $data data that was meant to be encoded
  202. * @throws \RuntimeException
  203. */
  204. private function throwEncodeError($code, $data)
  205. {
  206. switch ($code) {
  207. case JSON_ERROR_DEPTH:
  208. $msg = 'Maximum stack depth exceeded';
  209. break;
  210. case JSON_ERROR_STATE_MISMATCH:
  211. $msg = 'Underflow or the modes mismatch';
  212. break;
  213. case JSON_ERROR_CTRL_CHAR:
  214. $msg = 'Unexpected control character found';
  215. break;
  216. case JSON_ERROR_UTF8:
  217. $msg = 'Malformed UTF-8 characters, possibly incorrectly encoded';
  218. break;
  219. default:
  220. $msg = 'Unknown error';
  221. }
  222. throw new \RuntimeException('JSON encoding failed: '.$msg.'. Encoding: '.var_export($data, true));
  223. }
  224. /**
  225. * Detect invalid UTF-8 string characters and convert to valid UTF-8.
  226. *
  227. * Valid UTF-8 input will be left unmodified, but strings containing
  228. * invalid UTF-8 codepoints will be reencoded as UTF-8 with an assumed
  229. * original encoding of ISO-8859-15. This conversion may result in
  230. * incorrect output if the actual encoding was not ISO-8859-15, but it
  231. * will be clean UTF-8 output and will not rely on expensive and fragile
  232. * detection algorithms.
  233. *
  234. * Function converts the input in place in the passed variable so that it
  235. * can be used as a callback for array_walk_recursive.
  236. *
  237. * @param mixed &$data Input to check and convert if needed
  238. * @private
  239. */
  240. public function detectAndCleanUtf8(&$data)
  241. {
  242. if (is_string($data) && !preg_match('//u', $data)) {
  243. $data = preg_replace_callback(
  244. '/[\x80-\xFF]+/',
  245. function ($m) { return utf8_encode($m[0]); },
  246. $data
  247. );
  248. $data = str_replace(
  249. array('¤', '¦', '¨', '´', '¸', '¼', '½', '¾'),
  250. array('€', 'Š', 'š', 'Ž', 'ž', 'Œ', 'œ', 'Ÿ'),
  251. $data
  252. );
  253. }
  254. }
  255. }