JsonFormatterTest.php 12 KB

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