JsonFormatterTest.php 13 KB

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