JsonFormatterTest.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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. /**
  159. * @param string $expected
  160. * @param string $actual
  161. *
  162. * @internal param string $exception
  163. */
  164. private function assertContextContainsFormattedException($expected, $actual)
  165. {
  166. $this->assertEquals(
  167. '{"level_name":"CRITICAL","channel":"core","context":{"exception":'.$expected.'},"datetime":null,"extra":{},"message":"foobar"}'."\n",
  168. $actual
  169. );
  170. }
  171. /**
  172. * @param JsonFormatter $formatter
  173. * @param \Throwable $exception
  174. *
  175. * @return string
  176. */
  177. private function formatRecordWithExceptionInContext(JsonFormatter $formatter, \Throwable $exception)
  178. {
  179. $message = $formatter->format([
  180. 'level_name' => 'CRITICAL',
  181. 'channel' => 'core',
  182. 'context' => ['exception' => $exception],
  183. 'datetime' => null,
  184. 'extra' => [],
  185. 'message' => 'foobar',
  186. ]);
  187. return $message;
  188. }
  189. /**
  190. * @param \Exception|\Throwable $exception
  191. *
  192. * @return string
  193. */
  194. private function formatExceptionFilePathWithLine($exception)
  195. {
  196. $options = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE;
  197. $path = substr(json_encode($exception->getFile(), $options), 1, -1);
  198. return $path . ':' . $exception->getLine();
  199. }
  200. /**
  201. * @param \Exception|\Throwable $exception
  202. *
  203. * @param null|string $previous
  204. *
  205. * @return string
  206. */
  207. private function formatException($exception, $previous = null)
  208. {
  209. $formattedException =
  210. '{"class":"' . get_class($exception) .
  211. '","message":"' . $exception->getMessage() .
  212. '","code":' . $exception->getCode() .
  213. ',"file":"' . $this->formatExceptionFilePathWithLine($exception) .
  214. ($previous ? '","previous":' . $previous : '"') .
  215. '}';
  216. return $formattedException;
  217. }
  218. public function testNormalizeHandleLargeArraysWithExactly1000Items()
  219. {
  220. $formatter = new NormalizerFormatter();
  221. $largeArray = range(1, 1000);
  222. $res = $formatter->format(array(
  223. 'level_name' => 'CRITICAL',
  224. 'channel' => 'test',
  225. 'message' => 'bar',
  226. 'context' => array($largeArray),
  227. 'datetime' => new \DateTime,
  228. 'extra' => array(),
  229. ));
  230. $this->assertCount(1000, $res['context'][0]);
  231. $this->assertArrayNotHasKey('...', $res['context'][0]);
  232. }
  233. public function testNormalizeHandleLargeArrays()
  234. {
  235. $formatter = new NormalizerFormatter();
  236. $largeArray = range(1, 2000);
  237. $res = $formatter->format(array(
  238. 'level_name' => 'CRITICAL',
  239. 'channel' => 'test',
  240. 'message' => 'bar',
  241. 'context' => array($largeArray),
  242. 'datetime' => new \DateTime,
  243. 'extra' => array(),
  244. ));
  245. $this->assertCount(1001, $res['context'][0]);
  246. $this->assertEquals('Over 1000 items (2000 total), aborting normalization', $res['context'][0]['...']);
  247. }
  248. }