JsonFormatterTest.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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. $this->assertEquals(json_encode($record)."\n", $formatter->format($record));
  37. $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false);
  38. $record = $this->getRecord();
  39. $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));
  40. }
  41. /**
  42. * @covers Monolog\Formatter\JsonFormatter::formatBatch
  43. * @covers Monolog\Formatter\JsonFormatter::formatBatchJson
  44. */
  45. public function testFormatBatch()
  46. {
  47. $formatter = new JsonFormatter();
  48. $records = [
  49. $this->getRecord(Logger::WARNING),
  50. $this->getRecord(Logger::DEBUG),
  51. ];
  52. $this->assertEquals(json_encode($records), $formatter->formatBatch($records));
  53. }
  54. /**
  55. * @covers Monolog\Formatter\JsonFormatter::formatBatch
  56. * @covers Monolog\Formatter\JsonFormatter::formatBatchNewlines
  57. */
  58. public function testFormatBatchNewlines()
  59. {
  60. $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_NEWLINES);
  61. $records = $expected = [
  62. $this->getRecord(Logger::WARNING),
  63. $this->getRecord(Logger::DEBUG),
  64. ];
  65. array_walk($expected, function (&$value, $key) {
  66. $value = json_encode($value);
  67. });
  68. $this->assertEquals(implode("\n", $expected), $formatter->formatBatch($records));
  69. }
  70. public function testDefFormatWithException()
  71. {
  72. $formatter = new JsonFormatter();
  73. $exception = new \RuntimeException('Foo');
  74. $formattedException = $this->formatException($exception);
  75. $message = $this->formatRecordWithExceptionInContext($formatter, $exception);
  76. $this->assertContextContainsFormattedException($formattedException, $message);
  77. }
  78. public function testDefFormatWithPreviousException()
  79. {
  80. $formatter = new JsonFormatter();
  81. $exception = new \RuntimeException('Foo', 0, new \LogicException('Wut?'));
  82. $formattedPrevException = $this->formatException($exception->getPrevious());
  83. $formattedException = $this->formatException($exception, $formattedPrevException);
  84. $message = $this->formatRecordWithExceptionInContext($formatter, $exception);
  85. $this->assertContextContainsFormattedException($formattedException, $message);
  86. }
  87. public function testDefFormatWithThrowable()
  88. {
  89. $formatter = new JsonFormatter();
  90. $throwable = new \Error('Foo');
  91. $formattedThrowable = $this->formatException($throwable);
  92. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  93. $this->assertContextContainsFormattedException($formattedThrowable, $message);
  94. }
  95. public function testMaxNormalizeDepth()
  96. {
  97. $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, true);
  98. $formatter->setMaxNormalizeDepth(1);
  99. $throwable = new \Error('Foo');
  100. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  101. $this->assertContextContainsFormattedException('"Over 1 levels deep, aborting normalization"', $message);
  102. }
  103. public function testMaxNormalizeItemCountWith0ItemsMax()
  104. {
  105. $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, true);
  106. $formatter->setMaxNormalizeDepth(9);
  107. $formatter->setMaxNormalizeItemCount(0);
  108. $throwable = new \Error('Foo');
  109. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  110. $this->assertEquals(
  111. '{"...":"Over 0 items (6 total), aborting normalization"}'."\n",
  112. $message
  113. );
  114. }
  115. public function testMaxNormalizeItemCountWith2ItemsMax()
  116. {
  117. $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, true);
  118. $formatter->setMaxNormalizeDepth(9);
  119. $formatter->setMaxNormalizeItemCount(2);
  120. $throwable = new \Error('Foo');
  121. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  122. $this->assertEquals(
  123. '{"level_name":"CRITICAL","channel":"core","...":"Over 2 items (6 total), aborting normalization"}'."\n",
  124. $message
  125. );
  126. }
  127. /**
  128. * @param string $expected
  129. * @param string $actual
  130. *
  131. * @internal param string $exception
  132. */
  133. private function assertContextContainsFormattedException($expected, $actual)
  134. {
  135. $this->assertEquals(
  136. '{"level_name":"CRITICAL","channel":"core","context":{"exception":'.$expected.'},"datetime":null,"extra":[],"message":"foobar"}'."\n",
  137. $actual
  138. );
  139. }
  140. /**
  141. * @param JsonFormatter $formatter
  142. * @param \Throwable $exception
  143. *
  144. * @return string
  145. */
  146. private function formatRecordWithExceptionInContext(JsonFormatter $formatter, \Throwable $exception)
  147. {
  148. $message = $formatter->format([
  149. 'level_name' => 'CRITICAL',
  150. 'channel' => 'core',
  151. 'context' => ['exception' => $exception],
  152. 'datetime' => null,
  153. 'extra' => [],
  154. 'message' => 'foobar',
  155. ]);
  156. return $message;
  157. }
  158. /**
  159. * @param \Exception|\Throwable $exception
  160. *
  161. * @return string
  162. */
  163. private function formatExceptionFilePathWithLine($exception)
  164. {
  165. $options = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE;
  166. $path = substr(json_encode($exception->getFile(), $options), 1, -1);
  167. return $path . ':' . $exception->getLine();
  168. }
  169. /**
  170. * @param \Exception|\Throwable $exception
  171. *
  172. * @param null|string $previous
  173. *
  174. * @return string
  175. */
  176. private function formatException($exception, $previous = null)
  177. {
  178. $formattedException =
  179. '{"class":"' . get_class($exception) .
  180. '","message":"' . $exception->getMessage() .
  181. '","code":' . $exception->getCode() .
  182. ',"file":"' . $this->formatExceptionFilePathWithLine($exception) .
  183. ($previous ? '","previous":' . $previous : '"') .
  184. '}';
  185. return $formattedException;
  186. }
  187. public function testNormalizeHandleLargeArraysWithExactly1000Items()
  188. {
  189. $formatter = new NormalizerFormatter();
  190. $largeArray = range(1, 1000);
  191. $res = $formatter->format(array(
  192. 'level_name' => 'CRITICAL',
  193. 'channel' => 'test',
  194. 'message' => 'bar',
  195. 'context' => array($largeArray),
  196. 'datetime' => new \DateTime,
  197. 'extra' => array(),
  198. ));
  199. $this->assertCount(1000, $res['context'][0]);
  200. $this->assertArrayNotHasKey('...', $res['context'][0]);
  201. }
  202. public function testNormalizeHandleLargeArrays()
  203. {
  204. $formatter = new NormalizerFormatter();
  205. $largeArray = range(1, 2000);
  206. $res = $formatter->format(array(
  207. 'level_name' => 'CRITICAL',
  208. 'channel' => 'test',
  209. 'message' => 'bar',
  210. 'context' => array($largeArray),
  211. 'datetime' => new \DateTime,
  212. 'extra' => array(),
  213. ));
  214. $this->assertCount(1001, $res['context'][0]);
  215. $this->assertEquals('Over 1000 items (2000 total), aborting normalization', $res['context'][0]['...']);
  216. }
  217. }