2
0

NormalizerFormatter.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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. } elseif (isset($frame['function']) && $frame['function'] === '{closure}') {
  127. // Simplify closures handling
  128. $data['trace'][] = $frame['function'];
  129. } else {
  130. if (isset($frame['args'])) {
  131. // Make sure that objects present as arguments are not serialized nicely but rather only
  132. // as a class name to avoid any unexpected leak of sensitive information
  133. $frame['args'] = array_map(function ($arg) {
  134. if (is_object($arg) && !($arg instanceof \DateTime || $arg instanceof \DateTimeInterface)) {
  135. return sprintf("[object] (%s)", Utils::getClass($arg));
  136. }
  137. return $arg;
  138. }, $frame['args']);
  139. }
  140. // We should again normalize the frames, because it might contain invalid items
  141. $data['trace'][] = $this->toJson($this->normalize($frame), true);
  142. }
  143. }
  144. if ($previous = $e->getPrevious()) {
  145. $data['previous'] = $this->normalizeException($previous);
  146. }
  147. return $data;
  148. }
  149. /**
  150. * Return the JSON representation of a value
  151. *
  152. * @param mixed $data
  153. * @param bool $ignoreErrors
  154. * @throws \RuntimeException if encoding fails and errors are not ignored
  155. * @return string
  156. */
  157. protected function toJson($data, $ignoreErrors = false)
  158. {
  159. // suppress json_encode errors since it's twitchy with some inputs
  160. if ($ignoreErrors) {
  161. return @$this->jsonEncode($data);
  162. }
  163. $json = $this->jsonEncode($data);
  164. if ($json === false) {
  165. $json = $this->handleJsonError(json_last_error(), $data);
  166. }
  167. return $json;
  168. }
  169. /**
  170. * @param mixed $data
  171. * @return string JSON encoded data or null on failure
  172. */
  173. private function jsonEncode($data)
  174. {
  175. if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
  176. return json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
  177. }
  178. return json_encode($data);
  179. }
  180. /**
  181. * Handle a json_encode failure.
  182. *
  183. * If the failure is due to invalid string encoding, try to clean the
  184. * input and encode again. If the second encoding attempt fails, the
  185. * inital error is not encoding related or the input can't be cleaned then
  186. * raise a descriptive exception.
  187. *
  188. * @param int $code return code of json_last_error function
  189. * @param mixed $data data that was meant to be encoded
  190. * @throws \RuntimeException if failure can't be corrected
  191. * @return string JSON encoded data after error correction
  192. */
  193. private function handleJsonError($code, $data)
  194. {
  195. if ($code !== JSON_ERROR_UTF8) {
  196. $this->throwEncodeError($code, $data);
  197. }
  198. if (is_string($data)) {
  199. $this->detectAndCleanUtf8($data);
  200. } elseif (is_array($data)) {
  201. array_walk_recursive($data, array($this, 'detectAndCleanUtf8'));
  202. } else {
  203. $this->throwEncodeError($code, $data);
  204. }
  205. $json = $this->jsonEncode($data);
  206. if ($json === false) {
  207. $this->throwEncodeError(json_last_error(), $data);
  208. }
  209. return $json;
  210. }
  211. /**
  212. * Throws an exception according to a given code with a customized message
  213. *
  214. * @param int $code return code of json_last_error function
  215. * @param mixed $data data that was meant to be encoded
  216. * @throws \RuntimeException
  217. */
  218. private function throwEncodeError($code, $data)
  219. {
  220. switch ($code) {
  221. case JSON_ERROR_DEPTH:
  222. $msg = 'Maximum stack depth exceeded';
  223. break;
  224. case JSON_ERROR_STATE_MISMATCH:
  225. $msg = 'Underflow or the modes mismatch';
  226. break;
  227. case JSON_ERROR_CTRL_CHAR:
  228. $msg = 'Unexpected control character found';
  229. break;
  230. case JSON_ERROR_UTF8:
  231. $msg = 'Malformed UTF-8 characters, possibly incorrectly encoded';
  232. break;
  233. default:
  234. $msg = 'Unknown error';
  235. }
  236. throw new \RuntimeException('JSON encoding failed: '.$msg.'. Encoding: '.var_export($data, true));
  237. }
  238. /**
  239. * Detect invalid UTF-8 string characters and convert to valid UTF-8.
  240. *
  241. * Valid UTF-8 input will be left unmodified, but strings containing
  242. * invalid UTF-8 codepoints will be reencoded as UTF-8 with an assumed
  243. * original encoding of ISO-8859-15. This conversion may result in
  244. * incorrect output if the actual encoding was not ISO-8859-15, but it
  245. * will be clean UTF-8 output and will not rely on expensive and fragile
  246. * detection algorithms.
  247. *
  248. * Function converts the input in place in the passed variable so that it
  249. * can be used as a callback for array_walk_recursive.
  250. *
  251. * @param mixed &$data Input to check and convert if needed
  252. * @private
  253. */
  254. public function detectAndCleanUtf8(&$data)
  255. {
  256. if (is_string($data) && !preg_match('//u', $data)) {
  257. $data = preg_replace_callback(
  258. '/[\x80-\xFF]+/',
  259. function ($m) { return utf8_encode($m[0]); },
  260. $data
  261. );
  262. $data = str_replace(
  263. array('¤', '¦', '¨', '´', '¸', '¼', '½', '¾'),
  264. array('€', 'Š', 'š', 'Ž', 'ž', 'Œ', 'œ', 'Ÿ'),
  265. $data
  266. );
  267. }
  268. }
  269. }