JsonFormatterTest.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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\Logger;
  12. use Monolog\Test\TestCase;
  13. class JsonFormatterTest extends TestCase
  14. {
  15. /**
  16. * @covers Monolog\Formatter\JsonFormatter::__construct
  17. * @covers Monolog\Formatter\JsonFormatter::getBatchMode
  18. * @covers Monolog\Formatter\JsonFormatter::isAppendingNewlines
  19. */
  20. public function testConstruct()
  21. {
  22. $formatter = new JsonFormatter();
  23. $this->assertEquals(JsonFormatter::BATCH_MODE_JSON, $formatter->getBatchMode());
  24. $this->assertEquals(true, $formatter->isAppendingNewlines());
  25. $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_NEWLINES, false);
  26. $this->assertEquals(JsonFormatter::BATCH_MODE_NEWLINES, $formatter->getBatchMode());
  27. $this->assertEquals(false, $formatter->isAppendingNewlines());
  28. }
  29. /**
  30. * @covers Monolog\Formatter\JsonFormatter::format
  31. */
  32. public function testFormat()
  33. {
  34. $formatter = new JsonFormatter();
  35. $record = $this->getRecord();
  36. $record['context'] = $record['extra'] = new \stdClass;
  37. $this->assertEquals(json_encode($record)."\n", $formatter->format($record));
  38. $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false);
  39. $record = $this->getRecord();
  40. $this->assertEquals('{"message":"test","context":{},"level":300,"level_name":"WARNING","channel":"test","datetime":"'.$record['datetime']->format('Y-m-d\TH:i:s.uP').'","extra":{}}', $formatter->format($record));
  41. }
  42. /**
  43. * @covers Monolog\Formatter\JsonFormatter::format
  44. */
  45. public function testFormatWithPrettyPrint()
  46. {
  47. $formatter = new JsonFormatter();
  48. $formatter->setJsonPrettyPrint(true);
  49. $record = $this->getRecord();
  50. $record['context'] = $record['extra'] = new \stdClass;
  51. $this->assertEquals(json_encode($record, JSON_PRETTY_PRINT)."\n", $formatter->format($record));
  52. $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false);
  53. $formatter->setJsonPrettyPrint(true);
  54. $record = $this->getRecord();
  55. $this->assertEquals(
  56. '{
  57. "message": "test",
  58. "context": {},
  59. "level": 300,
  60. "level_name": "WARNING",
  61. "channel": "test",
  62. "datetime": "'.$record['datetime']->format('Y-m-d\TH:i:s.uP').'",
  63. "extra": {}
  64. }',
  65. $formatter->format($record)
  66. );
  67. $formatter->setJsonPrettyPrint(false);
  68. $record = $this->getRecord();
  69. $this->assertEquals('{"message":"test","context":{},"level":300,"level_name":"WARNING","channel":"test","datetime":"'.$record['datetime']->format('Y-m-d\TH:i:s.uP').'","extra":{}}', $formatter->format($record));
  70. }
  71. /**
  72. * @covers Monolog\Formatter\JsonFormatter::formatBatch
  73. * @covers Monolog\Formatter\JsonFormatter::formatBatchJson
  74. */
  75. public function testFormatBatch()
  76. {
  77. $formatter = new JsonFormatter();
  78. $records = [
  79. $this->getRecord(Logger::WARNING),
  80. $this->getRecord(Logger::DEBUG),
  81. ];
  82. $this->assertEquals(json_encode($records), $formatter->formatBatch($records));
  83. }
  84. /**
  85. * @covers Monolog\Formatter\JsonFormatter::formatBatch
  86. * @covers Monolog\Formatter\JsonFormatter::formatBatchNewlines
  87. */
  88. public function testFormatBatchNewlines()
  89. {
  90. $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_NEWLINES);
  91. $records = $expected = [
  92. $this->getRecord(Logger::WARNING),
  93. $this->getRecord(Logger::DEBUG),
  94. ];
  95. array_walk($expected, function (&$value, $key) {
  96. $value['context'] = $value['extra'] = new \stdClass;
  97. $value = json_encode($value);
  98. });
  99. $this->assertEquals(implode("\n", $expected), $formatter->formatBatch($records));
  100. }
  101. public function testDefFormatWithException()
  102. {
  103. $formatter = new JsonFormatter();
  104. $exception = new \RuntimeException('Foo');
  105. $formattedException = $this->formatException($exception);
  106. $message = $this->formatRecordWithExceptionInContext($formatter, $exception);
  107. $this->assertContextContainsFormattedException($formattedException, $message);
  108. }
  109. public function testDefFormatWithPreviousException()
  110. {
  111. $formatter = new JsonFormatter();
  112. $exception = new \RuntimeException('Foo', 0, new \LogicException('Wut?'));
  113. $formattedPrevException = $this->formatException($exception->getPrevious());
  114. $formattedException = $this->formatException($exception, $formattedPrevException);
  115. $message = $this->formatRecordWithExceptionInContext($formatter, $exception);
  116. $this->assertContextContainsFormattedException($formattedException, $message);
  117. }
  118. public function testDefFormatWithThrowable()
  119. {
  120. $formatter = new JsonFormatter();
  121. $throwable = new \Error('Foo');
  122. $formattedThrowable = $this->formatException($throwable);
  123. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  124. $this->assertContextContainsFormattedException($formattedThrowable, $message);
  125. }
  126. public function testMaxNormalizeDepth()
  127. {
  128. $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, true);
  129. $formatter->setMaxNormalizeDepth(1);
  130. $throwable = new \Error('Foo');
  131. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  132. $this->assertContextContainsFormattedException('"Over 1 levels deep, aborting normalization"', $message);
  133. }
  134. public function testMaxNormalizeItemCountWith0ItemsMax()
  135. {
  136. $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, true);
  137. $formatter->setMaxNormalizeDepth(9);
  138. $formatter->setMaxNormalizeItemCount(0);
  139. $throwable = new \Error('Foo');
  140. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  141. $this->assertEquals(
  142. '{"...":"Over 0 items (6 total), aborting normalization"}'."\n",
  143. $message
  144. );
  145. }
  146. public function testMaxNormalizeItemCountWith2ItemsMax()
  147. {
  148. $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, true);
  149. $formatter->setMaxNormalizeDepth(9);
  150. $formatter->setMaxNormalizeItemCount(2);
  151. $throwable = new \Error('Foo');
  152. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  153. $this->assertEquals(
  154. '{"level_name":"CRITICAL","channel":"core","...":"Over 2 items (6 total), aborting normalization"}'."\n",
  155. $message
  156. );
  157. }
  158. public function testDefFormatWithResource()
  159. {
  160. $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false);
  161. $record = $this->getRecord();
  162. $record['context'] = ['field_resource' => curl_init()];
  163. $this->assertEquals('{"message":"test","context":{"field_resource":"[resource(curl)]"},"level":300,"level_name":"WARNING","channel":"test","datetime":"'.$record['datetime']->format('Y-m-d\TH:i:s.uP').'","extra":{}}', $formatter->format($record));
  164. }
  165. /**
  166. * @param string $expected
  167. * @param string $actual
  168. *
  169. * @internal param string $exception
  170. */
  171. private function assertContextContainsFormattedException($expected, $actual)
  172. {
  173. $this->assertEquals(
  174. '{"level_name":"CRITICAL","channel":"core","context":{"exception":'.$expected.'},"datetime":null,"extra":{},"message":"foobar"}'."\n",
  175. $actual
  176. );
  177. }
  178. /**
  179. * @param JsonFormatter $formatter
  180. * @param \Throwable $exception
  181. *
  182. * @return string
  183. */
  184. private function formatRecordWithExceptionInContext(JsonFormatter $formatter, \Throwable $exception)
  185. {
  186. $message = $formatter->format([
  187. 'level_name' => 'CRITICAL',
  188. 'channel' => 'core',
  189. 'context' => ['exception' => $exception],
  190. 'datetime' => null,
  191. 'extra' => [],
  192. 'message' => 'foobar',
  193. ]);
  194. return $message;
  195. }
  196. /**
  197. * @param \Exception|\Throwable $exception
  198. *
  199. * @return string
  200. */
  201. private function formatExceptionFilePathWithLine($exception)
  202. {
  203. $options = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE;
  204. $path = substr(json_encode($exception->getFile(), $options), 1, -1);
  205. return $path . ':' . $exception->getLine();
  206. }
  207. /**
  208. * @param \Exception|\Throwable $exception
  209. *
  210. * @param null|string $previous
  211. *
  212. * @return string
  213. */
  214. private function formatException($exception, $previous = null)
  215. {
  216. $formattedException =
  217. '{"class":"' . get_class($exception) .
  218. '","message":"' . $exception->getMessage() .
  219. '","code":' . $exception->getCode() .
  220. ',"file":"' . $this->formatExceptionFilePathWithLine($exception) .
  221. ($previous ? '","previous":' . $previous : '"') .
  222. '}';
  223. return $formattedException;
  224. }
  225. public function testNormalizeHandleLargeArraysWithExactly1000Items()
  226. {
  227. $formatter = new NormalizerFormatter();
  228. $largeArray = range(1, 1000);
  229. $res = $formatter->format(array(
  230. 'level_name' => 'CRITICAL',
  231. 'channel' => 'test',
  232. 'message' => 'bar',
  233. 'context' => array($largeArray),
  234. 'datetime' => new \DateTime,
  235. 'extra' => array(),
  236. ));
  237. $this->assertCount(1000, $res['context'][0]);
  238. $this->assertArrayNotHasKey('...', $res['context'][0]);
  239. }
  240. public function testNormalizeHandleLargeArrays()
  241. {
  242. $formatter = new NormalizerFormatter();
  243. $largeArray = range(1, 2000);
  244. $res = $formatter->format(array(
  245. 'level_name' => 'CRITICAL',
  246. 'channel' => 'test',
  247. 'message' => 'bar',
  248. 'context' => array($largeArray),
  249. 'datetime' => new \DateTime,
  250. 'extra' => array(),
  251. ));
  252. $this->assertCount(1001, $res['context'][0]);
  253. $this->assertEquals('Over 1000 items (2000 total), aborting normalization', $res['context'][0]['...']);
  254. }
  255. }