JsonFormatterTest.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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\Level;
  12. use Monolog\LogRecord;
  13. use JsonSerializable;
  14. use Monolog\Test\TestCase;
  15. class JsonFormatterTest extends TestCase
  16. {
  17. /**
  18. * @covers Monolog\Formatter\JsonFormatter::__construct
  19. * @covers Monolog\Formatter\JsonFormatter::getBatchMode
  20. * @covers Monolog\Formatter\JsonFormatter::isAppendingNewlines
  21. */
  22. public function testConstruct()
  23. {
  24. $formatter = new JsonFormatter();
  25. $this->assertEquals(JsonFormatter::BATCH_MODE_JSON, $formatter->getBatchMode());
  26. $this->assertEquals(true, $formatter->isAppendingNewlines());
  27. $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_NEWLINES, false);
  28. $this->assertEquals(JsonFormatter::BATCH_MODE_NEWLINES, $formatter->getBatchMode());
  29. $this->assertEquals(false, $formatter->isAppendingNewlines());
  30. }
  31. /**
  32. * @covers Monolog\Formatter\JsonFormatter::format
  33. */
  34. public function testFormat()
  35. {
  36. $formatter = new JsonFormatter();
  37. $record = $this->getRecord();
  38. $this->assertEquals(json_encode($record->toArray(), JSON_FORCE_OBJECT)."\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. $this->assertEquals(json_encode($record->toArray(), JSON_PRETTY_PRINT | JSON_FORCE_OBJECT)."\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(Level::Warning),
  80. $this->getRecord(Level::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 = [
  92. $this->getRecord(Level::Warning),
  93. $this->getRecord(Level::Debug),
  94. ];
  95. $expected = array_map(fn (LogRecord $record) => json_encode($record->toArray(), JSON_FORCE_OBJECT), $records);
  96. $this->assertEquals(implode("\n", $expected), $formatter->formatBatch($records));
  97. }
  98. public function testDefFormatWithException()
  99. {
  100. $formatter = new JsonFormatter();
  101. $exception = new \RuntimeException('Foo');
  102. $formattedException = $this->formatException($exception);
  103. $message = $this->formatRecordWithExceptionInContext($formatter, $exception);
  104. $this->assertContextContainsFormattedException($formattedException, $message);
  105. }
  106. public function testBasePathWithException(): void
  107. {
  108. $formatter = new JsonFormatter();
  109. $formatter->setBasePath(\dirname(\dirname(\dirname(__DIR__))));
  110. $exception = new \RuntimeException('Foo');
  111. $message = $this->formatRecordWithExceptionInContext($formatter, $exception);
  112. $parsed = json_decode($message, true);
  113. self::assertSame('tests/Monolog/Formatter/JsonFormatterTest.php:' . (__LINE__ - 5), $parsed['context']['exception']['file']);
  114. }
  115. public function testDefFormatWithPreviousException()
  116. {
  117. $formatter = new JsonFormatter();
  118. $exception = new \RuntimeException('Foo', 0, new \LogicException('Wut?'));
  119. $formattedPrevException = $this->formatException($exception->getPrevious());
  120. $formattedException = $this->formatException($exception, $formattedPrevException);
  121. $message = $this->formatRecordWithExceptionInContext($formatter, $exception);
  122. $this->assertContextContainsFormattedException($formattedException, $message);
  123. }
  124. public function testDefFormatWithThrowable()
  125. {
  126. $formatter = new JsonFormatter();
  127. $throwable = new \Error('Foo');
  128. $formattedThrowable = $this->formatException($throwable);
  129. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  130. $this->assertContextContainsFormattedException($formattedThrowable, $message);
  131. }
  132. public function testMaxNormalizeDepth()
  133. {
  134. $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, true);
  135. $formatter->setMaxNormalizeDepth(1);
  136. $throwable = new \Error('Foo');
  137. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  138. $this->assertContextContainsFormattedException('"Over 1 levels deep, aborting normalization"', $message);
  139. }
  140. public function testMaxNormalizeItemCountWith0ItemsMax()
  141. {
  142. $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, true);
  143. $formatter->setMaxNormalizeDepth(9);
  144. $formatter->setMaxNormalizeItemCount(0);
  145. $throwable = new \Error('Foo');
  146. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  147. $this->assertEquals(
  148. '{"...":"Over 0 items (7 total), aborting normalization"}'."\n",
  149. $message
  150. );
  151. }
  152. public function testMaxNormalizeItemCountWith2ItemsMax()
  153. {
  154. $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, true);
  155. $formatter->setMaxNormalizeDepth(9);
  156. $formatter->setMaxNormalizeItemCount(2);
  157. $throwable = new \Error('Foo');
  158. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  159. $this->assertEquals(
  160. '{"message":"foobar","context":{"exception":{"class":"Error","message":"Foo","code":0,"file":"'.__FILE__.':'.(__LINE__ - 5).'"}},"...":"Over 2 items (7 total), aborting normalization"}'."\n",
  161. $message
  162. );
  163. }
  164. public function testDefFormatWithResource()
  165. {
  166. $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false);
  167. $record = $this->getRecord(
  168. context: ['field_resource' => opendir(__DIR__)],
  169. );
  170. $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));
  171. }
  172. /**
  173. * @internal param string $exception
  174. */
  175. private function assertContextContainsFormattedException(string $expected, string $actual)
  176. {
  177. $this->assertEquals(
  178. '{"message":"foobar","context":{"exception":'.$expected.'},"level":500,"level_name":"CRITICAL","channel":"core","datetime":"2022-02-22T00:00:00+00:00","extra":{}}'."\n",
  179. $actual
  180. );
  181. }
  182. private function formatRecordWithExceptionInContext(JsonFormatter $formatter, \Throwable $exception): string
  183. {
  184. $message = $formatter->format($this->getRecord(
  185. Level::Critical,
  186. 'foobar',
  187. channel: 'core',
  188. context: ['exception' => $exception],
  189. datetime: new \DateTimeImmutable('2022-02-22 00:00:00'),
  190. ));
  191. return $message;
  192. }
  193. /**
  194. * @param \Exception|\Throwable $exception
  195. */
  196. private function formatExceptionFilePathWithLine($exception): string
  197. {
  198. $options = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE;
  199. $path = substr(json_encode($exception->getFile(), $options), 1, -1);
  200. return $path . ':' . $exception->getLine();
  201. }
  202. /**
  203. * @param \Exception|\Throwable $exception
  204. */
  205. private function formatException($exception, ?string $previous = null): string
  206. {
  207. $formattedException =
  208. '{"class":"' . \get_class($exception) .
  209. '","message":"' . $exception->getMessage() .
  210. '","code":' . $exception->getCode() .
  211. ',"file":"' . $this->formatExceptionFilePathWithLine($exception) .
  212. ($previous ? '","previous":' . $previous : '"') .
  213. '}';
  214. return $formattedException;
  215. }
  216. public function testNormalizeHandleLargeArraysWithExactly1000Items()
  217. {
  218. $formatter = new NormalizerFormatter();
  219. $largeArray = range(1, 1000);
  220. $res = $formatter->format($this->getRecord(
  221. Level::Critical,
  222. 'bar',
  223. channel: 'test',
  224. context: [$largeArray],
  225. ));
  226. $this->assertCount(1000, $res['context'][0]);
  227. $this->assertArrayNotHasKey('...', $res['context'][0]);
  228. }
  229. public function testNormalizeHandleLargeArrays()
  230. {
  231. $formatter = new NormalizerFormatter();
  232. $largeArray = range(1, 2000);
  233. $res = $formatter->format($this->getRecord(
  234. Level::Critical,
  235. 'bar',
  236. channel: 'test',
  237. context: [$largeArray],
  238. ));
  239. $this->assertCount(1001, $res['context'][0]);
  240. $this->assertEquals('Over 1000 items (2000 total), aborting normalization', $res['context'][0]['...']);
  241. }
  242. public function testCanNormalizeIncompleteObject(): void
  243. {
  244. $serialized = "O:17:\"Monolog\TestClass\":1:{s:23:\"\x00Monolog\TestClass\x00name\";s:4:\"test\";}";
  245. $object = unserialize($serialized);
  246. $formatter = new JsonFormatter();
  247. $record = $this->getRecord(context: ['object' => $object], datetime: new \DateTimeImmutable('2022-02-22 00:00:00'));
  248. $result = $formatter->format($record);
  249. self::assertSame('{"message":"test","context":{"object":{"__PHP_Incomplete_Class_Name":"Monolog\\\\TestClass"}},"level":300,"level_name":"WARNING","channel":"test","datetime":"2022-02-22T00:00:00+00:00","extra":{}}'."\n", $result);
  250. }
  251. public function testEmptyContextAndExtraFieldsCanBeIgnored()
  252. {
  253. $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, true, true);
  254. $record = $formatter->format($this->getRecord(
  255. Level::Debug,
  256. 'Testing',
  257. channel: 'test',
  258. datetime: new \DateTimeImmutable('2022-02-22 00:00:00'),
  259. ));
  260. $this->assertSame(
  261. '{"message":"Testing","level":100,"level_name":"DEBUG","channel":"test","datetime":"2022-02-22T00:00:00+00:00"}'."\n",
  262. $record
  263. );
  264. }
  265. public function testFormatObjects()
  266. {
  267. $formatter = new JsonFormatter();
  268. $record = $formatter->format($this->getRecord(
  269. Level::Debug,
  270. 'Testing',
  271. channel: 'test',
  272. datetime: new \DateTimeImmutable('2022-02-22 00:00:00'),
  273. context: [
  274. 'public' => new TestJsonNormPublic,
  275. 'private' => new TestJsonNormPrivate,
  276. 'withToStringAndJson' => new TestJsonNormWithToStringAndJson,
  277. 'withToString' => new TestJsonNormWithToString,
  278. ],
  279. ));
  280. $this->assertSame(
  281. '{"message":"Testing","context":{"public":{"foo":"fooValue"},"private":{},"withToStringAndJson":["json serialized"],"withToString":"stringified"},"level":100,"level_name":"DEBUG","channel":"test","datetime":"2022-02-22T00:00:00+00:00","extra":{}}'."\n",
  282. $record
  283. );
  284. }
  285. }
  286. class TestJsonNormPublic
  287. {
  288. public $foo = 'fooValue';
  289. }
  290. class TestJsonNormPrivate
  291. {
  292. private $foo = 'fooValue';
  293. }
  294. class TestJsonNormWithToStringAndJson implements JsonSerializable
  295. {
  296. public function jsonSerialize(): mixed
  297. {
  298. return ['json serialized'];
  299. }
  300. public function __toString()
  301. {
  302. return 'SHOULD NOT SHOW UP';
  303. }
  304. }
  305. class TestJsonNormWithToString
  306. {
  307. public function __toString()
  308. {
  309. return 'stringified';
  310. }
  311. }