1
0
mirror of https://github.com/Seldaek/monolog.git synced 2025-10-17 06:36:48 +02:00

Fix some issues, bump phpunit version

This commit is contained in:
Jordi Boggiano
2022-02-26 15:09:41 +01:00
parent 22c8b19358
commit 400effdd45
45 changed files with 602 additions and 774 deletions

View File

@@ -25,7 +25,7 @@
"php-amqplib/php-amqplib": "~2.4 || ^3", "php-amqplib/php-amqplib": "~2.4 || ^3",
"php-console/php-console": "^3.1.3", "php-console/php-console": "^3.1.3",
"phpspec/prophecy": "^1.6.1", "phpspec/prophecy": "^1.6.1",
"phpunit/phpunit": "^9", "phpunit/phpunit": "^9.5.16",
"predis/predis": "^1.1", "predis/predis": "^1.1",
"rollbar/rollbar": "^3", "rollbar/rollbar": "^3",
"ruflin/elastica": ">=0.90@dev", "ruflin/elastica": ">=0.90@dev",

View File

@@ -80,7 +80,7 @@ class ElasticsearchFormatter extends NormalizerFormatter
* @param mixed[] $record Log message * @param mixed[] $record Log message
* @return mixed[] * @return mixed[]
*/ */
protected function getDocument(LogRecord $record): array protected function getDocument(array $record): array
{ {
$record['_index'] = $this->index; $record['_index'] = $this->index;
$record['_type'] = $this->type; $record['_type'] = $this->type;

View File

@@ -60,7 +60,7 @@ class FlowdockFormatter implements FormatterInterface
$this->getShortMessage($record['message']) $this->getShortMessage($record['message'])
); );
$record['flowdock'] = [ return [
'source' => $this->source, 'source' => $this->source,
'from_address' => $this->sourceEmail, 'from_address' => $this->sourceEmail,
'subject' => $subject, 'subject' => $subject,
@@ -68,8 +68,6 @@ class FlowdockFormatter implements FormatterInterface
'tags' => $tags, 'tags' => $tags,
'project' => $this->source, 'project' => $this->source,
]; ];
return $record;
} }
/** /**

View File

@@ -96,10 +96,6 @@ class GelfMessageFormatter extends NormalizerFormatter
$extra = parent::normalize($record['extra']); $extra = parent::normalize($record['extra']);
} }
if (!isset($record['datetime'], $record['message'], $record['level'])) {
throw new \InvalidArgumentException('The record should at least contain datetime, message and level keys, '.var_export($record, true).' given');
}
$message = new Message(); $message = new Message();
$message $message
->setTimestamp($record['datetime']) ->setTimestamp($record['datetime'])

View File

@@ -75,7 +75,7 @@ class JsonFormatter extends NormalizerFormatter
*/ */
public function format(LogRecord $record): string public function format(LogRecord $record): string
{ {
$normalized = $this->normalize($record); $normalized = parent::format($record);
if (isset($normalized['context']) && $normalized['context'] === []) { if (isset($normalized['context']) && $normalized['context'] === []) {
if ($this->ignoreEmptyContextAndExtra) { if ($this->ignoreEmptyContextAndExtra) {
@@ -157,7 +157,7 @@ class JsonFormatter extends NormalizerFormatter
* *
* @return mixed * @return mixed
*/ */
protected function normalize($data, int $depth = 0) protected function normalize(mixed $data, int $depth = 0): mixed
{ {
if ($depth > $this->maxNormalizeDepth) { if ($depth > $this->maxNormalizeDepth) {
return 'Over '.$this->maxNormalizeDepth.' levels deep, aborting normalization'; return 'Over '.$this->maxNormalizeDepth.' levels deep, aborting normalization';

View File

@@ -82,7 +82,6 @@ class LineFormatter extends NormalizerFormatter
$vars = parent::format($record); $vars = parent::format($record);
$output = $this->format; $output = $this->format;
foreach ($vars['extra'] as $var => $val) { foreach ($vars['extra'] as $var => $val) {
if (false !== strpos($output, '%extra.'.$var.'%')) { if (false !== strpos($output, '%extra.'.$var.'%')) {
$output = str_replace('%extra.'.$var.'%', $this->stringify($val), $output); $output = str_replace('%extra.'.$var.'%', $this->stringify($val), $output);

View File

@@ -35,13 +35,13 @@ class LogglyFormatter extends JsonFormatter
* @see https://www.loggly.com/docs/automated-parsing/#json * @see https://www.loggly.com/docs/automated-parsing/#json
* @see \Monolog\Formatter\JsonFormatter::format() * @see \Monolog\Formatter\JsonFormatter::format()
*/ */
public function format(LogRecord $record): string protected function normalizeRecord(LogRecord $record): array
{ {
if (isset($record["datetime"]) && ($record["datetime"] instanceof \DateTimeInterface)) { $recordData = parent::normalizeRecord($record);
$record["timestamp"] = $record["datetime"]->format("Y-m-d\TH:i:s.uO");
unset($record["datetime"]);
}
return parent::format($record); $recordData["timestamp"] = $record->datetime->format("Y-m-d\TH:i:s.uO");
unset($recordData["datetime"]);
return $recordData;
} }
} }

View File

@@ -52,8 +52,10 @@ class LogmaticFormatter extends JsonFormatter
* @see http://doc.logmatic.io/docs/basics-to-send-data * @see http://doc.logmatic.io/docs/basics-to-send-data
* @see \Monolog\Formatter\JsonFormatter::format() * @see \Monolog\Formatter\JsonFormatter::format()
*/ */
public function format(LogRecord $record): string public function normalizeRecord(LogRecord $record): array
{ {
$record = parent::normalizeRecord($record);
if (!empty($this->hostname)) { if (!empty($this->hostname)) {
$record["hostname"] = $this->hostname; $record["hostname"] = $this->hostname;
} }
@@ -63,6 +65,6 @@ class LogmaticFormatter extends JsonFormatter
$record["@marker"] = static::MARKERS; $record["@marker"] = static::MARKERS;
return parent::format($record); return $record;
} }
} }

View File

@@ -50,7 +50,7 @@ class MongoDBFormatter implements FormatterInterface
public function format(LogRecord $record): array public function format(LogRecord $record): array
{ {
/** @var mixed[] $res */ /** @var mixed[] $res */
$res = $this->formatArray($record); $res = $this->formatArray($record->toArray());
return $res; return $res;
} }

View File

@@ -53,9 +53,12 @@ class NormalizerFormatter implements FormatterInterface
*/ */
public function format(LogRecord $record) public function format(LogRecord $record)
{ {
$record = $record->toArray(); return $this->normalizeRecord($record);
}
return $this->normalize($record); public function normalizeValue(mixed $data): mixed
{
return $this->normalize($data);
} }
/** /**
@@ -126,11 +129,22 @@ class NormalizerFormatter implements FormatterInterface
return $this; return $this;
} }
/**
* Provided as extension point
*
* Because normalize is called with sub-values of context data etc, normalizeRecord can be
* extended when data needs to be appended on the record array but not to other normalized data.
*/
protected function normalizeRecord(LogRecord $record): array
{
return $this->normalize($record->toArray());
}
/** /**
* @param mixed $data * @param mixed $data
* @return null|scalar|array<array|scalar|null> * @return null|scalar|array<array|scalar|null>
*/ */
protected function normalize($data, int $depth = 0) protected function normalize(mixed $data, int $depth = 0): mixed
{ {
if ($depth > $this->maxNormalizeDepth) { if ($depth > $this->maxNormalizeDepth) {
return 'Over ' . $this->maxNormalizeDepth . ' levels deep, aborting normalization'; return 'Over ' . $this->maxNormalizeDepth . ' levels deep, aborting normalization';

View File

@@ -14,7 +14,7 @@ namespace Monolog\Formatter;
use Monolog\LogRecord; use Monolog\LogRecord;
/** /**
* Formats data into an associative array of scalar values. * Formats data into an associative array of scalar (+ null) values.
* Objects and arrays will be JSON encoded. * Objects and arrays will be JSON encoded.
* *
* @author Andrew Lawson <adlawson@gmail.com> * @author Andrew Lawson <adlawson@gmail.com>
@@ -29,18 +29,14 @@ class ScalarFormatter extends NormalizerFormatter
public function format(LogRecord $record): array public function format(LogRecord $record): array
{ {
$result = []; $result = [];
foreach ($record as $key => $value) { foreach ($record->toArray() as $key => $value) {
$result[$key] = $this->normalizeValue($value); $result[$key] = $this->toScalar($value);
} }
return $result; return $result;
} }
/** protected function toScalar(mixed $value): string|int|float|bool|null
* @param mixed $value
* @return scalar|null
*/
protected function normalizeValue($value)
{ {
$normalized = $this->normalize($value); $normalized = $this->normalize($value);

View File

@@ -129,7 +129,7 @@ class WildfireFormatter extends NormalizerFormatter
* *
* @return null|scalar|array<array|scalar|null>|object * @return null|scalar|array<array|scalar|null>|object
*/ */
protected function normalize($data, int $depth = 0) protected function normalize(mixed $data, int $depth = 0): mixed
{ {
if (is_object($data) && !$data instanceof \DateTimeInterface) { if (is_object($data) && !$data instanceof \DateTimeInterface) {
return $data; return $data;

View File

@@ -16,6 +16,7 @@ use Monolog\Formatter\FormatterInterface;
use Monolog\Logger; use Monolog\Logger;
use Monolog\Utils; use Monolog\Utils;
use Monolog\LogRecord; use Monolog\LogRecord;
use Monolog\DateTimeImmutable;
/** /**
* Handler sending logs to the ChromePHP extension (http://www.chromephp.com/) * Handler sending logs to the ChromePHP extension (http://www.chromephp.com/)
@@ -154,15 +155,12 @@ class ChromePHPHandler extends AbstractProcessingHandler
if (strlen($data) > 3 * 1024) { if (strlen($data) > 3 * 1024) {
self::$overflowed = true; self::$overflowed = true;
$record = [ $record = new LogRecord(
'message' => 'Incomplete logs, chrome header size limit reached', message: 'Incomplete logs, chrome header size limit reached',
'context' => [], level: Logger::WARNING,
'level' => Logger::WARNING, channel: 'monolog',
'level_name' => Logger::getLevelName(Logger::WARNING), datetime: new DateTimeImmutable(true),
'channel' => 'monolog', );
'datetime' => new \DateTimeImmutable(),
'extra' => [],
];
self::$json['rows'][count(self::$json['rows']) - 1] = $this->getFormatter()->format($record); self::$json['rows'][count(self::$json['rows']) - 1] = $this->getFormatter()->format($record);
$json = Utils::jsonEncode(self::$json, null, true); $json = Utils::jsonEncode(self::$json, null, true);
$data = base64_encode(utf8_encode($json)); $data = base64_encode(utf8_encode($json));

View File

@@ -88,7 +88,7 @@ class DynamoDbHandler extends AbstractProcessingHandler
* @param mixed[] $record * @param mixed[] $record
* @return mixed[] * @return mixed[]
*/ */
protected function filterEmptyFields(LogRecord $record): array protected function filterEmptyFields(array $record): array
{ {
return array_filter($record, function ($value) { return array_filter($record, function ($value) {
return !empty($value) || false === $value || 0 === $value; return !empty($value) || false === $value || 0 === $value;

View File

@@ -114,7 +114,7 @@ class FlowdockHandler extends SocketHandler
*/ */
private function buildContent(LogRecord $record): string private function buildContent(LogRecord $record): string
{ {
return Utils::jsonEncode($record['formatted']['flowdock']); return Utils::jsonEncode($record['formatted']);
} }
/** /**

View File

@@ -51,7 +51,7 @@ abstract class MailHandler extends AbstractProcessingHandler
* @param string $content formatted email body to be sent * @param string $content formatted email body to be sent
* @param array $records the array of log records that formed this content * @param array $records the array of log records that formed this content
* *
* @phpstan-param Record[] $records * @phpstan-param non-empty-array<LogRecord> $records
*/ */
abstract protected function send(string $content, array $records): void; abstract protected function send(string $content, array $records): void;
@@ -64,10 +64,9 @@ abstract class MailHandler extends AbstractProcessingHandler
} }
/** /**
* @phpstan-param non-empty-array<Record> $records * @phpstan-param non-empty-array<LogRecord> $records
* @phpstan-return Record
*/ */
protected function getHighestRecord(array $records): array protected function getHighestRecord(array $records): LogRecord
{ {
$highestRecord = null; $highestRecord = null;
foreach ($records as $record) { foreach ($records as $record) {

View File

@@ -196,10 +196,10 @@ class PHPConsoleHandler extends AbstractProcessingHandler
*/ */
private function handleDebugRecord(LogRecord $record): void private function handleDebugRecord(LogRecord $record): void
{ {
$tags = $this->getRecordTags($record); [$tags, $filteredContext] = $this->getRecordTags($record);
$message = $record['message']; $message = $record['message'];
if ($record['context']) { if ($filteredContext) {
$message .= ' ' . Utils::jsonEncode($this->connector->getDumper()->dump(array_filter($record['context'])), null, true); $message .= ' ' . Utils::jsonEncode($this->connector->getDumper()->dump(array_filter($filteredContext)), null, true);
} }
$this->connector->getDebugDispatcher()->dispatchDebug($message, $tags, $this->options['classesPartialsTraceIgnore']); $this->connector->getDebugDispatcher()->dispatchDebug($message, $tags, $this->options['classesPartialsTraceIgnore']);
} }
@@ -217,7 +217,7 @@ class PHPConsoleHandler extends AbstractProcessingHandler
*/ */
private function handleErrorRecord(LogRecord $record): void private function handleErrorRecord(LogRecord $record): void
{ {
$context = $record['context']; $context = $record->context;
$this->connector->getErrorsDispatcher()->dispatchError( $this->connector->getErrorsDispatcher()->dispatchError(
$context['code'] ?? null, $context['code'] ?? null,
@@ -229,28 +229,28 @@ class PHPConsoleHandler extends AbstractProcessingHandler
} }
/** /**
* @phpstan-param Record $record * @return array{string, mixed[]}
* @return string
*/ */
private function getRecordTags(array &$record) private function getRecordTags(LogRecord $record): array
{ {
$tags = null; $tags = null;
if (!empty($record['context'])) { $filteredContext = [];
$context = & $record['context']; if ($record->context !== []) {
$filteredContext = $record->context;
foreach ($this->options['debugTagsKeysInContext'] as $key) { foreach ($this->options['debugTagsKeysInContext'] as $key) {
if (!empty($context[$key])) { if (!empty($filteredContext[$key])) {
$tags = $context[$key]; $tags = $filteredContext[$key];
if ($key === 0) { if ($key === 0) {
array_shift($context); array_shift($filteredContext);
} else { } else {
unset($context[$key]); unset($filteredContext[$key]);
} }
break; break;
} }
} }
} }
return $tags ?: strtolower($record['level_name']); return [$tags ?: strtolower($record->levelName), $filteredContext];
} }
/** /**

View File

@@ -128,7 +128,6 @@ class SlackRecord
public function getSlackData(LogRecord $record): array public function getSlackData(LogRecord $record): array
{ {
$dataArray = array(); $dataArray = array();
$record = $this->removeExcludedFields($record);
if ($this->username) { if ($this->username) {
$dataArray['username'] = $this->username; $dataArray['username'] = $this->username;
@@ -142,9 +141,11 @@ class SlackRecord
/** @phpstan-ignore-next-line */ /** @phpstan-ignore-next-line */
$message = $this->formatter->format($record); $message = $this->formatter->format($record);
} else { } else {
$message = $record['message']; $message = $record->message;
} }
$record = $this->removeExcludedFields($record);
if ($this->useAttachment) { if ($this->useAttachment) {
$attachment = array( $attachment = array(
'fallback' => $message, 'fallback' => $message,
@@ -226,8 +227,7 @@ class SlackRecord
*/ */
public function stringify(array $fields): string public function stringify(array $fields): string
{ {
/** @var Record $fields */ $normalized = $this->normalizerFormatter->normalizeValue($fields);
$normalized = $this->normalizerFormatter->format($fields);
$hasSecondDimension = count(array_filter($normalized, 'is_array')); $hasSecondDimension = count(array_filter($normalized, 'is_array'));
$hasNonNumericKeys = !count(array_filter(array_keys($normalized), 'is_numeric')); $hasNonNumericKeys = !count(array_filter(array_keys($normalized), 'is_numeric'));
@@ -347,8 +347,7 @@ class SlackRecord
*/ */
private function generateAttachmentFields(array $data): array private function generateAttachmentFields(array $data): array
{ {
/** @var Record $data */ $normalized = $this->normalizerFormatter->normalizeValue($data);
$normalized = $this->normalizerFormatter->format($data);
$fields = array(); $fields = array();
foreach ($normalized as $key => $value) { foreach ($normalized as $key => $value) {
@@ -367,6 +366,7 @@ class SlackRecord
*/ */
private function removeExcludedFields(LogRecord $record): array private function removeExcludedFields(LogRecord $record): array
{ {
$record = $record->toArray();
foreach ($this->excludeFields as $field) { foreach ($this->excludeFields as $field) {
$keys = explode('.', $field); $keys = explode('.', $field);
$node = &$record; $node = &$record;

View File

@@ -14,6 +14,7 @@ namespace Monolog\Handler;
use Monolog\Logger; use Monolog\Logger;
use Psr\Log\LogLevel; use Psr\Log\LogLevel;
use Monolog\LogRecord; use Monolog\LogRecord;
use Monolog\DateTimeImmutable;
/** /**
* Used for testing purposes. * Used for testing purposes.
@@ -125,16 +126,16 @@ class TestHandler extends AbstractProcessingHandler
} }
/** /**
* @param string|LogRecord $record Either a message string or an array containing message and optionally context keys that will be checked against all records * @param string|array $record Either a message string or an array containing message and optionally context keys that will be checked against all records
* @param string|int $level Logging level value or name * @param string|int $level Logging level value or name
* *
* @phpstan-param array{message: string, context?: mixed[]}|string $record * @phpstan-param array{message: string, context?: mixed[]}|string $record
* @phpstan-param Level|LevelName|LogLevel::* $level * @phpstan-param Level|LevelName|LogLevel::* $level
*/ */
public function hasRecord($record, $level): bool public function hasRecord(string|array $record, $level): bool
{ {
if (is_string($record)) { if (is_string($record)) {
$record = array('message' => $record); $record = ['message' => $record];
} }
return $this->hasRecordThatPasses(function (LogRecord $rec) use ($record) { return $this->hasRecordThatPasses(function (LogRecord $rec) use ($record) {
@@ -168,8 +169,8 @@ class TestHandler extends AbstractProcessingHandler
*/ */
public function hasRecordThatMatches(string $regex, $level): bool public function hasRecordThatMatches(string $regex, $level): bool
{ {
return $this->hasRecordThatPasses(function (array $rec) use ($regex): bool { return $this->hasRecordThatPasses(function (LogRecord $rec) use ($regex): bool {
return preg_match($regex, $rec['message']) > 0; return preg_match($regex, $rec->message) > 0;
}, $level); }, $level);
} }
@@ -202,7 +203,7 @@ class TestHandler extends AbstractProcessingHandler
*/ */
protected function write(LogRecord $record): void protected function write(LogRecord $record): void
{ {
$this->recordsByLevel[$record['level']][] = $record; $this->recordsByLevel[$record->level][] = $record;
$this->records[] = $record; $this->records[] = $record;
} }

View File

@@ -301,6 +301,7 @@ class Logger implements LoggerInterface, ResettableInterface
datetime: new DateTimeImmutable($this->microsecondTimestamps, $this->timezone), datetime: new DateTimeImmutable($this->microsecondTimestamps, $this->timezone),
extra: [], extra: [],
); );
$handled = false;
foreach ($this->handlers as $handler) { foreach ($this->handlers as $handler) {
if (false === $recordInitialized) { if (false === $recordInitialized) {
@@ -323,6 +324,7 @@ class Logger implements LoggerInterface, ResettableInterface
// once the record is initialized, send it to all handlers as long as the bubbling chain is not interrupted // once the record is initialized, send it to all handlers as long as the bubbling chain is not interrupted
try { try {
$handled = true;
if (true === $handler->handle($record)) { if (true === $handler->handle($record)) {
break; break;
} }
@@ -333,7 +335,7 @@ class Logger implements LoggerInterface, ResettableInterface
} }
} }
return null !== $record; return $handled;
} }
/** /**

View File

@@ -12,8 +12,9 @@
namespace Monolog\Formatter; namespace Monolog\Formatter;
use Monolog\Logger; use Monolog\Logger;
use Monolog\Test\TestCase;
class ChromePHPFormatterTest extends \PHPUnit\Framework\TestCase class ChromePHPFormatterTest extends TestCase
{ {
/** /**
* @covers Monolog\Formatter\ChromePHPFormatter::format * @covers Monolog\Formatter\ChromePHPFormatter::format
@@ -21,15 +22,14 @@ class ChromePHPFormatterTest extends \PHPUnit\Framework\TestCase
public function testDefaultFormat() public function testDefaultFormat()
{ {
$formatter = new ChromePHPFormatter(); $formatter = new ChromePHPFormatter();
$record = [ $record = $this->getRecord(
'level' => Logger::ERROR, Logger::ERROR,
'level_name' => 'ERROR', 'log',
'channel' => 'meh', channel: 'meh',
'context' => ['from' => 'logger'], context: ['from' => 'logger'],
'datetime' => new \DateTimeImmutable("@0"), datetime: new \DateTimeImmutable("@0"),
'extra' => ['ip' => '127.0.0.1'], extra: ['ip' => '127.0.0.1'],
'message' => 'log', );
];
$message = $formatter->format($record); $message = $formatter->format($record);
@@ -54,15 +54,14 @@ class ChromePHPFormatterTest extends \PHPUnit\Framework\TestCase
public function testFormatWithFileAndLine() public function testFormatWithFileAndLine()
{ {
$formatter = new ChromePHPFormatter(); $formatter = new ChromePHPFormatter();
$record = [ $record = $this->getRecord(
'level' => Logger::CRITICAL, Logger::CRITICAL,
'level_name' => 'CRITICAL', 'log',
'channel' => 'meh', channel: 'meh',
'context' => ['from' => 'logger'], context: ['from' => 'logger'],
'datetime' => new \DateTimeImmutable("@0"), datetime: new \DateTimeImmutable("@0"),
'extra' => ['ip' => '127.0.0.1', 'file' => 'test', 'line' => 14], extra: ['ip' => '127.0.0.1', 'file' => 'test', 'line' => 14],
'message' => 'log', );
];
$message = $formatter->format($record); $message = $formatter->format($record);
@@ -87,15 +86,12 @@ class ChromePHPFormatterTest extends \PHPUnit\Framework\TestCase
public function testFormatWithoutContext() public function testFormatWithoutContext()
{ {
$formatter = new ChromePHPFormatter(); $formatter = new ChromePHPFormatter();
$record = [ $record = $this->getRecord(
'level' => Logger::DEBUG, Logger::DEBUG,
'level_name' => 'DEBUG', 'log',
'channel' => 'meh', channel: 'meh',
'context' => [], datetime: new \DateTimeImmutable("@0"),
'datetime' => new \DateTimeImmutable("@0"), );
'extra' => [],
'message' => 'log',
];
$message = $formatter->format($record); $message = $formatter->format($record);
@@ -117,24 +113,18 @@ class ChromePHPFormatterTest extends \PHPUnit\Framework\TestCase
{ {
$formatter = new ChromePHPFormatter(); $formatter = new ChromePHPFormatter();
$records = [ $records = [
[ $this->getRecord(
'level' => Logger::INFO, Logger::INFO,
'level_name' => 'INFO', 'log',
'channel' => 'meh', channel: 'meh',
'context' => [], datetime: new \DateTimeImmutable("@0"),
'datetime' => new \DateTimeImmutable("@0"), ),
'extra' => [], $this->getRecord(
'message' => 'log', Logger::WARNING,
], 'log2',
[ channel: 'foo',
'level' => Logger::WARNING, datetime: new \DateTimeImmutable("@0"),
'level_name' => 'WARNING', ),
'channel' => 'foo',
'context' => [],
'datetime' => new \DateTimeImmutable("@0"),
'extra' => [],
'message' => 'log2',
],
]; ];
$this->assertEquals( $this->assertEquals(

View File

@@ -13,8 +13,9 @@ namespace Monolog\Formatter;
use Monolog\Logger; use Monolog\Logger;
use Monolog\LogRecord; use Monolog\LogRecord;
use Monolog\Test\TestCase;
class ElasticaFormatterTest extends \PHPUnit\Framework\TestCase class ElasticaFormatterTest extends TestCase
{ {
public function setUp(): void public function setUp(): void
{ {
@@ -31,18 +32,16 @@ class ElasticaFormatterTest extends \PHPUnit\Framework\TestCase
public function testFormat() public function testFormat()
{ {
// test log message // test log message
$msg = new LogRecord( $msg = $this->getRecord(
level: Logger::ERROR, Logger::ERROR,
levelName: 'ERROR', 'log',
channel: 'meh', channel: 'meh',
context: ['foo' => 7, 'bar', 'class' => new \stdClass], context: ['foo' => 7, 'bar', 'class' => new \stdClass],
datetime: new \DateTimeImmutable("@0"), datetime: new \DateTimeImmutable("@0"),
message: 'log',
); );
// expected values // expected values
$expected = (array) $msg; $expected = $msg->toArray();
unset($expected['formatted']);
$expected['datetime'] = '1970-01-01T00:00:00.000000+00:00'; $expected['datetime'] = '1970-01-01T00:00:00.000000+00:00';
$expected['context'] = [ $expected['context'] = [
'class' => ['stdClass' => []], 'class' => ['stdClass' => []],

View File

@@ -12,8 +12,9 @@
namespace Monolog\Formatter; namespace Monolog\Formatter;
use Monolog\Logger; use Monolog\Logger;
use Monolog\Test\TestCase;
class ElasticsearchFormatterTest extends \PHPUnit\Framework\TestCase class ElasticsearchFormatterTest extends TestCase
{ {
/** /**
* @covers Monolog\Formatter\ElasticsearchFormatter::__construct * @covers Monolog\Formatter\ElasticsearchFormatter::__construct
@@ -23,18 +24,16 @@ class ElasticsearchFormatterTest extends \PHPUnit\Framework\TestCase
public function testFormat() public function testFormat()
{ {
// Test log message // Test log message
$msg = [ $msg = $this->getRecord(
'level' => Logger::ERROR, Logger::ERROR,
'level_name' => 'ERROR', 'log',
'channel' => 'meh', channel: 'meh',
'context' => ['foo' => 7, 'bar', 'class' => new \stdClass], context: ['foo' => 7, 'bar', 'class' => new \stdClass],
'datetime' => new \DateTimeImmutable("@0"), datetime: new \DateTimeImmutable("@0"),
'extra' => [], );
'message' => 'log',
];
// Expected values // Expected values
$expected = $msg; $expected = $msg->toArray();
$expected['datetime'] = '1970-01-01T00:00:00+0000'; $expected['datetime'] = '1970-01-01T00:00:00+0000';
$expected['context'] = [ $expected['context'] = [
'class' => ['stdClass' => []], 'class' => ['stdClass' => []],

View File

@@ -34,7 +34,7 @@ class FlowdockFormatterTest extends TestCase
]; ];
$formatted = $formatter->format($record); $formatted = $formatter->format($record);
$this->assertEquals($expected, $formatted['flowdock']); $this->assertEquals($expected, $formatted);
} }
/** /**
@@ -49,7 +49,7 @@ class FlowdockFormatterTest extends TestCase
]; ];
$formatted = $formatter->formatBatch($records); $formatted = $formatter->formatBatch($records);
$this->assertArrayHasKey('flowdock', $formatted[0]); $this->assertArrayHasKey('from_address', $formatted[0]);
$this->assertArrayHasKey('flowdock', $formatted[1]); $this->assertArrayHasKey('from_address', $formatted[1]);
} }
} }

View File

@@ -35,8 +35,7 @@ class FluentdFormatterTest extends TestCase
*/ */
public function testFormat() public function testFormat()
{ {
$record = $this->getRecord(Logger::WARNING); $record = $this->getRecord(Logger::WARNING, datetime: new \DateTimeImmutable("@0"));
$record['datetime'] = new \DateTimeImmutable("@0");
$formatter = new FluentdFormatter(); $formatter = new FluentdFormatter();
$this->assertEquals( $this->assertEquals(
@@ -50,8 +49,7 @@ class FluentdFormatterTest extends TestCase
*/ */
public function testFormatWithTag() public function testFormatWithTag()
{ {
$record = $this->getRecord(Logger::ERROR); $record = $this->getRecord(Logger::ERROR, datetime: new \DateTimeImmutable("@0"));
$record['datetime'] = new \DateTimeImmutable("@0");
$formatter = new FluentdFormatter(true); $formatter = new FluentdFormatter(true);
$this->assertEquals( $this->assertEquals(

View File

@@ -12,7 +12,7 @@
namespace Monolog\Formatter; namespace Monolog\Formatter;
use Monolog\Logger; use Monolog\Logger;
use PHPUnit\Framework\TestCase; use Monolog\Test\TestCase;
class GelfMessageFormatterTest extends TestCase class GelfMessageFormatterTest extends TestCase
{ {
@@ -29,15 +29,12 @@ class GelfMessageFormatterTest extends TestCase
public function testDefaultFormatter() public function testDefaultFormatter()
{ {
$formatter = new GelfMessageFormatter(); $formatter = new GelfMessageFormatter();
$record = [ $record = $this->getRecord(
'level' => Logger::ERROR, Logger::ERROR,
'level_name' => 'ERROR', 'log',
'channel' => 'meh', channel: 'meh',
'context' => [], datetime: new \DateTimeImmutable("@0"),
'datetime' => new \DateTimeImmutable("@0"), );
'extra' => [],
'message' => 'log',
];
$message = $formatter->format($record); $message = $formatter->format($record);
@@ -64,15 +61,14 @@ class GelfMessageFormatterTest extends TestCase
public function testFormatWithFileAndLine() public function testFormatWithFileAndLine()
{ {
$formatter = new GelfMessageFormatter(); $formatter = new GelfMessageFormatter();
$record = [ $record = $this->getRecord(
'level' => Logger::ERROR, Logger::ERROR,
'level_name' => 'ERROR', 'log',
'channel' => 'meh', channel: 'meh',
'context' => ['from' => 'logger'], context: ['from' => 'logger'],
'datetime' => new \DateTimeImmutable("@0"), datetime: new \DateTimeImmutable("@0"),
'extra' => ['file' => 'test', 'line' => 14], extra: ['file' => 'test', 'line' => 14],
'message' => 'log', );
];
$message = $formatter->format($record); $message = $formatter->format($record);
@@ -81,37 +77,20 @@ class GelfMessageFormatterTest extends TestCase
$this->assertEquals(14, $message->getLine()); $this->assertEquals(14, $message->getLine());
} }
/**
* @covers Monolog\Formatter\GelfMessageFormatter::format
*/
public function testFormatInvalidFails()
{
$formatter = new GelfMessageFormatter();
$record = [
'level' => Logger::ERROR,
'level_name' => 'ERROR',
];
$this->expectException(\InvalidArgumentException::class);
$formatter->format($record);
}
/** /**
* @covers Monolog\Formatter\GelfMessageFormatter::format * @covers Monolog\Formatter\GelfMessageFormatter::format
*/ */
public function testFormatWithContext() public function testFormatWithContext()
{ {
$formatter = new GelfMessageFormatter(); $formatter = new GelfMessageFormatter();
$record = [ $record = $this->getRecord(
'level' => Logger::ERROR, Logger::ERROR,
'level_name' => 'ERROR', 'log',
'channel' => 'meh', channel: 'meh',
'context' => ['from' => 'logger'], context: ['from' => 'logger'],
'datetime' => new \DateTimeImmutable("@0"), datetime: new \DateTimeImmutable("@0"),
'extra' => ['key' => 'pair'], extra: ['key' => 'pair'],
'message' => 'log', );
];
$message = $formatter->format($record); $message = $formatter->format($record);
@@ -140,19 +119,17 @@ class GelfMessageFormatterTest extends TestCase
public function testFormatWithContextContainingException() public function testFormatWithContextContainingException()
{ {
$formatter = new GelfMessageFormatter(); $formatter = new GelfMessageFormatter();
$record = [ $record = $this->getRecord(
'level' => Logger::ERROR, Logger::ERROR,
'level_name' => 'ERROR', 'log',
'channel' => 'meh', channel: 'meh',
'context' => ['from' => 'logger', 'exception' => [ context: ['from' => 'logger', 'exception' => [
'class' => '\Exception', 'class' => '\Exception',
'file' => '/some/file/in/dir.php:56', 'file' => '/some/file/in/dir.php:56',
'trace' => ['/some/file/1.php:23', '/some/file/2.php:3'], 'trace' => ['/some/file/1.php:23', '/some/file/2.php:3'],
]], ]],
'datetime' => new \DateTimeImmutable("@0"), datetime: new \DateTimeImmutable("@0"),
'extra' => [], );
'message' => 'log',
];
$message = $formatter->format($record); $message = $formatter->format($record);
@@ -168,15 +145,14 @@ class GelfMessageFormatterTest extends TestCase
public function testFormatWithExtra() public function testFormatWithExtra()
{ {
$formatter = new GelfMessageFormatter(); $formatter = new GelfMessageFormatter();
$record = [ $record = $this->getRecord(
'level' => Logger::ERROR, Logger::ERROR,
'level_name' => 'ERROR', 'log',
'channel' => 'meh', channel: 'meh',
'context' => ['from' => 'logger'], context: ['from' => 'logger'],
'datetime' => new \DateTimeImmutable("@0"), datetime: new \DateTimeImmutable("@0"),
'extra' => ['key' => 'pair'], extra: ['key' => 'pair'],
'message' => 'log', );
];
$message = $formatter->format($record); $message = $formatter->format($record);
@@ -202,15 +178,14 @@ class GelfMessageFormatterTest extends TestCase
public function testFormatWithLargeData() public function testFormatWithLargeData()
{ {
$formatter = new GelfMessageFormatter(); $formatter = new GelfMessageFormatter();
$record = [ $record = $this->getRecord(
'level' => Logger::ERROR, Logger::ERROR,
'level_name' => 'ERROR', 'log',
'channel' => 'meh', channel: 'meh',
'context' => ['exception' => str_repeat(' ', 32767)], context: ['exception' => str_repeat(' ', 32767)],
'datetime' => new \DateTimeImmutable("@0"), datetime: new \DateTimeImmutable("@0"),
'extra' => ['key' => str_repeat(' ', 32767)], extra: ['key' => str_repeat(' ', 32767)],
'message' => 'log', );
];
$message = $formatter->format($record); $message = $formatter->format($record);
$messageArray = $message->toArray(); $messageArray = $message->toArray();
@@ -229,14 +204,13 @@ class GelfMessageFormatterTest extends TestCase
public function testFormatWithUnlimitedLength() public function testFormatWithUnlimitedLength()
{ {
$formatter = new GelfMessageFormatter('LONG_SYSTEM_NAME', null, 'ctxt_', PHP_INT_MAX); $formatter = new GelfMessageFormatter('LONG_SYSTEM_NAME', null, 'ctxt_', PHP_INT_MAX);
$record = array( $record = $this->getRecord(
'level' => Logger::ERROR, Logger::ERROR,
'level_name' => 'ERROR', 'log',
'channel' => 'meh', channel: 'meh',
'context' => array('exception' => str_repeat(' ', 32767 * 2)), context: ['exception' => str_repeat(' ', 32767 * 2)],
'datetime' => new \DateTime("@0"), datetime: new \DateTimeImmutable("@0"),
'extra' => array('key' => str_repeat(' ', 32767 * 2)), extra: ['key' => str_repeat(' ', 32767 * 2)],
'message' => 'log',
); );
$message = $formatter->format($record); $message = $formatter->format($record);
$messageArray = $message->toArray(); $messageArray = $message->toArray();
@@ -256,15 +230,14 @@ class GelfMessageFormatterTest extends TestCase
public function testFormatWithLargeCyrillicData() public function testFormatWithLargeCyrillicData()
{ {
$formatter = new GelfMessageFormatter(); $formatter = new GelfMessageFormatter();
$record = [ $record = $this->getRecord(
'level' => Logger::ERROR, Logger::ERROR,
'level_name' => 'ERROR', str_repeat('в', 32767),
'channel' => 'meh', channel: 'meh',
'context' => ['exception' => str_repeat('а', 32767)], context: ['exception' => str_repeat('а', 32767)],
'datetime' => new \DateTimeImmutable("@0"), datetime: new \DateTimeImmutable("@0"),
'extra' => ['key' => str_repeat('б', 32767)], extra: ['key' => str_repeat('б', 32767)],
'message' => str_repeat('в', 32767), );
];
$message = $formatter->format($record); $message = $formatter->format($record);
$messageArray = $message->toArray(); $messageArray = $message->toArray();

View File

@@ -12,6 +12,7 @@
namespace Monolog\Formatter; namespace Monolog\Formatter;
use Monolog\Logger; use Monolog\Logger;
use Monolog\LogRecord;
use Monolog\Test\TestCase; use Monolog\Test\TestCase;
class JsonFormatterTest extends TestCase class JsonFormatterTest extends TestCase
@@ -38,8 +39,7 @@ class JsonFormatterTest extends TestCase
{ {
$formatter = new JsonFormatter(); $formatter = new JsonFormatter();
$record = $this->getRecord(); $record = $this->getRecord();
$record['context'] = $record['extra'] = new \stdClass; $this->assertEquals(json_encode($record->toArray(), JSON_FORCE_OBJECT)."\n", $formatter->format($record));
$this->assertEquals(json_encode($record)."\n", $formatter->format($record));
$formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false); $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false);
$record = $this->getRecord(); $record = $this->getRecord();
@@ -54,8 +54,7 @@ class JsonFormatterTest extends TestCase
$formatter = new JsonFormatter(); $formatter = new JsonFormatter();
$formatter->setJsonPrettyPrint(true); $formatter->setJsonPrettyPrint(true);
$record = $this->getRecord(); $record = $this->getRecord();
$record['context'] = $record['extra'] = new \stdClass; $this->assertEquals(json_encode($record->toArray(), JSON_PRETTY_PRINT | JSON_FORCE_OBJECT)."\n", $formatter->format($record));
$this->assertEquals(json_encode($record, JSON_PRETTY_PRINT)."\n", $formatter->format($record));
$formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false); $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false);
$formatter->setJsonPrettyPrint(true); $formatter->setJsonPrettyPrint(true);
@@ -99,14 +98,11 @@ class JsonFormatterTest extends TestCase
public function testFormatBatchNewlines() public function testFormatBatchNewlines()
{ {
$formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_NEWLINES); $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_NEWLINES);
$records = $expected = [ $records = [
$this->getRecord(Logger::WARNING), $this->getRecord(Logger::WARNING),
$this->getRecord(Logger::DEBUG), $this->getRecord(Logger::DEBUG),
]; ];
array_walk($expected, function (&$value, $key) { $expected = array_map(fn (LogRecord $record) => json_encode($record->toArray(), JSON_FORCE_OBJECT), $records);
$value['context'] = $value['extra'] = new \stdClass;
$value = json_encode($value);
});
$this->assertEquals(implode("\n", $expected), $formatter->formatBatch($records)); $this->assertEquals(implode("\n", $expected), $formatter->formatBatch($records));
} }
@@ -165,7 +161,7 @@ class JsonFormatterTest extends TestCase
$message = $this->formatRecordWithExceptionInContext($formatter, $throwable); $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
$this->assertEquals( $this->assertEquals(
'{"...":"Over 0 items (6 total), aborting normalization"}'."\n", '{"...":"Over 0 items (7 total), aborting normalization"}'."\n",
$message $message
); );
} }
@@ -180,7 +176,7 @@ class JsonFormatterTest extends TestCase
$message = $this->formatRecordWithExceptionInContext($formatter, $throwable); $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
$this->assertEquals( $this->assertEquals(
'{"level_name":"CRITICAL","channel":"core","...":"Over 2 items (6 total), aborting normalization"}'."\n", '{"message":"foobar","context":{"exception":{"class":"Error","message":"Foo","code":0,"file":"'.__FILE__.':'.(__LINE__ - 5).'"}},"...":"Over 2 items (7 total), aborting normalization"}'."\n",
$message $message
); );
} }
@@ -188,8 +184,9 @@ class JsonFormatterTest extends TestCase
public function testDefFormatWithResource() public function testDefFormatWithResource()
{ {
$formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false); $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false);
$record = $this->getRecord(); $record = $this->getRecord(
$record['context'] = ['field_resource' => opendir(__DIR__)]; 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)); $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));
} }
@@ -202,7 +199,7 @@ class JsonFormatterTest extends TestCase
private function assertContextContainsFormattedException($expected, $actual) private function assertContextContainsFormattedException($expected, $actual)
{ {
$this->assertEquals( $this->assertEquals(
'{"level_name":"CRITICAL","channel":"core","context":{"exception":'.$expected.'},"datetime":null,"extra":{},"message":"foobar"}'."\n", '{"message":"foobar","context":{"exception":'.$expected.'},"level":500,"level_name":"CRITICAL","channel":"core","datetime":"2022-02-22T00:00:00+00:00","extra":{}}'."\n",
$actual $actual
); );
} }
@@ -215,14 +212,13 @@ class JsonFormatterTest extends TestCase
*/ */
private function formatRecordWithExceptionInContext(JsonFormatter $formatter, \Throwable $exception) private function formatRecordWithExceptionInContext(JsonFormatter $formatter, \Throwable $exception)
{ {
$message = $formatter->format([ $message = $formatter->format($this->getRecord(
'level_name' => 'CRITICAL', Logger::CRITICAL,
'channel' => 'core', 'foobar',
'context' => ['exception' => $exception], channel: 'core',
'datetime' => null, context: ['exception' => $exception],
'extra' => [], datetime: new \DateTimeImmutable('2022-02-22 00:00:00'),
'message' => 'foobar', ));
]);
return $message; return $message;
} }
@@ -265,13 +261,11 @@ class JsonFormatterTest extends TestCase
$formatter = new NormalizerFormatter(); $formatter = new NormalizerFormatter();
$largeArray = range(1, 1000); $largeArray = range(1, 1000);
$res = $formatter->format(array( $res = $formatter->format($this->getRecord(
'level_name' => 'CRITICAL', Logger::CRITICAL,
'channel' => 'test', 'bar',
'message' => 'bar', channel: 'test',
'context' => array($largeArray), context: array($largeArray),
'datetime' => new \DateTime,
'extra' => array(),
)); ));
$this->assertCount(1000, $res['context'][0]); $this->assertCount(1000, $res['context'][0]);
@@ -283,13 +277,11 @@ class JsonFormatterTest extends TestCase
$formatter = new NormalizerFormatter(); $formatter = new NormalizerFormatter();
$largeArray = range(1, 2000); $largeArray = range(1, 2000);
$res = $formatter->format(array( $res = $formatter->format($this->getRecord(
'level_name' => 'CRITICAL', Logger::CRITICAL,
'channel' => 'test', 'bar',
'message' => 'bar', channel: 'test',
'context' => array($largeArray), context: array($largeArray),
'datetime' => new \DateTime,
'extra' => array(),
)); ));
$this->assertCount(1001, $res['context'][0]); $this->assertCount(1001, $res['context'][0]);
@@ -300,17 +292,15 @@ class JsonFormatterTest extends TestCase
{ {
$formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, true, true); $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, true, true);
$record = $formatter->format(array( $record = $formatter->format($this->getRecord(
'level' => 100, Logger::DEBUG,
'level_name' => 'DEBUG', 'Testing',
'channel' => 'test', channel: 'test',
'message' => 'Testing', datetime: new \DateTimeImmutable('2022-02-22 00:00:00'),
'context' => array(),
'extra' => array(),
)); ));
$this->assertSame( $this->assertSame(
'{"level":100,"level_name":"DEBUG","channel":"test","message":"Testing"}'."\n", '{"message":"Testing","level":100,"level_name":"DEBUG","channel":"test","datetime":"2022-02-22T00:00:00+00:00"}'."\n",
$record $record
); );
} }

View File

@@ -11,111 +11,101 @@
namespace Monolog\Formatter; namespace Monolog\Formatter;
use Monolog\Test\TestCase;
use Monolog\Logger;
/** /**
* @covers Monolog\Formatter\LineFormatter * @covers Monolog\Formatter\LineFormatter
*/ */
class LineFormatterTest extends \PHPUnit\Framework\TestCase class LineFormatterTest extends TestCase
{ {
public function testDefFormatWithString() public function testDefFormatWithString()
{ {
$formatter = new LineFormatter(null, 'Y-m-d'); $formatter = new LineFormatter(null, 'Y-m-d');
$message = $formatter->format([ $message = $formatter->format($this->getRecord(
'level_name' => 'WARNING', Logger::WARNING,
'channel' => 'log', 'foo',
'context' => [], channel: 'log',
'message' => 'foo', ));
'datetime' => new \DateTimeImmutable,
'extra' => [],
]);
$this->assertEquals('['.date('Y-m-d').'] log.WARNING: foo [] []'."\n", $message); $this->assertEquals('['.date('Y-m-d').'] log.WARNING: foo [] []'."\n", $message);
} }
public function testDefFormatWithArrayContext() public function testDefFormatWithArrayContext()
{ {
$formatter = new LineFormatter(null, 'Y-m-d'); $formatter = new LineFormatter(null, 'Y-m-d');
$message = $formatter->format([ $message = $formatter->format($this->getRecord(
'level_name' => 'ERROR', Logger::ERROR,
'channel' => 'meh', 'foo',
'message' => 'foo', channel: 'meh',
'datetime' => new \DateTimeImmutable, context: [
'extra' => [],
'context' => [
'foo' => 'bar', 'foo' => 'bar',
'baz' => 'qux', 'baz' => 'qux',
'bool' => false, 'bool' => false,
'null' => null, 'null' => null,
], ],
]); ));
$this->assertEquals('['.date('Y-m-d').'] meh.ERROR: foo {"foo":"bar","baz":"qux","bool":false,"null":null} []'."\n", $message); $this->assertEquals('['.date('Y-m-d').'] meh.ERROR: foo {"foo":"bar","baz":"qux","bool":false,"null":null} []'."\n", $message);
} }
public function testDefFormatExtras() public function testDefFormatExtras()
{ {
$formatter = new LineFormatter(null, 'Y-m-d'); $formatter = new LineFormatter(null, 'Y-m-d');
$message = $formatter->format([ $message = $formatter->format($this->getRecord(
'level_name' => 'ERROR', Logger::ERROR,
'channel' => 'meh', 'log',
'context' => [], channel: 'meh',
'datetime' => new \DateTimeImmutable, extra: ['ip' => '127.0.0.1'],
'extra' => ['ip' => '127.0.0.1'], ));
'message' => 'log',
]);
$this->assertEquals('['.date('Y-m-d').'] meh.ERROR: log [] {"ip":"127.0.0.1"}'."\n", $message); $this->assertEquals('['.date('Y-m-d').'] meh.ERROR: log [] {"ip":"127.0.0.1"}'."\n", $message);
} }
public function testFormatExtras() public function testFormatExtras()
{ {
$formatter = new LineFormatter("[%datetime%] %channel%.%level_name%: %message% %context% %extra.file% %extra%\n", 'Y-m-d'); $formatter = new LineFormatter("[%datetime%] %channel%.%level_name%: %message% %context% %extra.file% %extra%\n", 'Y-m-d');
$message = $formatter->format([ $message = $formatter->format($this->getRecord(
'level_name' => 'ERROR', Logger::ERROR,
'channel' => 'meh', 'log',
'context' => [], channel: 'meh',
'datetime' => new \DateTimeImmutable, extra: ['ip' => '127.0.0.1', 'file' => 'test'],
'extra' => ['ip' => '127.0.0.1', 'file' => 'test'], ));
'message' => 'log',
]);
$this->assertEquals('['.date('Y-m-d').'] meh.ERROR: log [] test {"ip":"127.0.0.1"}'."\n", $message); $this->assertEquals('['.date('Y-m-d').'] meh.ERROR: log [] test {"ip":"127.0.0.1"}'."\n", $message);
} }
public function testContextAndExtraOptionallyNotShownIfEmpty() public function testContextAndExtraOptionallyNotShownIfEmpty()
{ {
$formatter = new LineFormatter(null, 'Y-m-d', false, true); $formatter = new LineFormatter(null, 'Y-m-d', false, true);
$message = $formatter->format([ $message = $formatter->format($this->getRecord(
'level_name' => 'ERROR', Logger::ERROR,
'channel' => 'meh', 'log',
'context' => [], channel: 'meh',
'datetime' => new \DateTimeImmutable, ));
'extra' => [],
'message' => 'log',
]);
$this->assertEquals('['.date('Y-m-d').'] meh.ERROR: log '."\n", $message); $this->assertEquals('['.date('Y-m-d').'] meh.ERROR: log '."\n", $message);
} }
public function testContextAndExtraReplacement() public function testContextAndExtraReplacement()
{ {
$formatter = new LineFormatter('%context.foo% => %extra.foo%'); $formatter = new LineFormatter('%context.foo% => %extra.foo%');
$message = $formatter->format([ $message = $formatter->format($this->getRecord(
'level_name' => 'ERROR', Logger::ERROR,
'channel' => 'meh', 'log',
'context' => ['foo' => 'bar'], channel: 'meh',
'datetime' => new \DateTimeImmutable, context: ['foo' => 'bar'],
'extra' => ['foo' => 'xbar'], extra: ['foo' => 'xbar'],
'message' => 'log', ));
]);
$this->assertEquals('bar => xbar', $message); $this->assertEquals('bar => xbar', $message);
} }
public function testDefFormatWithObject() public function testDefFormatWithObject()
{ {
$formatter = new LineFormatter(null, 'Y-m-d'); $formatter = new LineFormatter(null, 'Y-m-d');
$message = $formatter->format([ $message = $formatter->format($this->getRecord(
'level_name' => 'ERROR', Logger::ERROR,
'channel' => 'meh', 'foobar',
'context' => [], channel: 'meh',
'datetime' => new \DateTimeImmutable, context: [],
'extra' => ['foo' => new TestFoo, 'bar' => new TestBar, 'baz' => [], 'res' => fopen('php://memory', 'rb')], extra: ['foo' => new TestFoo, 'bar' => new TestBar, 'baz' => [], 'res' => fopen('php://memory', 'rb')],
'message' => 'foobar', ));
]);
$this->assertEquals('['.date('Y-m-d').'] meh.ERROR: foobar [] {"foo":{"Monolog\\\\Formatter\\\\TestFoo":{"foo":"fooValue"}},"bar":{"Monolog\\\\Formatter\\\\TestBar":"bar"},"baz":[],"res":"[resource(stream)]"}'."\n", $message); $this->assertEquals('['.date('Y-m-d').'] meh.ERROR: foobar [] {"foo":{"Monolog\\\\Formatter\\\\TestFoo":{"foo":"fooValue"}},"bar":{"Monolog\\\\Formatter\\\\TestBar":"bar"},"baz":[],"res":"[resource(stream)]"}'."\n", $message);
} }
@@ -123,54 +113,48 @@ class LineFormatterTest extends \PHPUnit\Framework\TestCase
public function testDefFormatWithException() public function testDefFormatWithException()
{ {
$formatter = new LineFormatter(null, 'Y-m-d'); $formatter = new LineFormatter(null, 'Y-m-d');
$message = $formatter->format([ $message = $formatter->format($this->getRecord(
'level_name' => 'CRITICAL', Logger::CRITICAL,
'channel' => 'core', 'foobar',
'context' => ['exception' => new \RuntimeException('Foo')], channel: 'core',
'datetime' => new \DateTimeImmutable, context: ['exception' => new \RuntimeException('Foo')],
'extra' => [], ));
'message' => 'foobar',
]);
$path = str_replace('\\/', '/', json_encode(__FILE__)); $path = str_replace('\\/', '/', json_encode(__FILE__));
$this->assertEquals('['.date('Y-m-d').'] core.CRITICAL: foobar {"exception":"[object] (RuntimeException(code: 0): Foo at '.substr($path, 1, -1).':'.(__LINE__ - 8).')"} []'."\n", $message); $this->assertEquals('['.date('Y-m-d').'] core.CRITICAL: foobar {"exception":"[object] (RuntimeException(code: 0): Foo at '.substr($path, 1, -1).':'.(__LINE__ - 5).')"} []'."\n", $message);
} }
public function testDefFormatWithExceptionAndStacktrace() public function testDefFormatWithExceptionAndStacktrace()
{ {
$formatter = new LineFormatter(null, 'Y-m-d'); $formatter = new LineFormatter(null, 'Y-m-d');
$formatter->includeStacktraces(); $formatter->includeStacktraces();
$message = $formatter->format([ $message = $formatter->format($this->getRecord(
'level_name' => 'CRITICAL', Logger::CRITICAL,
'channel' => 'core', 'foobar',
'context' => ['exception' => new \RuntimeException('Foo')], channel: 'core',
'datetime' => new \DateTimeImmutable, context: ['exception' => new \RuntimeException('Foo')],
'extra' => [], ));
'message' => 'foobar',
]);
$path = str_replace('\\/', '/', json_encode(__FILE__)); $path = str_replace('\\/', '/', json_encode(__FILE__));
$this->assertMatchesRegularExpression('{^\['.date('Y-m-d').'] core\.CRITICAL: foobar \{"exception":"\[object] \(RuntimeException\(code: 0\): Foo at '.preg_quote(substr($path, 1, -1)).':'.(__LINE__ - 8).'\)\n\[stacktrace]\n#0}', $message); $this->assertMatchesRegularExpression('{^\['.date('Y-m-d').'] core\.CRITICAL: foobar \{"exception":"\[object] \(RuntimeException\(code: 0\): Foo at '.preg_quote(substr($path, 1, -1)).':'.(__LINE__ - 5).'\)\n\[stacktrace]\n#0}', $message);
} }
public function testDefFormatWithPreviousException() public function testDefFormatWithPreviousException()
{ {
$formatter = new LineFormatter(null, 'Y-m-d'); $formatter = new LineFormatter(null, 'Y-m-d');
$previous = new \LogicException('Wut?'); $previous = new \LogicException('Wut?');
$message = $formatter->format([ $message = $formatter->format($this->getRecord(
'level_name' => 'CRITICAL', Logger::CRITICAL,
'channel' => 'core', 'foobar',
'context' => ['exception' => new \RuntimeException('Foo', 0, $previous)], channel: 'core',
'datetime' => new \DateTimeImmutable, context: ['exception' => new \RuntimeException('Foo', 0, $previous)],
'extra' => [], ));
'message' => 'foobar',
]);
$path = str_replace('\\/', '/', json_encode(__FILE__)); $path = str_replace('\\/', '/', json_encode(__FILE__));
$this->assertEquals('['.date('Y-m-d').'] core.CRITICAL: foobar {"exception":"[object] (RuntimeException(code: 0): Foo at '.substr($path, 1, -1).':'.(__LINE__ - 8).')\n[previous exception] [object] (LogicException(code: 0): Wut? at '.substr($path, 1, -1).':'.(__LINE__ - 12).')"} []'."\n", $message); $this->assertEquals('['.date('Y-m-d').'] core.CRITICAL: foobar {"exception":"[object] (RuntimeException(code: 0): Foo at '.substr($path, 1, -1).':'.(__LINE__ - 5).')\n[previous exception] [object] (LogicException(code: 0): Wut? at '.substr($path, 1, -1).':'.(__LINE__ - 10).')"} []'."\n", $message);
} }
public function testDefFormatWithSoapFaultException() public function testDefFormatWithSoapFaultException()
@@ -180,53 +164,43 @@ class LineFormatterTest extends \PHPUnit\Framework\TestCase
} }
$formatter = new LineFormatter(null, 'Y-m-d'); $formatter = new LineFormatter(null, 'Y-m-d');
$message = $formatter->format([ $message = $formatter->format($this->getRecord(
'level_name' => 'CRITICAL', Logger::CRITICAL,
'channel' => 'core', 'foobar',
'context' => ['exception' => new \SoapFault('foo', 'bar', 'hello', 'world')], channel: 'core',
'datetime' => new \DateTimeImmutable, context: ['exception' => new \SoapFault('foo', 'bar', 'hello', 'world')],
'extra' => [], ));
'message' => 'foobar',
]);
$path = str_replace('\\/', '/', json_encode(__FILE__)); $path = str_replace('\\/', '/', json_encode(__FILE__));
$this->assertEquals('['.date('Y-m-d').'] core.CRITICAL: foobar {"exception":"[object] (SoapFault(code: 0 faultcode: foo faultactor: hello detail: world): bar at '.substr($path, 1, -1).':'.(__LINE__ - 8).')"} []'."\n", $message); $this->assertEquals('['.date('Y-m-d').'] core.CRITICAL: foobar {"exception":"[object] (SoapFault(code: 0 faultcode: foo faultactor: hello detail: world): bar at '.substr($path, 1, -1).':'.(__LINE__ - 5).')"} []'."\n", $message);
$message = $formatter->format([ $message = $formatter->format($this->getRecord(
'level_name' => 'CRITICAL', Logger::CRITICAL,
'channel' => 'core', 'foobar',
'context' => ['exception' => new \SoapFault('foo', 'bar', 'hello', (object) ['bar' => (object) ['biz' => 'baz'], 'foo' => 'world'])], channel: 'core',
'datetime' => new \DateTimeImmutable, context: ['exception' => new \SoapFault('foo', 'bar', 'hello', (object) ['bar' => (object) ['biz' => 'baz'], 'foo' => 'world'])],
'extra' => [], ));
'message' => 'foobar',
]);
$path = str_replace('\\/', '/', json_encode(__FILE__)); $path = str_replace('\\/', '/', json_encode(__FILE__));
$this->assertEquals('['.date('Y-m-d').'] core.CRITICAL: foobar {"exception":"[object] (SoapFault(code: 0 faultcode: foo faultactor: hello detail: {\"bar\":{\"biz\":\"baz\"},\"foo\":\"world\"}): bar at '.substr($path, 1, -1).':'.(__LINE__ - 8).')"} []'."\n", $message); $this->assertEquals('['.date('Y-m-d').'] core.CRITICAL: foobar {"exception":"[object] (SoapFault(code: 0 faultcode: foo faultactor: hello detail: {\"bar\":{\"biz\":\"baz\"},\"foo\":\"world\"}): bar at '.substr($path, 1, -1).':'.(__LINE__ - 5).')"} []'."\n", $message);
} }
public function testBatchFormat() public function testBatchFormat()
{ {
$formatter = new LineFormatter(null, 'Y-m-d'); $formatter = new LineFormatter(null, 'Y-m-d');
$message = $formatter->formatBatch([ $message = $formatter->formatBatch([
[ $this->getRecord(
'level_name' => 'CRITICAL', Logger::CRITICAL,
'channel' => 'test', 'bar',
'message' => 'bar', channel: 'test',
'context' => [], ),
'datetime' => new \DateTimeImmutable, $this->getRecord(
'extra' => [], Logger::WARNING,
], 'foo',
[ channel: 'log',
'level_name' => 'WARNING', ),
'channel' => 'log',
'message' => 'foo',
'context' => [],
'datetime' => new \DateTimeImmutable,
'extra' => [],
],
]); ]);
$this->assertEquals('['.date('Y-m-d').'] test.CRITICAL: bar [] []'."\n".'['.date('Y-m-d').'] log.WARNING: foo [] []'."\n", $message); $this->assertEquals('['.date('Y-m-d').'] test.CRITICAL: bar [] []'."\n".'['.date('Y-m-d').'] log.WARNING: foo [] []'."\n", $message);
} }
@@ -234,13 +208,7 @@ class LineFormatterTest extends \PHPUnit\Framework\TestCase
public function testFormatShouldStripInlineLineBreaks() public function testFormatShouldStripInlineLineBreaks()
{ {
$formatter = new LineFormatter(null, 'Y-m-d'); $formatter = new LineFormatter(null, 'Y-m-d');
$message = $formatter->format( $message = $formatter->format($this->getRecord(message: "foo\nbar"));
[
'message' => "foo\nbar",
'context' => [],
'extra' => [],
]
);
$this->assertMatchesRegularExpression('/foo bar/', $message); $this->assertMatchesRegularExpression('/foo bar/', $message);
} }
@@ -248,13 +216,7 @@ class LineFormatterTest extends \PHPUnit\Framework\TestCase
public function testFormatShouldNotStripInlineLineBreaksWhenFlagIsSet() public function testFormatShouldNotStripInlineLineBreaksWhenFlagIsSet()
{ {
$formatter = new LineFormatter(null, 'Y-m-d', true); $formatter = new LineFormatter(null, 'Y-m-d', true);
$message = $formatter->format( $message = $formatter->format($this->getRecord(message: "foo\nbar"));
[
'message' => "foo\nbar",
'context' => [],
'extra' => [],
]
);
$this->assertMatchesRegularExpression('/foo\nbar/', $message); $this->assertMatchesRegularExpression('/foo\nbar/', $message);
} }

View File

@@ -12,7 +12,7 @@
namespace Monolog\Formatter; namespace Monolog\Formatter;
use Monolog\Logger; use Monolog\Logger;
use PHPUnit\Framework\TestCase; use Monolog\Test\TestCase;
class LogstashFormatterTest extends TestCase class LogstashFormatterTest extends TestCase
{ {
@@ -22,15 +22,12 @@ class LogstashFormatterTest extends TestCase
public function testDefaultFormatterV1() public function testDefaultFormatterV1()
{ {
$formatter = new LogstashFormatter('test', 'hostname'); $formatter = new LogstashFormatter('test', 'hostname');
$record = [ $record = $this->getRecord(
'level' => Logger::ERROR, Logger::ERROR,
'level_name' => 'ERROR', 'log',
'channel' => 'meh', channel: 'meh',
'context' => [], datetime: new \DateTimeImmutable("@0"),
'datetime' => new \DateTimeImmutable("@0"), );
'extra' => [],
'message' => 'log',
];
$message = json_decode($formatter->format($record), true); $message = json_decode($formatter->format($record), true);
@@ -56,15 +53,14 @@ class LogstashFormatterTest extends TestCase
public function testFormatWithFileAndLineV1() public function testFormatWithFileAndLineV1()
{ {
$formatter = new LogstashFormatter('test'); $formatter = new LogstashFormatter('test');
$record = [ $record = $this->getRecord(
'level' => Logger::ERROR, Logger::ERROR,
'level_name' => 'ERROR', 'log',
'channel' => 'meh', channel: 'meh',
'context' => ['from' => 'logger'], context: ['from' => 'logger'],
'datetime' => new \DateTimeImmutable("@0"), datetime: new \DateTimeImmutable("@0"),
'extra' => ['file' => 'test', 'line' => 14], extra: ['file' => 'test', 'line' => 14],
'message' => 'log', );
];
$message = json_decode($formatter->format($record), true); $message = json_decode($formatter->format($record), true);
@@ -78,15 +74,14 @@ class LogstashFormatterTest extends TestCase
public function testFormatWithContextV1() public function testFormatWithContextV1()
{ {
$formatter = new LogstashFormatter('test'); $formatter = new LogstashFormatter('test');
$record = [ $record = $this->getRecord(
'level' => Logger::ERROR, Logger::ERROR,
'level_name' => 'ERROR', 'log',
'channel' => 'meh', channel: 'meh',
'context' => ['from' => 'logger'], context: ['from' => 'logger'],
'datetime' => new \DateTimeImmutable("@0"), datetime: new \DateTimeImmutable("@0"),
'extra' => ['key' => 'pair'], extra: ['key' => 'pair'],
'message' => 'log', );
];
$message = json_decode($formatter->format($record), true); $message = json_decode($formatter->format($record), true);
@@ -109,15 +104,14 @@ class LogstashFormatterTest extends TestCase
public function testFormatWithExtraV1() public function testFormatWithExtraV1()
{ {
$formatter = new LogstashFormatter('test'); $formatter = new LogstashFormatter('test');
$record = [ $record = $this->getRecord(
'level' => Logger::ERROR, Logger::ERROR,
'level_name' => 'ERROR', 'log',
'channel' => 'meh', channel: 'meh',
'context' => ['from' => 'logger'], context: ['from' => 'logger'],
'datetime' => new \DateTimeImmutable("@0"), datetime: new \DateTimeImmutable("@0"),
'extra' => ['key' => 'pair'], extra: ['key' => 'pair'],
'message' => 'log', );
];
$message = json_decode($formatter->format($record), true); $message = json_decode($formatter->format($record), true);
@@ -137,15 +131,14 @@ class LogstashFormatterTest extends TestCase
public function testFormatWithApplicationNameV1() public function testFormatWithApplicationNameV1()
{ {
$formatter = new LogstashFormatter('app', 'test'); $formatter = new LogstashFormatter('app', 'test');
$record = [ $record = $this->getRecord(
'level' => Logger::ERROR, Logger::ERROR,
'level_name' => 'ERROR', 'log',
'channel' => 'meh', channel: 'meh',
'context' => ['from' => 'logger'], context: ['from' => 'logger'],
'datetime' => new \DateTimeImmutable("@0"), datetime: new \DateTimeImmutable("@0"),
'extra' => ['key' => 'pair'], extra: ['key' => 'pair'],
'message' => 'log', );
];
$message = json_decode($formatter->format($record), true); $message = json_decode($formatter->format($record), true);
@@ -156,17 +149,15 @@ class LogstashFormatterTest extends TestCase
public function testFormatWithLatin9Data() public function testFormatWithLatin9Data()
{ {
$formatter = new LogstashFormatter('test', 'hostname'); $formatter = new LogstashFormatter('test', 'hostname');
$record = [ $record = $this->getRecord(
'level' => Logger::ERROR, Logger::ERROR,
'level_name' => 'ERROR', 'log',
'channel' => '¯\_(ツ)_/¯', channel: '¯\_(ツ)_/¯',
'context' => [], datetime: new \DateTimeImmutable("@0"),
'datetime' => new \DateTimeImmutable("@0"), extra: [
'extra' => [
'user_agent' => "\xD6WN; FBCR/OrangeEspa\xF1a; Vers\xE3o/4.0; F\xE4rist", 'user_agent' => "\xD6WN; FBCR/OrangeEspa\xF1a; Vers\xE3o/4.0; F\xE4rist",
], ],
'message' => 'log', );
];
$message = json_decode($formatter->format($record), true); $message = json_decode($formatter->format($record), true);

View File

@@ -15,11 +15,12 @@ use MongoDB\BSON\ObjectId;
use MongoDB\BSON\Regex; use MongoDB\BSON\Regex;
use MongoDB\BSON\UTCDateTime; use MongoDB\BSON\UTCDateTime;
use Monolog\Logger; use Monolog\Logger;
use Monolog\Test\TestCase;
/** /**
* @author Florian Plattner <me@florianplattner.de> * @author Florian Plattner <me@florianplattner.de>
*/ */
class MongoDBFormatterTest extends \PHPUnit\Framework\TestCase class MongoDBFormatterTest extends TestCase
{ {
public function setUp(): void public function setUp(): void
{ {
@@ -59,15 +60,12 @@ class MongoDBFormatterTest extends \PHPUnit\Framework\TestCase
public function testSimpleFormat() public function testSimpleFormat()
{ {
$record = [ $record = $this->getRecord(
'message' => 'some log message', message: 'some log message',
'context' => [], level: Logger::WARNING,
'level' => Logger::WARNING, channel: 'test',
'level_name' => Logger::getLevelName(Logger::WARNING), datetime: new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'),
'channel' => 'test', );
'datetime' => new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'),
'extra' => [],
];
$formatter = new MongoDBFormatter(); $formatter = new MongoDBFormatter();
$formattedRecord = $formatter->format($record); $formattedRecord = $formatter->format($record);
@@ -89,21 +87,19 @@ class MongoDBFormatterTest extends \PHPUnit\Framework\TestCase
$someObject->foo = 'something'; $someObject->foo = 'something';
$someObject->bar = 'stuff'; $someObject->bar = 'stuff';
$record = [ $record = $this->getRecord(
'message' => 'some log message', message: 'some log message',
'context' => [ context: [
'stuff' => new \DateTimeImmutable('1969-01-21T21:11:30.213000+00:00'), 'stuff' => new \DateTimeImmutable('1969-01-21T21:11:30.213000+00:00'),
'some_object' => $someObject, 'some_object' => $someObject,
'context_string' => 'some string', 'context_string' => 'some string',
'context_int' => 123456, 'context_int' => 123456,
'except' => new \Exception('exception message', 987), 'except' => new \Exception('exception message', 987),
], ],
'level' => Logger::WARNING, level: Logger::WARNING,
'level_name' => Logger::getLevelName(Logger::WARNING), channel: 'test',
'channel' => 'test', datetime: new \DateTimeImmutable('2016-01-21T21:11:30.213000+00:00'),
'datetime' => new \DateTimeImmutable('2016-01-21T21:11:30.213000+00:00'), );
'extra' => [],
];
$formatter = new MongoDBFormatter(); $formatter = new MongoDBFormatter();
$formattedRecord = $formatter->format($record); $formattedRecord = $formatter->format($record);
@@ -133,9 +129,9 @@ class MongoDBFormatterTest extends \PHPUnit\Framework\TestCase
public function testFormatDepthArray() public function testFormatDepthArray()
{ {
$record = [ $record = $this->getRecord(
'message' => 'some log message', message: 'some log message',
'context' => [ context: [
'nest2' => [ 'nest2' => [
'property' => 'anything', 'property' => 'anything',
'nest3' => [ 'nest3' => [
@@ -144,12 +140,10 @@ class MongoDBFormatterTest extends \PHPUnit\Framework\TestCase
], ],
], ],
], ],
'level' => Logger::WARNING, level: Logger::WARNING,
'level_name' => Logger::getLevelName(Logger::WARNING), channel: 'test',
'channel' => 'test', datetime: new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'),
'datetime' => new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'), );
'extra' => [],
];
$formatter = new MongoDBFormatter(2); $formatter = new MongoDBFormatter(2);
$formattedResult = $formatter->format($record); $formattedResult = $formatter->format($record);
@@ -167,9 +161,9 @@ class MongoDBFormatterTest extends \PHPUnit\Framework\TestCase
public function testFormatDepthArrayInfiniteNesting() public function testFormatDepthArrayInfiniteNesting()
{ {
$record = [ $record = $this->getRecord(
'message' => 'some log message', message: 'some log message',
'context' => [ context: [
'nest2' => [ 'nest2' => [
'property' => 'something', 'property' => 'something',
'nest3' => [ 'nest3' => [
@@ -180,12 +174,10 @@ class MongoDBFormatterTest extends \PHPUnit\Framework\TestCase
], ],
], ],
], ],
'level' => Logger::WARNING, level: Logger::WARNING,
'level_name' => Logger::getLevelName(Logger::WARNING), channel: 'test',
'channel' => 'test', datetime: new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'),
'datetime' => new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'), );
'extra' => [],
];
$formatter = new MongoDBFormatter(0); $formatter = new MongoDBFormatter(0);
$formattedResult = $formatter->format($record); $formattedResult = $formatter->format($record);
@@ -214,17 +206,15 @@ class MongoDBFormatterTest extends \PHPUnit\Framework\TestCase
$someObject->nest3->property = 'nothing'; $someObject->nest3->property = 'nothing';
$someObject->nest3->nest4 = 'invisible'; $someObject->nest3->nest4 = 'invisible';
$record = [ $record = $this->getRecord(
'message' => 'some log message', message: 'some log message',
'context' => [ context: [
'nest2' => $someObject, 'nest2' => $someObject,
], ],
'level' => Logger::WARNING, level: Logger::WARNING,
'level_name' => Logger::getLevelName(Logger::WARNING), channel: 'test',
'channel' => 'test', datetime: new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'),
'datetime' => new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'), );
'extra' => [],
];
$formatter = new MongoDBFormatter(2, true); $formatter = new MongoDBFormatter(2, true);
$formattedResult = $formatter->format($record); $formattedResult = $formatter->format($record);
@@ -243,17 +233,15 @@ class MongoDBFormatterTest extends \PHPUnit\Framework\TestCase
public function testFormatDepthException() public function testFormatDepthException()
{ {
$record = [ $record = $this->getRecord(
'message' => 'some log message', message: 'some log message',
'context' => [ context: [
'nest2' => new \Exception('exception message', 987), 'nest2' => new \Exception('exception message', 987),
], ],
'level' => Logger::WARNING, level: Logger::WARNING,
'level_name' => Logger::getLevelName(Logger::WARNING), channel: 'test',
'channel' => 'test', datetime: new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'),
'datetime' => new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'), );
'extra' => [],
];
$formatter = new MongoDBFormatter(2, false); $formatter = new MongoDBFormatter(2, false);
$formattedRecord = $formatter->format($record); $formattedRecord = $formatter->format($record);

View File

@@ -11,7 +11,8 @@
namespace Monolog\Formatter; namespace Monolog\Formatter;
use PHPUnit\Framework\TestCase; use Monolog\Test\TestCase;
use Monolog\Logger;
/** /**
* @covers Monolog\Formatter\NormalizerFormatter * @covers Monolog\Formatter\NormalizerFormatter
@@ -21,23 +22,23 @@ class NormalizerFormatterTest extends TestCase
public function testFormat() public function testFormat()
{ {
$formatter = new NormalizerFormatter('Y-m-d'); $formatter = new NormalizerFormatter('Y-m-d');
$formatted = $formatter->format([ $formatted = $formatter->format($this->getRecord(
'level_name' => 'ERROR', Logger::ERROR,
'channel' => 'meh', 'foo',
'message' => 'foo', channel: 'meh',
'datetime' => new \DateTimeImmutable, extra: ['foo' => new TestFooNorm, 'bar' => new TestBarNorm, 'baz' => [], 'res' => fopen('php://memory', 'rb')],
'extra' => ['foo' => new TestFooNorm, 'bar' => new TestBarNorm, 'baz' => [], 'res' => fopen('php://memory', 'rb')], context: [
'context' => [
'foo' => 'bar', 'foo' => 'bar',
'baz' => 'qux', 'baz' => 'qux',
'inf' => INF, 'inf' => INF,
'-inf' => -INF, '-inf' => -INF,
'nan' => acos(4), 'nan' => acos(4),
], ],
]); ));
$this->assertEquals([ $this->assertEquals([
'level_name' => 'ERROR', 'level_name' => 'ERROR',
'level' => Logger::ERROR,
'channel' => 'meh', 'channel' => 'meh',
'message' => 'foo', 'message' => 'foo',
'datetime' => date('Y-m-d'), 'datetime' => date('Y-m-d'),
@@ -62,7 +63,7 @@ class NormalizerFormatterTest extends TestCase
$formatter = new NormalizerFormatter('Y-m-d'); $formatter = new NormalizerFormatter('Y-m-d');
$e = new \LogicException('bar'); $e = new \LogicException('bar');
$e2 = new \RuntimeException('foo', 0, $e); $e2 = new \RuntimeException('foo', 0, $e);
$formatted = $formatter->format([ $formatted = $formatter->normalizeValue([
'exception' => $e2, 'exception' => $e2,
]); ]);
@@ -88,7 +89,7 @@ class NormalizerFormatterTest extends TestCase
$formatter = new NormalizerFormatter('Y-m-d'); $formatter = new NormalizerFormatter('Y-m-d');
$e = new \SoapFault('foo', 'bar', 'hello', 'world'); $e = new \SoapFault('foo', 'bar', 'hello', 'world');
$formatted = $formatter->format([ $formatted = $formatter->normalizeValue([
'exception' => $e, 'exception' => $e,
]); ]);
@@ -108,7 +109,7 @@ class NormalizerFormatterTest extends TestCase
$formatter = new NormalizerFormatter('Y-m-d'); $formatter = new NormalizerFormatter('Y-m-d');
$e = new \SoapFault('foo', 'bar', 'hello', (object) ['bar' => (object) ['biz' => 'baz'], 'foo' => 'world']); $e = new \SoapFault('foo', 'bar', 'hello', (object) ['bar' => (object) ['biz' => 'baz'], 'foo' => 'world']);
$formatted = $formatter->format([ $formatted = $formatter->normalizeValue([
'exception' => $e, 'exception' => $e,
]); ]);
@@ -132,35 +133,22 @@ class NormalizerFormatterTest extends TestCase
$formatter = new NormalizerFormatter('Y-m-d'); $formatter = new NormalizerFormatter('Y-m-d');
$this->expectException('RuntimeException'); $this->expectException('RuntimeException');
$this->expectExceptionMessage('Could not convert to string'); $this->expectExceptionMessage('Could not convert to string');
$formatter->format([ $formatter->format($this->getRecord(context: [
'myObject' => new TestToStringError(), 'myObject' => new TestToStringError(),
]); ]));
} }
public function testBatchFormat() public function testBatchFormat()
{ {
$formatter = new NormalizerFormatter('Y-m-d'); $formatter = new NormalizerFormatter('Y-m-d');
$formatted = $formatter->formatBatch([ $formatted = $formatter->formatBatch([
[ $this->getRecord(Logger::CRITICAL, 'bar', channel: 'test'),
'level_name' => 'CRITICAL', $this->getRecord(Logger::WARNING, 'foo', channel: 'log'),
'channel' => 'test',
'message' => 'bar',
'context' => [],
'datetime' => new \DateTimeImmutable,
'extra' => [],
],
[
'level_name' => 'WARNING',
'channel' => 'log',
'message' => 'foo',
'context' => [],
'datetime' => new \DateTimeImmutable,
'extra' => [],
],
]); ]);
$this->assertEquals([ $this->assertEquals([
[ [
'level_name' => 'CRITICAL', 'level_name' => 'CRITICAL',
'level' => Logger::CRITICAL,
'channel' => 'test', 'channel' => 'test',
'message' => 'bar', 'message' => 'bar',
'context' => [], 'context' => [],
@@ -169,6 +157,7 @@ class NormalizerFormatterTest extends TestCase
], ],
[ [
'level_name' => 'WARNING', 'level_name' => 'WARNING',
'level' => Logger::WARNING,
'channel' => 'log', 'channel' => 'log',
'message' => 'foo', 'message' => 'foo',
'context' => [], 'context' => [],
@@ -217,7 +206,7 @@ class NormalizerFormatterTest extends TestCase
$x = ['foo' => 'bar']; $x = ['foo' => 'bar'];
$y = ['x' => &$x]; $y = ['x' => &$x];
$x['y'] = &$y; $x['y'] = &$y;
$formatter->format($y); $formatter->normalizeValue($y);
} }
public function testToJsonIgnoresInvalidTypes() public function testToJsonIgnoresInvalidTypes()
@@ -251,13 +240,11 @@ class NormalizerFormatterTest extends TestCase
$formatter = new NormalizerFormatter(); $formatter = new NormalizerFormatter();
$largeArray = range(1, 1000); $largeArray = range(1, 1000);
$res = $formatter->format(array( $res = $formatter->format($this->getRecord(
'level_name' => 'CRITICAL', Logger::CRITICAL,
'channel' => 'test', 'bar',
'message' => 'bar', channel: 'test',
'context' => array($largeArray), context: [$largeArray],
'datetime' => new \DateTime,
'extra' => array(),
)); ));
$this->assertCount(1000, $res['context'][0]); $this->assertCount(1000, $res['context'][0]);
@@ -269,13 +256,11 @@ class NormalizerFormatterTest extends TestCase
$formatter = new NormalizerFormatter(); $formatter = new NormalizerFormatter();
$largeArray = range(1, 2000); $largeArray = range(1, 2000);
$res = $formatter->format(array( $res = $formatter->format($this->getRecord(
'level_name' => 'CRITICAL', Logger::CRITICAL,
'channel' => 'test', 'bar',
'message' => 'bar', channel: 'test',
'context' => array($largeArray), context: [$largeArray],
'datetime' => new \DateTime,
'extra' => array(),
)); ));
$this->assertCount(1001, $res['context'][0]); $this->assertCount(1001, $res['context'][0]);
@@ -328,12 +313,12 @@ class NormalizerFormatterTest extends TestCase
$message = $this->formatRecordWithExceptionInContext($formatter, $throwable); $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
$this->assertEquals( $this->assertEquals(
["..." => "Over 0 items (6 total), aborting normalization"], ["..." => "Over 0 items (7 total), aborting normalization"],
$message $message
); );
} }
public function testMaxNormalizeItemCountWith3ItemsMax() public function testMaxNormalizeItemCountWith2ItemsMax()
{ {
$formatter = new NormalizerFormatter(); $formatter = new NormalizerFormatter();
$formatter->setMaxNormalizeDepth(9); $formatter->setMaxNormalizeDepth(9);
@@ -342,8 +327,18 @@ class NormalizerFormatterTest extends TestCase
$message = $this->formatRecordWithExceptionInContext($formatter, $throwable); $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
unset($message['context']['exception']['trace']);
unset($message['context']['exception']['file']);
$this->assertEquals( $this->assertEquals(
["level_name" => "CRITICAL", "channel" => "core", "..." => "Over 2 items (6 total), aborting normalization"], [
"message" => "foobar",
"context" => ['exception' => [
'class' => 'Error',
'message' => 'Foo',
'code' => 0,
]],
"..." => "Over 2 items (7 total), aborting normalization"
],
$message $message
); );
} }
@@ -366,7 +361,7 @@ class NormalizerFormatterTest extends TestCase
} }
$formatter = new NormalizerFormatter(); $formatter = new NormalizerFormatter();
$record = ['context' => ['exception' => $e]]; $record = $this->getRecord(context: ['exception' => $e]);
$result = $formatter->format($record); $result = $formatter->format($record);
$this->assertSame( $this->assertSame(
@@ -383,14 +378,12 @@ class NormalizerFormatterTest extends TestCase
*/ */
private function formatRecordWithExceptionInContext(NormalizerFormatter $formatter, \Throwable $exception) private function formatRecordWithExceptionInContext(NormalizerFormatter $formatter, \Throwable $exception)
{ {
$message = $formatter->format([ $message = $formatter->format($this->getRecord(
'level_name' => 'CRITICAL', Logger::CRITICAL,
'channel' => 'core', 'foobar',
'context' => ['exception' => $exception], channel: 'core',
'datetime' => null, context: ['exception' => $exception],
'extra' => [], ));
'message' => 'foobar',
]);
return $message; return $message;
} }
@@ -404,7 +397,7 @@ class NormalizerFormatterTest extends TestCase
} }
$formatter = new NormalizerFormatter(); $formatter = new NormalizerFormatter();
$record = array('context' => array('exception' => $e)); $record = $this->getRecord(context: ['exception' => $e]);
$result = $formatter->format($record); $result = $formatter->format($record);
$this->assertSame( $this->assertSame(

View File

@@ -12,8 +12,9 @@
namespace Monolog\Formatter; namespace Monolog\Formatter;
use Monolog\DateTimeImmutable; use Monolog\DateTimeImmutable;
use Monolog\Test\TestCase;
class ScalarFormatterTest extends \PHPUnit\Framework\TestCase class ScalarFormatterTest extends TestCase
{ {
private $formatter; private $formatter;
@@ -43,7 +44,7 @@ class ScalarFormatterTest extends \PHPUnit\Framework\TestCase
public function testFormat() public function testFormat()
{ {
$exception = new \Exception('foo'); $exception = new \Exception('foo');
$formatted = $this->formatter->format([ $formatted = $this->formatter->format($this->getRecord(context: [
'foo' => 'string', 'foo' => 'string',
'bar' => 1, 'bar' => 1,
'baz' => false, 'baz' => false,
@@ -51,56 +52,50 @@ class ScalarFormatterTest extends \PHPUnit\Framework\TestCase
'bat' => ['foo' => 'bar'], 'bat' => ['foo' => 'bar'],
'bap' => $dt = new DateTimeImmutable(true), 'bap' => $dt = new DateTimeImmutable(true),
'ban' => $exception, 'ban' => $exception,
]); ]));
$this->assertSame([ $this->assertSame($this->encodeJson([
'foo' => 'string', 'foo' => 'string',
'bar' => 1, 'bar' => 1,
'baz' => false, 'baz' => false,
'bam' => $this->encodeJson([1, 2, 3]), 'bam' => [1, 2, 3],
'bat' => $this->encodeJson(['foo' => 'bar']), 'bat' => ['foo' => 'bar'],
'bap' => (string) $dt, 'bap' => (string) $dt,
'ban' => $this->encodeJson([ 'ban' => [
'class' => get_class($exception), 'class' => get_class($exception),
'message' => $exception->getMessage(), 'message' => $exception->getMessage(),
'code' => $exception->getCode(), 'code' => $exception->getCode(),
'file' => $exception->getFile() . ':' . $exception->getLine(), 'file' => $exception->getFile() . ':' . $exception->getLine(),
'trace' => $this->buildTrace($exception), 'trace' => $this->buildTrace($exception),
]), ],
], $formatted); ]), $formatted['context']);
} }
public function testFormatWithErrorContext() public function testFormatWithErrorContext()
{ {
$context = ['file' => 'foo', 'line' => 1]; $context = ['file' => 'foo', 'line' => 1];
$formatted = $this->formatter->format([ $formatted = $this->formatter->format($this->getRecord(
'context' => $context, context: $context,
]); ));
$this->assertSame([ $this->assertSame($this->encodeJson($context), $formatted['context']);
'context' => $this->encodeJson($context),
], $formatted);
} }
public function testFormatWithExceptionContext() public function testFormatWithExceptionContext()
{ {
$exception = new \Exception('foo'); $exception = new \Exception('foo');
$formatted = $this->formatter->format([ $formatted = $this->formatter->format($this->getRecord(context: [
'context' => [ 'exception' => $exception,
'exception' => $exception, ]));
],
]);
$this->assertSame([ $this->assertSame($this->encodeJson([
'context' => $this->encodeJson([ 'exception' => [
'exception' => [ 'class' => get_class($exception),
'class' => get_class($exception), 'message' => $exception->getMessage(),
'message' => $exception->getMessage(), 'code' => $exception->getCode(),
'code' => $exception->getCode(), 'file' => $exception->getFile() . ':' . $exception->getLine(),
'file' => $exception->getFile() . ':' . $exception->getLine(), 'trace' => $this->buildTrace($exception),
'trace' => $this->buildTrace($exception), ]
], ]), $formatted['context']);
]),
], $formatted);
} }
} }

View File

@@ -12,8 +12,9 @@
namespace Monolog\Formatter; namespace Monolog\Formatter;
use Monolog\Logger; use Monolog\Logger;
use Monolog\Test\TestCase;
class WildfireFormatterTest extends \PHPUnit\Framework\TestCase class WildfireFormatterTest extends TestCase
{ {
/** /**
* @covers Monolog\Formatter\WildfireFormatter::format * @covers Monolog\Formatter\WildfireFormatter::format
@@ -21,15 +22,13 @@ class WildfireFormatterTest extends \PHPUnit\Framework\TestCase
public function testDefaultFormat() public function testDefaultFormat()
{ {
$wildfire = new WildfireFormatter(); $wildfire = new WildfireFormatter();
$record = [ $record = $this->getRecord(
'level' => Logger::ERROR, Logger::ERROR,
'level_name' => 'ERROR', 'log',
'channel' => 'meh', channel: 'meh',
'context' => ['from' => 'logger'], context: ['from' => 'logger'],
'datetime' => new \DateTimeImmutable("@0"), extra: ['ip' => '127.0.0.1'],
'extra' => ['ip' => '127.0.0.1'], );
'message' => 'log',
];
$message = $wildfire->format($record); $message = $wildfire->format($record);
@@ -46,15 +45,13 @@ class WildfireFormatterTest extends \PHPUnit\Framework\TestCase
public function testFormatWithFileAndLine() public function testFormatWithFileAndLine()
{ {
$wildfire = new WildfireFormatter(); $wildfire = new WildfireFormatter();
$record = [ $record = $this->getRecord(
'level' => Logger::ERROR, Logger::ERROR,
'level_name' => 'ERROR', 'log',
'channel' => 'meh', channel: 'meh',
'context' => ['from' => 'logger'], context: ['from' => 'logger'],
'datetime' => new \DateTimeImmutable("@0"), extra: ['ip' => '127.0.0.1', 'file' => 'test', 'line' => 14],
'extra' => ['ip' => '127.0.0.1', 'file' => 'test', 'line' => 14], );
'message' => 'log',
];
$message = $wildfire->format($record); $message = $wildfire->format($record);
@@ -71,15 +68,11 @@ class WildfireFormatterTest extends \PHPUnit\Framework\TestCase
public function testFormatWithoutContext() public function testFormatWithoutContext()
{ {
$wildfire = new WildfireFormatter(); $wildfire = new WildfireFormatter();
$record = [ $record = $this->getRecord(
'level' => Logger::ERROR, Logger::ERROR,
'level_name' => 'ERROR', 'log',
'channel' => 'meh', channel: 'meh',
'context' => [], );
'datetime' => new \DateTimeImmutable("@0"),
'extra' => [],
'message' => 'log',
];
$message = $wildfire->format($record); $message = $wildfire->format($record);
@@ -97,15 +90,11 @@ class WildfireFormatterTest extends \PHPUnit\Framework\TestCase
$this->expectException(\BadMethodCallException::class); $this->expectException(\BadMethodCallException::class);
$wildfire = new WildfireFormatter(); $wildfire = new WildfireFormatter();
$record = [ $record = $this->getRecord(
'level' => Logger::ERROR, Logger::ERROR,
'level_name' => 'ERROR', 'log',
'channel' => 'meh', channel: 'meh',
'context' => [], );
'datetime' => new \DateTimeImmutable("@0"),
'extra' => [],
'message' => 'log',
];
$wildfire->formatBatch([$record]); $wildfire->formatBatch([$record]);
} }
@@ -116,11 +105,11 @@ class WildfireFormatterTest extends \PHPUnit\Framework\TestCase
public function testTableFormat() public function testTableFormat()
{ {
$wildfire = new WildfireFormatter(); $wildfire = new WildfireFormatter();
$record = [ $record = $this->getRecord(
'level' => Logger::ERROR, Logger::ERROR,
'level_name' => 'ERROR', 'table-message',
'channel' => 'table-channel', channel: 'table-channel',
'context' => [ context: [
'table' => [ 'table' => [
['col1', 'col2', 'col3'], ['col1', 'col2', 'col3'],
['val1', 'val2', 'val3'], ['val1', 'val2', 'val3'],
@@ -128,10 +117,7 @@ class WildfireFormatterTest extends \PHPUnit\Framework\TestCase
['bar1', 'bar2', 'bar3'], ['bar1', 'bar2', 'bar3'],
], ],
], ],
'datetime' => new \DateTimeImmutable("@0"), );
'extra' => [],
'message' => 'table-message',
];
$message = $wildfire->format($record); $message = $wildfire->format($record);

View File

@@ -87,11 +87,9 @@ class DeduplicationHandlerTest extends TestCase
$test = new TestHandler(); $test = new TestHandler();
$handler = new DeduplicationHandler($test, sys_get_temp_dir().'/monolog_dedup.log', 0); $handler = new DeduplicationHandler($test, sys_get_temp_dir().'/monolog_dedup.log', 0);
$record = $this->getRecord(Logger::ERROR); $record = $this->getRecord(Logger::ERROR, datetime: new \DateTimeImmutable('+62seconds'));
$record['datetime'] = $record['datetime']->modify('+62seconds');
$handler->handle($record); $handler->handle($record);
$record = $this->getRecord(Logger::CRITICAL); $record = $this->getRecord(Logger::CRITICAL, datetime: new \DateTimeImmutable('+62seconds'));
$record['datetime'] = $record['datetime']->modify('+62seconds');
$handler->handle($record); $handler->handle($record);
$handler->flush(); $handler->flush();
@@ -114,14 +112,11 @@ class DeduplicationHandlerTest extends TestCase
$handler = new DeduplicationHandler($test, sys_get_temp_dir().'/monolog_dedup.log', 0); $handler = new DeduplicationHandler($test, sys_get_temp_dir().'/monolog_dedup.log', 0);
// handle two records from yesterday, and one recent // handle two records from yesterday, and one recent
$record = $this->getRecord(Logger::ERROR); $record = $this->getRecord(Logger::ERROR, datetime: new \DateTimeImmutable('-1day -10seconds'));
$record['datetime'] = $record['datetime']->modify('-1day -10seconds');
$handler->handle($record); $handler->handle($record);
$record2 = $this->getRecord(Logger::CRITICAL); $record2 = $this->getRecord(Logger::CRITICAL, datetime: new \DateTimeImmutable('-1day -10seconds'));
$record2['datetime'] = $record2['datetime']->modify('-1day -10seconds');
$handler->handle($record2); $handler->handle($record2);
$record3 = $this->getRecord(Logger::CRITICAL); $record3 = $this->getRecord(Logger::CRITICAL, datetime: new \DateTimeImmutable('-30seconds'));
$record3['datetime'] = $record3['datetime']->modify('-30seconds');
$handler->handle($record3); $handler->handle($record3);
// log is written as none of them are duplicate // log is written as none of them are duplicate

View File

@@ -58,15 +58,7 @@ class ElasticaHandlerTest extends TestCase
public function testHandle() public function testHandle()
{ {
// log message // log message
$msg = new LogRecord( $msg = $this->getRecord(Logger::ERROR, 'log', context: ['foo' => 7, 'bar', 'class' => new \stdClass], datetime: new \DateTimeImmutable("@0"));
level: Logger::ERROR,
levelName: 'ERROR',
channel: 'meh',
context: ['foo' => 7, 'bar', 'class' => new \stdClass],
datetime: new \DateTimeImmutable("@0"),
extra: [],
message: 'log',
);
// format expected result // format expected result
$formatter = new ElasticaFormatter($this->options['index'], $this->options['type']); $formatter = new ElasticaFormatter($this->options['index'], $this->options['type']);
@@ -166,17 +158,9 @@ class ElasticaHandlerTest extends TestCase
*/ */
public function testHandleIntegration() public function testHandleIntegration()
{ {
$msg = new LogRecord( $msg = $this->getRecord(Logger::ERROR, 'log', context: ['foo' => 7, 'bar', 'class' => new \stdClass], datetime: new \DateTimeImmutable("@0"));
level: Logger::ERROR,
levelName: 'ERROR',
channel: 'meh',
context: ['foo' => 7, 'bar', 'class' => new \stdClass],
datetime: new \DateTimeImmutable("@0"),
extra: [],
message: 'log',
);
$expected = (array) $msg; $expected = $msg->toArray();
$expected['datetime'] = $msg['datetime']->format(\DateTime::ISO8601); $expected['datetime'] = $msg['datetime']->format(\DateTime::ISO8601);
$expected['context'] = [ $expected['context'] = [
'class' => '[object] (stdClass: {})', 'class' => '[object] (stdClass: {})',
@@ -220,15 +204,7 @@ class ElasticaHandlerTest extends TestCase
*/ */
public function testHandleIntegrationNewESVersion() public function testHandleIntegrationNewESVersion()
{ {
$msg = new LogRecord( $msg = $this->getRecord(Logger::ERROR, 'log', context: ['foo' => 7, 'bar', 'class' => new \stdClass], datetime: new \DateTimeImmutable("@0"));
level: Logger::ERROR,
levelName: 'ERROR',
channel: 'meh',
context: ['foo' => 7, 'bar', 'class' => new \stdClass],
datetime: new \DateTimeImmutable("@0"),
extra: [],
message: 'log',
);
$expected = (array) $msg; $expected = (array) $msg;
$expected['datetime'] = $msg['datetime']->format(\DateTime::ISO8601); $expected['datetime'] = $msg['datetime']->format(\DateTime::ISO8601);

View File

@@ -56,15 +56,7 @@ class ElasticsearchHandlerTest extends TestCase
public function testHandle() public function testHandle()
{ {
// log message // log message
$msg = [ $msg = $this->getRecord(Logger::ERROR, 'log', context: ['foo' => 7, 'bar', 'class' => new \stdClass], datetime: new \DateTimeImmutable("@0"));
'level' => Logger::ERROR,
'level_name' => 'ERROR',
'channel' => 'meh',
'context' => ['foo' => 7, 'bar', 'class' => new \stdClass],
'datetime' => new \DateTimeImmutable("@0"),
'extra' => [],
'message' => 'log',
];
// format expected result // format expected result
$formatter = new ElasticsearchFormatter($this->options['index'], $this->options['type']); $formatter = new ElasticsearchFormatter($this->options['index'], $this->options['type']);
@@ -180,17 +172,9 @@ class ElasticsearchHandlerTest extends TestCase
*/ */
public function testHandleIntegration() public function testHandleIntegration()
{ {
$msg = [ $msg = $this->getRecord(Logger::ERROR, 'log', context: ['foo' => 7, 'bar', 'class' => new \stdClass], datetime: new \DateTimeImmutable("@0"));
'level' => Logger::ERROR,
'level_name' => 'ERROR',
'channel' => 'meh',
'context' => ['foo' => 7, 'bar', 'class' => new \stdClass],
'datetime' => new \DateTimeImmutable("@0"),
'extra' => [],
'message' => 'log',
];
$expected = $msg; $expected = $msg->toArray();
$expected['datetime'] = $msg['datetime']->format(\DateTime::ISO8601); $expected['datetime'] = $msg['datetime']->format(\DateTime::ISO8601);
$expected['context'] = [ $expected['context'] = [
'class' => ["stdClass" => []], 'class' => ["stdClass" => []],

View File

@@ -209,8 +209,7 @@ class FingersCrossedHandlerTest extends TestCase
$handler = new FingersCrossedHandler($test, new ChannelLevelActivationStrategy(Logger::ERROR, ['othertest' => Logger::DEBUG])); $handler = new FingersCrossedHandler($test, new ChannelLevelActivationStrategy(Logger::ERROR, ['othertest' => Logger::DEBUG]));
$handler->handle($this->getRecord(Logger::WARNING)); $handler->handle($this->getRecord(Logger::WARNING));
$this->assertFalse($test->hasWarningRecords()); $this->assertFalse($test->hasWarningRecords());
$record = $this->getRecord(Logger::DEBUG); $record = $this->getRecord(Logger::DEBUG, channel: 'othertest');
$record['channel'] = 'othertest';
$handler->handle($record); $handler->handle($record);
$this->assertTrue($test->hasDebugRecords()); $this->assertTrue($test->hasDebugRecords());
$this->assertTrue($test->hasWarningRecords()); $this->assertTrue($test->hasWarningRecords());
@@ -226,8 +225,7 @@ class FingersCrossedHandlerTest extends TestCase
$handler = new FingersCrossedHandler($test, new ChannelLevelActivationStrategy('error', ['othertest' => 'debug'])); $handler = new FingersCrossedHandler($test, new ChannelLevelActivationStrategy('error', ['othertest' => 'debug']));
$handler->handle($this->getRecord(Logger::WARNING)); $handler->handle($this->getRecord(Logger::WARNING));
$this->assertFalse($test->hasWarningRecords()); $this->assertFalse($test->hasWarningRecords());
$record = $this->getRecord(Logger::DEBUG); $record = $this->getRecord(Logger::DEBUG, channel: 'othertest');
$record['channel'] = 'othertest';
$handler->handle($record); $handler->handle($record);
$this->assertTrue($test->hasDebugRecords()); $this->assertTrue($test->hasDebugRecords());
$this->assertTrue($test->hasWarningRecords()); $this->assertTrue($test->hasWarningRecords());
@@ -242,7 +240,7 @@ class FingersCrossedHandlerTest extends TestCase
$test = new TestHandler(); $test = new TestHandler();
$handler = new FingersCrossedHandler($test, Logger::INFO); $handler = new FingersCrossedHandler($test, Logger::INFO);
$handler->pushProcessor(function ($record) { $handler->pushProcessor(function ($record) {
$record['extra']['foo'] = true; $record->extra['foo'] = true;
return $record; return $record;
}); });

View File

@@ -56,15 +56,7 @@ class FleepHookHandlerTest extends TestCase
*/ */
public function testHandlerUsesLineFormatterWhichIgnoresEmptyArrays() public function testHandlerUsesLineFormatterWhichIgnoresEmptyArrays()
{ {
$record = [ $record = $this->getRecord(Logger::DEBUG, 'msg');
'message' => 'msg',
'context' => [],
'level' => Logger::DEBUG,
'level_name' => Logger::getLevelName(Logger::DEBUG),
'channel' => 'channel',
'datetime' => new \DateTimeImmutable(),
'extra' => [],
];
$expectedFormatter = new LineFormatter(null, null, true, true); $expectedFormatter = new LineFormatter(null, null, true, true);
$expected = $expectedFormatter->format($record); $expected = $expectedFormatter->format($record);

View File

@@ -93,9 +93,12 @@ class GelfHandlerTest extends TestCase
public function testInjectedGelfMessageFormatter() public function testInjectedGelfMessageFormatter()
{ {
$record = $this->getRecord(Logger::WARNING, "A test warning message"); $record = $this->getRecord(
$record['extra']['blarg'] = 'yep'; Logger::WARNING,
$record['context']['from'] = 'logger'; "A test warning message",
extra: ['blarg' => 'yep'],
context: ['from' => 'logger'],
);
$expectedMessage = new Message(); $expectedMessage = new Message();
$expectedMessage $expectedMessage

View File

@@ -43,7 +43,7 @@ class MongoDBHandlerTest extends TestCase
->will($this->returnValue($collection)); ->will($this->returnValue($collection));
$record = $this->getRecord(); $record = $this->getRecord();
$expected = $record; $expected = $record->toArray();
$expected['datetime'] = new \MongoDB\BSON\UTCDateTime((int) floor(((float) $record['datetime']->format('U.u')) * 1000)); $expected['datetime'] = new \MongoDB\BSON\UTCDateTime((int) floor(((float) $record['datetime']->format('U.u')) * 1000));
$collection->expects($this->once()) $collection->expects($this->once())

View File

@@ -46,7 +46,7 @@ class PsrHandlerTest extends TestCase
->with(strtolower($levelName), $message, $context); ->with(strtolower($levelName), $message, $context);
$handler = new PsrHandler($psrLogger); $handler = new PsrHandler($psrLogger);
$handler->handle(['level' => $level, 'level_name' => $levelName, 'message' => $message, 'context' => $context]); $handler->handle($this->getRecord($level, $message, context: $context));
} }
public function testFormatter() public function testFormatter()
@@ -63,6 +63,6 @@ class PsrHandlerTest extends TestCase
$handler = new PsrHandler($psrLogger); $handler = new PsrHandler($psrLogger);
$handler->setFormatter(new LineFormatter('dummy')); $handler->setFormatter(new LineFormatter('dummy'));
$handler->handle(['level' => $level, 'level_name' => $levelName, 'message' => $message, 'context' => $context, 'extra' => [], 'date' => new \DateTimeImmutable()]); $handler->handle($this->getRecord($level, $message, context: $context, datetime: new \DateTimeImmutable()));
} }
} }

View File

@@ -38,12 +38,12 @@ class SyslogUdpHandlerTest extends TestCase
->onlyMethods(['write']) ->onlyMethods(['write'])
->setConstructorArgs(['lol']) ->setConstructorArgs(['lol'])
->getMock(); ->getMock();
$socket->expects($this->at(0)) $socket->expects($this->atLeast(2))
->method('write') ->method('write')
->with("lol", "<".(LOG_AUTHPRIV + LOG_WARNING).">1 $time $host php $pid - - "); ->withConsecutive(
$socket->expects($this->at(1)) [$this->equalTo("lol"), $this->equalTo("<".(LOG_AUTHPRIV + LOG_WARNING).">1 $time $host php $pid - - ")],
->method('write') [$this->equalTo("hej"), $this->equalTo("<".(LOG_AUTHPRIV + LOG_WARNING).">1 $time $host php $pid - - ")],
->with("hej", "<".(LOG_AUTHPRIV + LOG_WARNING).">1 $time $host php $pid - - "); );
$handler->setSocket($socket); $handler->setSocket($socket);
@@ -64,7 +64,7 @@ class SyslogUdpHandlerTest extends TestCase
$handler->setSocket($socket); $handler->setSocket($socket);
$handler->handle($this->getRecordWithMessage(null)); $handler->handle($this->getRecordWithMessage(''));
} }
public function testRfc() public function testRfc()
@@ -84,12 +84,12 @@ class SyslogUdpHandlerTest extends TestCase
->setConstructorArgs(array('lol', 999)) ->setConstructorArgs(array('lol', 999))
->onlyMethods(array('write')) ->onlyMethods(array('write'))
->getMock(); ->getMock();
$socket->expects($this->at(0)) $socket->expects($this->atLeast(2))
->method('write') ->method('write')
->with("lol", "<".(LOG_AUTHPRIV + LOG_WARNING).">$time $host php[$pid]: "); ->withConsecutive(
$socket->expects($this->at(1)) [$this->equalTo("lol"), $this->equalTo("<".(LOG_AUTHPRIV + LOG_WARNING).">$time $host php[$pid]: ")],
->method('write') [$this->equalTo("hej"), $this->equalTo("<".(LOG_AUTHPRIV + LOG_WARNING).">$time $host php[$pid]: ")],
->with("hej", "<".(LOG_AUTHPRIV + LOG_WARNING).">$time $host php[$pid]: "); );
$handler->setSocket($socket); $handler->setSocket($socket);
@@ -98,6 +98,6 @@ class SyslogUdpHandlerTest extends TestCase
protected function getRecordWithMessage($msg) protected function getRecordWithMessage($msg)
{ {
return ['message' => $msg, 'level' => \Monolog\Logger::WARNING, 'context' => null, 'extra' => [], 'channel' => 'lol', 'datetime' => new \DateTimeImmutable('2014-01-07 12:34:56')]; return $this->getRecord(message: $msg, level: \Monolog\Logger::WARNING, channel: 'lol', datetime: new \DateTimeImmutable('2014-01-07 12:34:56'));
} }
} }

View File

@@ -27,8 +27,8 @@ class TestHandlerTest extends TestCase
$handler = new TestHandler; $handler = new TestHandler;
$record = $this->getRecord($level, 'test'.$method); $record = $this->getRecord($level, 'test'.$method);
$this->assertFalse($handler->hasRecords($level)); $this->assertFalse($handler->hasRecords($level));
$this->assertFalse($handler->hasRecord($record, $level)); $this->assertFalse($handler->hasRecord($record->message, $level));
$this->assertFalse($handler->{'has'.$method}($record), 'has'.$method); $this->assertFalse($handler->{'has'.$method}($record->message), 'has'.$method);
$this->assertFalse($handler->{'has'.$method.'ThatContains'}('test'), 'has'.$method.'ThatContains'); $this->assertFalse($handler->{'has'.$method.'ThatContains'}('test'), 'has'.$method.'ThatContains');
$this->assertFalse($handler->{'has'.$method.'ThatPasses'}(function ($rec) { $this->assertFalse($handler->{'has'.$method.'ThatPasses'}(function ($rec) {
return true; return true;
@@ -39,8 +39,8 @@ class TestHandlerTest extends TestCase
$this->assertFalse($handler->{'has'.$method}('bar'), 'has'.$method); $this->assertFalse($handler->{'has'.$method}('bar'), 'has'.$method);
$this->assertTrue($handler->hasRecords($level)); $this->assertTrue($handler->hasRecords($level));
$this->assertTrue($handler->hasRecord($record, $level)); $this->assertTrue($handler->hasRecord($record->message, $level));
$this->assertTrue($handler->{'has'.$method}($record), 'has'.$method); $this->assertTrue($handler->{'has'.$method}($record->message), 'has'.$method);
$this->assertTrue($handler->{'has'.$method}('test'.$method), 'has'.$method); $this->assertTrue($handler->{'has'.$method}('test'.$method), 'has'.$method);
$this->assertTrue($handler->{'has'.$method.'ThatContains'}('test'), 'has'.$method.'ThatContains'); $this->assertTrue($handler->{'has'.$method.'ThatContains'}('test'), 'has'.$method.'ThatContains');
$this->assertTrue($handler->{'has'.$method.'ThatPasses'}(function ($rec) { $this->assertTrue($handler->{'has'.$method.'ThatPasses'}(function ($rec) {
@@ -50,7 +50,7 @@ class TestHandlerTest extends TestCase
$this->assertTrue($handler->{'has'.$method.'Records'}(), 'has'.$method.'Records'); $this->assertTrue($handler->{'has'.$method.'Records'}(), 'has'.$method.'Records');
$records = $handler->getRecords(); $records = $handler->getRecords();
unset($records[0]['formatted']); $records[0]->formatted = null;
$this->assertEquals([$record], $records); $this->assertEquals([$record], $records);
} }

View File

@@ -13,8 +13,9 @@ namespace Monolog;
use Monolog\Processor\WebProcessor; use Monolog\Processor\WebProcessor;
use Monolog\Handler\TestHandler; use Monolog\Handler\TestHandler;
use Monolog\Test\TestCase;
class LoggerTest extends \PHPUnit\Framework\TestCase class LoggerTest extends TestCase
{ {
/** /**
* @covers Monolog\Logger::getName * @covers Monolog\Logger::getName
@@ -91,11 +92,11 @@ class LoggerTest extends \PHPUnit\Framework\TestCase
{ {
$logger = new Logger(__METHOD__); $logger = new Logger(__METHOD__);
$handler = $this->prophesize('Monolog\Handler\NullHandler'); $handler = $this->getMockBuilder('Monolog\Handler\HandlerInterface')->getMock();
$handler->handle(\Prophecy\Argument::any())->shouldBeCalled(); $handler->expects($this->never())->method('isHandling');
$handler->isHandling(['level' => 300])->willReturn(true); $handler->expects($this->once())->method('handle');
$logger->pushHandler($handler->reveal()); $logger->pushHandler($handler);
$this->assertTrue($logger->addRecord(Logger::WARNING, 'test')); $this->assertTrue($logger->addRecord(Logger::WARNING, 'test'));
} }
@@ -103,15 +104,32 @@ class LoggerTest extends \PHPUnit\Framework\TestCase
/** /**
* @covers Monolog\Logger::addRecord * @covers Monolog\Logger::addRecord
*/ */
public function testLogNotHandled() public function testLogAlwaysHandledIfNoProcessorsArePresent()
{ {
$logger = new Logger(__METHOD__); $logger = new Logger(__METHOD__);
$handler = $this->prophesize('Monolog\Handler\NullHandler'); $handler = $this->getMockBuilder('Monolog\Handler\HandlerInterface')->getMock();
$handler->handle()->shouldNotBeCalled(); $handler->expects($this->never())->method('isHandling');
$handler->isHandling(['level' => 300])->willReturn(false); $handler->expects($this->once())->method('handle');
$logger->pushHandler($handler->reveal()); $logger->pushHandler($handler);
$this->assertTrue($logger->addRecord(Logger::WARNING, 'test'));
}
/**
* @covers Monolog\Logger::addRecord
*/
public function testLogNotHandledIfProcessorsArePresent()
{
$logger = new Logger(__METHOD__);
$handler = $this->getMockBuilder('Monolog\Handler\HandlerInterface')->getMock();
$handler->expects($this->once())->method('isHandling')->will($this->returnValue(false));
$handler->expects($this->never())->method('handle');
$logger->pushProcessor(fn (LogRecord $record) => $record);
$logger->pushHandler($handler);
$this->assertFalse($logger->addRecord(Logger::WARNING, 'test')); $this->assertFalse($logger->addRecord(Logger::WARNING, 'test'));
} }
@@ -273,9 +291,10 @@ class LoggerTest extends \PHPUnit\Framework\TestCase
/** /**
* @covers Monolog\Logger::addRecord * @covers Monolog\Logger::addRecord
*/ */
public function testHandlersNotCalledBeforeFirstHandling() public function testHandlersNotCalledBeforeFirstHandlingWhenProcessorsPresent()
{ {
$logger = new Logger(__METHOD__); $logger = new Logger(__METHOD__);
$logger->pushProcessor(fn($record) => $record);
$handler1 = $this->createMock('Monolog\Handler\HandlerInterface'); $handler1 = $this->createMock('Monolog\Handler\HandlerInterface');
$handler1->expects($this->never()) $handler1->expects($this->never())
@@ -315,7 +334,7 @@ class LoggerTest extends \PHPUnit\Framework\TestCase
/** /**
* @covers Monolog\Logger::addRecord * @covers Monolog\Logger::addRecord
*/ */
public function testHandlersNotCalledBeforeFirstHandlingWithAssocArray() public function testHandlersNotCalledBeforeFirstHandlingWhenProcessorsPresentWithAssocArray()
{ {
$handler1 = $this->createMock('Monolog\Handler\HandlerInterface'); $handler1 = $this->createMock('Monolog\Handler\HandlerInterface');
$handler1->expects($this->never()) $handler1->expects($this->never())
@@ -347,6 +366,7 @@ class LoggerTest extends \PHPUnit\Framework\TestCase
; ;
$logger = new Logger(__METHOD__, ['last' => $handler3, 'second' => $handler2, 'first' => $handler1]); $logger = new Logger(__METHOD__, ['last' => $handler3, 'second' => $handler2, 'first' => $handler1]);
$logger->pushProcessor(fn($record) => $record);
$logger->debug('test'); $logger->debug('test');
} }
@@ -627,7 +647,7 @@ class LoggerTest extends \PHPUnit\Framework\TestCase
$that = $this; $that = $this;
$logger->setExceptionHandler(function ($e, $record) use ($that) { $logger->setExceptionHandler(function ($e, $record) use ($that) {
$that->assertEquals($e->getMessage(), 'Some handler exception'); $that->assertEquals($e->getMessage(), 'Some handler exception');
$that->assertTrue(is_array($record)); $that->assertInstanceOf(LogRecord::class, $record);
$that->assertEquals($record['message'], 'test'); $that->assertEquals($record['message'], 'test');
}); });
$handler = $this->getMockBuilder('Monolog\Handler\HandlerInterface')->getMock(); $handler = $this->getMockBuilder('Monolog\Handler\HandlerInterface')->getMock();

View File

@@ -66,10 +66,7 @@ class IntrospectionProcessorTest extends TestCase
public function testLevelTooLow() public function testLevelTooLow()
{ {
$input = [ $input = $this->getRecord(Logger::DEBUG);
'level' => Logger::DEBUG,
'extra' => [],
];
$expected = $input; $expected = $input;
@@ -81,10 +78,7 @@ class IntrospectionProcessorTest extends TestCase
public function testLevelEqual() public function testLevelEqual()
{ {
$input = [ $input = $this->getRecord(Logger::CRITICAL);
'level' => Logger::CRITICAL,
'extra' => [],
];
$expected = $input; $expected = $input;
$expected['extra'] = [ $expected['extra'] = [
@@ -103,10 +97,7 @@ class IntrospectionProcessorTest extends TestCase
public function testLevelHigher() public function testLevelHigher()
{ {
$input = [ $input = $this->getRecord(Logger::EMERGENCY);
'level' => Logger::EMERGENCY,
'extra' => [],
];
$expected = $input; $expected = $input;
$expected['extra'] = [ $expected['extra'] = [