NormalizerFormatterTest.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  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. /**
  13. * @covers Monolog\Formatter\NormalizerFormatter
  14. */
  15. class NormalizerFormatterTest extends \Monolog\Test\MonologTestCase
  16. {
  17. public function testFormat()
  18. {
  19. $formatter = new NormalizerFormatter('Y-m-d');
  20. $formatted = $formatter->format($this->getRecord(
  21. Level::Error,
  22. 'foo',
  23. channel: 'meh',
  24. extra: ['foo' => new TestFooNorm, 'bar' => new TestBarNorm, 'baz' => [], 'res' => fopen('php://memory', 'rb')],
  25. context: [
  26. 'foo' => 'bar',
  27. 'baz' => 'qux',
  28. 'inf' => INF,
  29. '-inf' => -INF,
  30. 'nan' => acos(4),
  31. ],
  32. ));
  33. $this->assertEquals([
  34. 'level_name' => Level::Error->getName(),
  35. 'level' => Level::Error->value,
  36. 'channel' => 'meh',
  37. 'message' => 'foo',
  38. 'datetime' => date('Y-m-d'),
  39. 'extra' => [
  40. 'foo' => ['Monolog\\Formatter\\TestFooNorm' => ["foo" => "fooValue"]],
  41. 'bar' => ['Monolog\\Formatter\\TestBarNorm' => 'bar'],
  42. 'baz' => [],
  43. 'res' => '[resource(stream)]',
  44. ],
  45. 'context' => [
  46. 'foo' => 'bar',
  47. 'baz' => 'qux',
  48. 'inf' => 'INF',
  49. '-inf' => '-INF',
  50. 'nan' => 'NaN',
  51. ],
  52. ], $formatted);
  53. }
  54. public function testFormatExceptions()
  55. {
  56. $formatter = new NormalizerFormatter('Y-m-d');
  57. $e = new \LogicException('bar');
  58. $e2 = new \RuntimeException('foo', 0, $e);
  59. $formatted = $formatter->normalizeValue([
  60. 'exception' => $e2,
  61. ]);
  62. $this->assertGreaterThan(5, \count($formatted['exception']['trace']));
  63. $this->assertTrue(isset($formatted['exception']['previous']));
  64. unset($formatted['exception']['trace'], $formatted['exception']['previous']);
  65. $this->assertEquals([
  66. 'exception' => [
  67. 'class' => \get_class($e2),
  68. 'message' => $e2->getMessage(),
  69. 'code' => $e2->getCode(),
  70. 'file' => $e2->getFile().':'.$e2->getLine(),
  71. ],
  72. ], $formatted);
  73. }
  74. public function testFormatExceptionWithBasePath(): void
  75. {
  76. $formatter = new NormalizerFormatter('Y-m-d');
  77. $formatter->setBasePath(\dirname(\dirname(\dirname(__DIR__))));
  78. $e = new \LogicException('bar');
  79. $formatted = $formatter->normalizeValue([
  80. 'exception' => $e,
  81. ]);
  82. self::assertSame('tests/Monolog/Formatter/NormalizerFormatterTest.php:' . (__LINE__ - 5), $formatted['exception']['file']);
  83. self::assertStringStartsWith('vendor/phpunit/phpunit/src/Framework/TestCase.php:', $formatted['exception']['trace'][0]);
  84. self::assertStringStartsWith('vendor/phpunit/phpunit/src/Framework/TestCase.php:', $formatted['exception']['trace'][1]);
  85. }
  86. public function testFormatSoapFaultException()
  87. {
  88. if (!class_exists('SoapFault')) {
  89. $this->markTestSkipped('Requires the soap extension');
  90. }
  91. $formatter = new NormalizerFormatter('Y-m-d');
  92. $e = new \SoapFault('foo', 'bar', 'hello', 'world');
  93. $formatted = $formatter->normalizeValue([
  94. 'exception' => $e,
  95. ]);
  96. unset($formatted['exception']['trace']);
  97. $this->assertEquals([
  98. 'exception' => [
  99. 'class' => 'SoapFault',
  100. 'message' => 'bar',
  101. 'code' => 0,
  102. 'file' => $e->getFile().':'.$e->getLine(),
  103. 'faultcode' => 'foo',
  104. 'faultactor' => 'hello',
  105. 'detail' => 'world',
  106. ],
  107. ], $formatted);
  108. $formatter = new NormalizerFormatter('Y-m-d');
  109. $e = new \SoapFault('foo', 'bar', 'hello', (object) ['bar' => (object) ['biz' => 'baz'], 'foo' => 'world']);
  110. $formatted = $formatter->normalizeValue([
  111. 'exception' => $e,
  112. ]);
  113. unset($formatted['exception']['trace']);
  114. $this->assertEquals([
  115. 'exception' => [
  116. 'class' => 'SoapFault',
  117. 'message' => 'bar',
  118. 'code' => 0,
  119. 'file' => $e->getFile().':'.$e->getLine(),
  120. 'faultcode' => 'foo',
  121. 'faultactor' => 'hello',
  122. 'detail' => '{"bar":{"biz":"baz"},"foo":"world"}',
  123. ],
  124. ], $formatted);
  125. }
  126. public function testFormatToStringExceptionHandle()
  127. {
  128. $formatter = new NormalizerFormatter('Y-m-d');
  129. $formatted = $formatter->format($this->getRecord(context: [
  130. 'myObject' => new TestToStringError(),
  131. ]));
  132. $this->assertEquals(
  133. [
  134. 'level_name' => Level::Warning->getName(),
  135. 'level' => Level::Warning->value,
  136. 'channel' => 'test',
  137. 'message' => 'test',
  138. 'context' => [
  139. 'myObject' => [
  140. TestToStringError::class => [],
  141. ],
  142. ],
  143. 'datetime' => date('Y-m-d'),
  144. 'extra' => [],
  145. ],
  146. $formatted
  147. );
  148. }
  149. public function testBatchFormat()
  150. {
  151. $formatter = new NormalizerFormatter('Y-m-d');
  152. $formatted = $formatter->formatBatch([
  153. $this->getRecord(Level::Critical, 'bar', channel: 'test'),
  154. $this->getRecord(Level::Warning, 'foo', channel: 'log'),
  155. ]);
  156. $this->assertEquals([
  157. [
  158. 'level_name' => Level::Critical->getName(),
  159. 'level' => Level::Critical->value,
  160. 'channel' => 'test',
  161. 'message' => 'bar',
  162. 'context' => [],
  163. 'datetime' => date('Y-m-d'),
  164. 'extra' => [],
  165. ],
  166. [
  167. 'level_name' => Level::Warning->getName(),
  168. 'level' => Level::Warning->value,
  169. 'channel' => 'log',
  170. 'message' => 'foo',
  171. 'context' => [],
  172. 'datetime' => date('Y-m-d'),
  173. 'extra' => [],
  174. ],
  175. ], $formatted);
  176. }
  177. /**
  178. * Test issue #137
  179. */
  180. public function testIgnoresRecursiveObjectReferences()
  181. {
  182. // set up the recursion
  183. $foo = new \stdClass();
  184. $bar = new \stdClass();
  185. $foo->bar = $bar;
  186. $bar->foo = $foo;
  187. // set an error handler to assert that the error is not raised anymore
  188. $that = $this;
  189. set_error_handler(function ($level, $message, $file, $line, $context) use ($that) {
  190. if (error_reporting() & $level) {
  191. restore_error_handler();
  192. $that->fail("$message should not be raised");
  193. }
  194. return true;
  195. });
  196. $formatter = new NormalizerFormatter();
  197. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  198. $res = $reflMethod->invoke($formatter, [$foo, $bar], true);
  199. restore_error_handler();
  200. $this->assertEquals('[{"bar":{"foo":null}},{"foo":{"bar":null}}]', $res);
  201. }
  202. public function testCanNormalizeReferences()
  203. {
  204. $formatter = new NormalizerFormatter();
  205. $x = ['foo' => 'bar'];
  206. $y = ['x' => &$x];
  207. $x['y'] = &$y;
  208. $formatter->normalizeValue($y);
  209. }
  210. public function testToJsonIgnoresInvalidTypes()
  211. {
  212. // set up the invalid data
  213. $resource = fopen(__FILE__, 'r');
  214. // set an error handler to assert that the error is not raised anymore
  215. $that = $this;
  216. set_error_handler(function ($level, $message, $file, $line, $context) use ($that) {
  217. if (error_reporting() & $level) {
  218. restore_error_handler();
  219. $that->fail("$message should not be raised");
  220. }
  221. return true;
  222. });
  223. $formatter = new NormalizerFormatter();
  224. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  225. $res = $reflMethod->invoke($formatter, [$resource], true);
  226. restore_error_handler();
  227. $this->assertEquals('[null]', $res);
  228. }
  229. public function testNormalizeHandleLargeArraysWithExactly1000Items()
  230. {
  231. $formatter = new NormalizerFormatter();
  232. $largeArray = range(1, 1000);
  233. $res = $formatter->format($this->getRecord(
  234. Level::Critical,
  235. 'bar',
  236. channel: 'test',
  237. context: [$largeArray],
  238. ));
  239. $this->assertCount(1000, $res['context'][0]);
  240. $this->assertArrayNotHasKey('...', $res['context'][0]);
  241. }
  242. public function testNormalizeHandleLargeArrays()
  243. {
  244. $formatter = new NormalizerFormatter();
  245. $largeArray = range(1, 2000);
  246. $res = $formatter->format($this->getRecord(
  247. Level::Critical,
  248. 'bar',
  249. channel: 'test',
  250. context: [$largeArray],
  251. ));
  252. $this->assertCount(1001, $res['context'][0]);
  253. $this->assertEquals('Over 1000 items (2000 total), aborting normalization', $res['context'][0]['...']);
  254. }
  255. public function testIgnoresInvalidEncoding()
  256. {
  257. $formatter = new NormalizerFormatter();
  258. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  259. // send an invalid unicode sequence as a object that can't be cleaned
  260. $record = new \stdClass;
  261. $record->message = "\xB1\x31";
  262. $this->assertsame('{"message":"�1"}', $reflMethod->invoke($formatter, $record));
  263. }
  264. public function testConvertsInvalidEncodingAsLatin9()
  265. {
  266. $formatter = new NormalizerFormatter();
  267. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  268. $res = $reflMethod->invoke($formatter, ['message' => "\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE"]);
  269. $this->assertSame('{"message":"��������"}', $res);
  270. }
  271. public function testMaxNormalizeDepth()
  272. {
  273. $formatter = new NormalizerFormatter();
  274. $formatter->setMaxNormalizeDepth(1);
  275. $throwable = new \Error('Foo');
  276. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  277. $this->assertEquals(
  278. 'Over 1 levels deep, aborting normalization',
  279. $message['context']['exception']
  280. );
  281. }
  282. public function testMaxNormalizeItemCountWith0ItemsMax()
  283. {
  284. $formatter = new NormalizerFormatter();
  285. $formatter->setMaxNormalizeDepth(9);
  286. $formatter->setMaxNormalizeItemCount(0);
  287. $throwable = new \Error('Foo');
  288. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  289. $this->assertEquals(
  290. ["..." => "Over 0 items (7 total), aborting normalization"],
  291. $message
  292. );
  293. }
  294. public function testMaxNormalizeItemCountWith2ItemsMax()
  295. {
  296. $formatter = new NormalizerFormatter();
  297. $formatter->setMaxNormalizeDepth(9);
  298. $formatter->setMaxNormalizeItemCount(2);
  299. $throwable = new \Error('Foo');
  300. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  301. unset($message['context']['exception']['trace']);
  302. unset($message['context']['exception']['file']);
  303. $this->assertEquals(
  304. [
  305. "message" => "foobar",
  306. "context" => ['exception' => [
  307. 'class' => 'Error',
  308. 'message' => 'Foo',
  309. 'code' => 0,
  310. ]],
  311. "..." => "Over 2 items (7 total), aborting normalization",
  312. ],
  313. $message
  314. );
  315. }
  316. public function testExceptionTraceWithArgs()
  317. {
  318. try {
  319. // This will contain $resource and $wrappedResource as arguments in the trace item
  320. $resource = fopen('php://memory', 'rw+');
  321. fwrite($resource, 'test_resource');
  322. $wrappedResource = new TestFooNorm;
  323. $wrappedResource->foo = $resource;
  324. // Just do something stupid with a resource/wrapped resource as argument
  325. $arr = [$wrappedResource, $resource];
  326. // modifying the array inside throws a "usort(): Array was modified by the user comparison function"
  327. usort($arr, function ($a, $b) {
  328. throw new \ErrorException('Foo');
  329. });
  330. } catch (\Throwable $e) {
  331. }
  332. $formatter = new NormalizerFormatter();
  333. $record = $this->getRecord(context: ['exception' => $e]);
  334. $result = $formatter->format($record);
  335. // See https://github.com/php/php-src/issues/8810 fixed in PHP 8.2
  336. $offset = PHP_VERSION_ID >= 80200 ? 13 : 11;
  337. $this->assertSame(
  338. __FILE__.':'.(__LINE__ - $offset),
  339. $result['context']['exception']['trace'][0]
  340. );
  341. }
  342. private function formatRecordWithExceptionInContext(NormalizerFormatter $formatter, \Throwable $exception): array
  343. {
  344. $message = $formatter->format($this->getRecord(
  345. Level::Critical,
  346. 'foobar',
  347. channel: 'core',
  348. context: ['exception' => $exception],
  349. ));
  350. return $message;
  351. }
  352. public function testExceptionTraceDoesNotLeakCallUserFuncArgs()
  353. {
  354. try {
  355. $arg = new TestInfoLeak;
  356. \call_user_func([$this, 'throwHelper'], $arg, $dt = new \DateTime());
  357. } catch (\Exception $e) {
  358. }
  359. $formatter = new NormalizerFormatter();
  360. $record = $this->getRecord(context: ['exception' => $e]);
  361. $result = $formatter->format($record);
  362. $this->assertSame(
  363. __FILE__ .':'.(__LINE__-9),
  364. $result['context']['exception']['trace'][0]
  365. );
  366. }
  367. public function testCanNormalizeIncompleteObject(): void
  368. {
  369. $serialized = "O:17:\"Monolog\TestClass\":1:{s:23:\"\x00Monolog\TestClass\x00name\";s:4:\"test\";}";
  370. $object = unserialize($serialized);
  371. $formatter = new NormalizerFormatter();
  372. $record = $this->getRecord(context: ['object' => $object]);
  373. $result = $formatter->format($record);
  374. $this->assertEquals([
  375. '__PHP_Incomplete_Class' => 'Monolog\\TestClass',
  376. ], $result['context']['object']);
  377. }
  378. public function testMaxTraceLengthDefault()
  379. {
  380. $formatter = new NormalizerFormatter();
  381. $this->assertNull($formatter->getMaxTraceLength());
  382. }
  383. public function testMaxTraceLengthSetter()
  384. {
  385. $formatter = new NormalizerFormatter();
  386. $formatter->setMaxTraceLength(5);
  387. $this->assertEquals(5, $formatter->getMaxTraceLength());
  388. $formatter->setMaxTraceLength(null);
  389. $this->assertNull($formatter->getMaxTraceLength());
  390. }
  391. public function testMaxTraceLengthLimitsTrace()
  392. {
  393. $formatter = new NormalizerFormatter();
  394. $formatter->setMaxTraceLength(2);
  395. $exception = $this->createDeepTraceException();
  396. $formatted = $formatter->normalizeValue(['exception' => $exception]);
  397. $this->assertArrayHasKey('trace', $formatted['exception']);
  398. $this->assertCount(2, $formatted['exception']['trace']);
  399. }
  400. public function testMaxTraceLengthZeroDoesNotIncludeTrace()
  401. {
  402. $formatter = new NormalizerFormatter();
  403. $formatter->setMaxTraceLength(0);
  404. $exception = $this->createDeepTraceException();
  405. $formatted = $formatter->normalizeValue(['exception' => $exception]);
  406. $this->assertArrayNotHasKey('trace', $formatted['exception']);
  407. }
  408. public function testMaxTraceLengthNullAllowsUnlimited()
  409. {
  410. $formatter = new NormalizerFormatter();
  411. $formatter->setMaxTraceLength(null);
  412. $exception = $this->createDeepTraceException();
  413. $formatted = $formatter->normalizeValue(['exception' => $exception]);
  414. $this->assertArrayHasKey('trace', $formatted['exception']);
  415. $this->assertGreaterThan(2, count($formatted['exception']['trace']));
  416. }
  417. public function testMaxTraceLengthWithPreviousException()
  418. {
  419. $formatter = new NormalizerFormatter();
  420. $formatter->setMaxTraceLength(1);
  421. $previous = new \RuntimeException('Previous exception');
  422. $exception = new \LogicException('Main exception', 0, $previous);
  423. $formatted = $formatter->normalizeValue(['exception' => $exception]);
  424. $this->assertArrayHasKey('trace', $formatted['exception']);
  425. $this->assertCount(1, $formatted['exception']['trace']);
  426. $this->assertArrayHasKey('previous', $formatted['exception']);
  427. $this->assertArrayHasKey('trace', $formatted['exception']['previous']);
  428. $this->assertCount(1, $formatted['exception']['previous']['trace']);
  429. }
  430. public function testMaxTraceLengthWithBasePath()
  431. {
  432. $formatter = new NormalizerFormatter();
  433. $formatter->setMaxTraceLength(3);
  434. $formatter->setBasePath(dirname(__DIR__, 3));
  435. $exception = $this->createDeepTraceException();
  436. $formatted = $formatter->normalizeValue(['exception' => $exception]);
  437. $this->assertArrayHasKey('trace', $formatted['exception']);
  438. $this->assertCount(3, $formatted['exception']['trace']);
  439. foreach ($formatted['exception']['trace'] as $traceItem) {
  440. $this->assertStringNotContainsString(dirname(__DIR__, 3), $traceItem);
  441. }
  442. }
  443. private function createDeepTraceException(): \Exception
  444. {
  445. $createException = function(int $depth) use (&$createException): \Exception {
  446. if ($depth <= 0) {
  447. return new \RuntimeException('Test exception with deep trace');
  448. }
  449. return $createException($depth - 1);
  450. };
  451. return $createException(3);
  452. }
  453. private function throwHelper($arg)
  454. {
  455. throw new \RuntimeException('Thrown');
  456. }
  457. }
  458. class TestFooNorm
  459. {
  460. public $foo = 'fooValue';
  461. }
  462. class TestBarNorm
  463. {
  464. public function __toString()
  465. {
  466. return 'bar';
  467. }
  468. }
  469. class TestStreamFoo
  470. {
  471. public $foo;
  472. public $resource;
  473. public function __construct($resource)
  474. {
  475. $this->resource = $resource;
  476. $this->foo = 'BAR';
  477. }
  478. public function __toString()
  479. {
  480. fseek($this->resource, 0);
  481. return $this->foo . ' - ' . (string) stream_get_contents($this->resource);
  482. }
  483. }
  484. class TestToStringError
  485. {
  486. public function __toString()
  487. {
  488. throw new \RuntimeException('Could not convert to string');
  489. }
  490. }
  491. class TestInfoLeak
  492. {
  493. public function __toString()
  494. {
  495. return 'Sensitive information';
  496. }
  497. }