| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298 |
- <?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\Logger;
- 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();
- $record['context'] = $record['extra'] = new \stdClass;
- $this->assertEquals(json_encode($record)."\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();
- $record['context'] = $record['extra'] = new \stdClass;
- $this->assertEquals(json_encode($record, JSON_PRETTY_PRINT)."\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(Logger::WARNING),
- $this->getRecord(Logger::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 = $expected = [
- $this->getRecord(Logger::WARNING),
- $this->getRecord(Logger::DEBUG),
- ];
- array_walk($expected, function (&$value, $key) {
- $value['context'] = $value['extra'] = new \stdClass;
- $value = json_encode($value);
- });
- $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 (6 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(
- '{"level_name":"CRITICAL","channel":"core","...":"Over 2 items (6 total), aborting normalization"}'."\n",
- $message
- );
- }
- public function testDefFormatWithResource()
- {
- $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false);
- $record = $this->getRecord();
- $record['context'] = ['field_resource' => curl_init()];
- $this->assertEquals('{"message":"test","context":{"field_resource":"[resource(curl)]"},"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(
- '{"level_name":"CRITICAL","channel":"core","context":{"exception":'.$expected.'},"datetime":null,"extra":{},"message":"foobar"}'."\n",
- $actual
- );
- }
- /**
- * @param JsonFormatter $formatter
- * @param \Throwable $exception
- *
- * @return string
- */
- private function formatRecordWithExceptionInContext(JsonFormatter $formatter, \Throwable $exception)
- {
- $message = $formatter->format([
- 'level_name' => 'CRITICAL',
- 'channel' => 'core',
- 'context' => ['exception' => $exception],
- 'datetime' => null,
- 'extra' => [],
- 'message' => 'foobar',
- ]);
- 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(array(
- 'level_name' => 'CRITICAL',
- 'channel' => 'test',
- 'message' => 'bar',
- 'context' => array($largeArray),
- 'datetime' => new \DateTime,
- 'extra' => array(),
- ));
- $this->assertCount(1000, $res['context'][0]);
- $this->assertArrayNotHasKey('...', $res['context'][0]);
- }
- public function testNormalizeHandleLargeArrays()
- {
- $formatter = new NormalizerFormatter();
- $largeArray = range(1, 2000);
- $res = $formatter->format(array(
- 'level_name' => 'CRITICAL',
- 'channel' => 'test',
- 'message' => 'bar',
- 'context' => array($largeArray),
- 'datetime' => new \DateTime,
- 'extra' => array(),
- ));
- $this->assertCount(1001, $res['context'][0]);
- $this->assertEquals('Over 1000 items (2000 total), aborting normalization', $res['context'][0]['...']);
- }
- }
|