JsonFormatterTest.php 14 KB

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