| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307 |
- <?php declare(strict_types=1);
- /*
- * This file is part of the Monolog package.
- *
- * (c) Jordi Boggiano <j.boggiano@seld.be>
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
- namespace Monolog\Formatter;
- use Monolog\Level;
- use Monolog\LogRecord;
- use Monolog\Test\TestCase;
- class JsonFormatterTest extends TestCase
- {
- /**
- * @covers Monolog\Formatter\JsonFormatter::__construct
- * @covers Monolog\Formatter\JsonFormatter::getBatchMode
- * @covers Monolog\Formatter\JsonFormatter::isAppendingNewlines
- */
- public function testConstruct()
- {
- $formatter = new JsonFormatter();
- $this->assertEquals(JsonFormatter::BATCH_MODE_JSON, $formatter->getBatchMode());
- $this->assertEquals(true, $formatter->isAppendingNewlines());
- $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_NEWLINES, false);
- $this->assertEquals(JsonFormatter::BATCH_MODE_NEWLINES, $formatter->getBatchMode());
- $this->assertEquals(false, $formatter->isAppendingNewlines());
- }
- /**
- * @covers Monolog\Formatter\JsonFormatter::format
- */
- public function testFormat()
- {
- $formatter = new JsonFormatter();
- $record = $this->getRecord();
- $this->assertEquals(json_encode($record->toArray(), JSON_FORCE_OBJECT)."\n", $formatter->format($record));
- $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false);
- $record = $this->getRecord();
- $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));
- }
- /**
- * @covers Monolog\Formatter\JsonFormatter::format
- */
- public function testFormatWithPrettyPrint()
- {
- $formatter = new JsonFormatter();
- $formatter->setJsonPrettyPrint(true);
- $record = $this->getRecord();
- $this->assertEquals(json_encode($record->toArray(), JSON_PRETTY_PRINT | JSON_FORCE_OBJECT)."\n", $formatter->format($record));
- $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false);
- $formatter->setJsonPrettyPrint(true);
- $record = $this->getRecord();
- $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)
- );
- $formatter->setJsonPrettyPrint(false);
- $record = $this->getRecord();
- $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));
- }
- /**
- * @covers Monolog\Formatter\JsonFormatter::formatBatch
- * @covers Monolog\Formatter\JsonFormatter::formatBatchJson
- */
- public function testFormatBatch()
- {
- $formatter = new JsonFormatter();
- $records = [
- $this->getRecord(Level::Warning),
- $this->getRecord(Level::Debug),
- ];
- $this->assertEquals(json_encode($records), $formatter->formatBatch($records));
- }
- /**
- * @covers Monolog\Formatter\JsonFormatter::formatBatch
- * @covers Monolog\Formatter\JsonFormatter::formatBatchNewlines
- */
- public function testFormatBatchNewlines()
- {
- $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_NEWLINES);
- $records = [
- $this->getRecord(Level::Warning),
- $this->getRecord(Level::Debug),
- ];
- $expected = array_map(fn (LogRecord $record) => json_encode($record->toArray(), JSON_FORCE_OBJECT), $records);
- $this->assertEquals(implode("\n", $expected), $formatter->formatBatch($records));
- }
- public function testDefFormatWithException()
- {
- $formatter = new JsonFormatter();
- $exception = new \RuntimeException('Foo');
- $formattedException = $this->formatException($exception);
- $message = $this->formatRecordWithExceptionInContext($formatter, $exception);
- $this->assertContextContainsFormattedException($formattedException, $message);
- }
- public function testDefFormatWithPreviousException()
- {
- $formatter = new JsonFormatter();
- $exception = new \RuntimeException('Foo', 0, new \LogicException('Wut?'));
- $formattedPrevException = $this->formatException($exception->getPrevious());
- $formattedException = $this->formatException($exception, $formattedPrevException);
- $message = $this->formatRecordWithExceptionInContext($formatter, $exception);
- $this->assertContextContainsFormattedException($formattedException, $message);
- }
- public function testDefFormatWithThrowable()
- {
- $formatter = new JsonFormatter();
- $throwable = new \Error('Foo');
- $formattedThrowable = $this->formatException($throwable);
- $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
- $this->assertContextContainsFormattedException($formattedThrowable, $message);
- }
- public function testMaxNormalizeDepth()
- {
- $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, true);
- $formatter->setMaxNormalizeDepth(1);
- $throwable = new \Error('Foo');
- $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
- $this->assertContextContainsFormattedException('"Over 1 levels deep, aborting normalization"', $message);
- }
- public function testMaxNormalizeItemCountWith0ItemsMax()
- {
- $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, true);
- $formatter->setMaxNormalizeDepth(9);
- $formatter->setMaxNormalizeItemCount(0);
- $throwable = new \Error('Foo');
- $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
- $this->assertEquals(
- '{"...":"Over 0 items (7 total), aborting normalization"}'."\n",
- $message
- );
- }
- public function testMaxNormalizeItemCountWith2ItemsMax()
- {
- $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, true);
- $formatter->setMaxNormalizeDepth(9);
- $formatter->setMaxNormalizeItemCount(2);
- $throwable = new \Error('Foo');
- $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
- $this->assertEquals(
- '{"message":"foobar","context":{"exception":{"class":"Error","message":"Foo","code":0,"file":"'.__FILE__.':'.(__LINE__ - 5).'"}},"...":"Over 2 items (7 total), aborting normalization"}'."\n",
- $message
- );
- }
- public function testDefFormatWithResource()
- {
- $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false);
- $record = $this->getRecord(
- context: ['field_resource' => opendir(__DIR__)],
- );
- $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));
- }
- /**
- * @param string $expected
- * @param string $actual
- *
- * @internal param string $exception
- */
- private function assertContextContainsFormattedException($expected, $actual)
- {
- $this->assertEquals(
- '{"message":"foobar","context":{"exception":'.$expected.'},"level":500,"level_name":"CRITICAL","channel":"core","datetime":"2022-02-22T00:00:00+00:00","extra":{}}'."\n",
- $actual
- );
- }
- /**
- * @param JsonFormatter $formatter
- * @param \Throwable $exception
- *
- * @return string
- */
- private function formatRecordWithExceptionInContext(JsonFormatter $formatter, \Throwable $exception)
- {
- $message = $formatter->format($this->getRecord(
- Level::Critical,
- 'foobar',
- channel: 'core',
- context: ['exception' => $exception],
- datetime: new \DateTimeImmutable('2022-02-22 00:00:00'),
- ));
- return $message;
- }
- /**
- * @param \Exception|\Throwable $exception
- *
- * @return string
- */
- private function formatExceptionFilePathWithLine($exception)
- {
- $options = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE;
- $path = substr(json_encode($exception->getFile(), $options), 1, -1);
- return $path . ':' . $exception->getLine();
- }
- /**
- * @param \Exception|\Throwable $exception
- *
- * @param null|string $previous
- *
- * @return string
- */
- private function formatException($exception, $previous = null)
- {
- $formattedException =
- '{"class":"' . get_class($exception) .
- '","message":"' . $exception->getMessage() .
- '","code":' . $exception->getCode() .
- ',"file":"' . $this->formatExceptionFilePathWithLine($exception) .
- ($previous ? '","previous":' . $previous : '"') .
- '}';
- return $formattedException;
- }
- public function testNormalizeHandleLargeArraysWithExactly1000Items()
- {
- $formatter = new NormalizerFormatter();
- $largeArray = range(1, 1000);
- $res = $formatter->format($this->getRecord(
- Level::Critical,
- 'bar',
- channel: 'test',
- context: array($largeArray),
- ));
- $this->assertCount(1000, $res['context'][0]);
- $this->assertArrayNotHasKey('...', $res['context'][0]);
- }
- public function testNormalizeHandleLargeArrays()
- {
- $formatter = new NormalizerFormatter();
- $largeArray = range(1, 2000);
- $res = $formatter->format($this->getRecord(
- Level::Critical,
- 'bar',
- channel: 'test',
- context: array($largeArray),
- ));
- $this->assertCount(1001, $res['context'][0]);
- $this->assertEquals('Over 1000 items (2000 total), aborting normalization', $res['context'][0]['...']);
- }
- public function testEmptyContextAndExtraFieldsCanBeIgnored()
- {
- $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, true, true);
- $record = $formatter->format($this->getRecord(
- Level::Debug,
- 'Testing',
- channel: 'test',
- datetime: new \DateTimeImmutable('2022-02-22 00:00:00'),
- ));
- $this->assertSame(
- '{"message":"Testing","level":100,"level_name":"DEBUG","channel":"test","datetime":"2022-02-22T00:00:00+00:00"}'."\n",
- $record
- );
- }
- }
|