diff --git a/.gitignore b/.gitignore index a3ec4bab3..9418cccf3 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,6 @@ composer.phar phpunit.xml composer.lock .DS_Store -.php_cs.cache +.php-cs-fixer.cache .hg .phpunit.result.cache diff --git a/.php_cs b/.php-cs-fixer.php similarity index 85% rename from .php_cs rename to .php-cs-fixer.php index 6fc3ca2ea..2638adc7a 100644 --- a/.php_cs +++ b/.php-cs-fixer.php @@ -17,10 +17,8 @@ ->in(__DIR__.'/tests') ; -return PhpCsFixer\Config::create() - ->setUsingCache(true) - ->setRiskyAllowed(true) - ->setRules(array( +$config = new PhpCsFixer\Config(); +return $config->setRules(array( '@PSR2' => true, // some rules disabled as long as 1.x branch is maintained 'binary_operator_spaces' => array( @@ -30,11 +28,11 @@ 'cast_spaces' => ['space' => 'single'], 'header_comment' => ['header' => $header], 'include' => true, - 'class_attributes_separation' => ['elements' => ['method']], + 'class_attributes_separation' => array('elements' => array('method' => 'one', 'trait_import' => 'none')), 'no_blank_lines_after_class_opening' => true, 'no_blank_lines_after_phpdoc' => true, 'no_empty_statement' => true, - 'no_extra_consecutive_blank_lines' => true, + 'no_extra_blank_lines' => true, 'no_leading_import_slash' => true, 'no_leading_namespace_whitespace' => true, 'no_trailing_comma_in_singleline_array' => true, @@ -49,13 +47,15 @@ //'phpdoc_scalar' => true, 'phpdoc_trim' => true, //'phpdoc_types' => true, - 'psr0' => true, + 'psr_autoloading' => ['dir' => 'src'], //'array_syntax' => array('syntax' => 'short'), 'declare_strict_types' => true, 'single_blank_line_before_namespace' => true, 'standardize_not_equals' => true, 'ternary_operator_spaces' => true, - 'trailing_comma_in_multiline_array' => true, + 'trailing_comma_in_multiline' => true, )) + ->setUsingCache(true) + ->setRiskyAllowed(true) ->setFinder($finder) ; diff --git a/README.md b/README.md index bfcae0c00..8a431d7e3 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ use Monolog\Handler\StreamHandler; // create a log channel $log = new Logger('name'); -$log->pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING)); +$log->pushHandler(new StreamHandler('path/to/your.log', Level::Warning)); // add records to the log $log->warning('Foo'); @@ -50,7 +50,7 @@ $log->error('Bar'); ## Support Monolog Financially -Get supported Monolog and help fund the project with the [Tidelift Subscription](https://tidelift.com/subscription/pkg/packagist-monolog-monolog?utm_source=packagist-monolog-monolog&utm_medium=referral&utm_campaign=enterprise) or via [GitHub sponsorship](https://github.com/sponsors/Seldaek). +Get supported Monolog and help fund the project with the [Tidelift Subscription](https://tidelift.com/subscription/pkg/packagist-monolog-monolog?utm_source=packagist-monolog-monolog&utm_medium=referral&utm_campaign=enterprise) or via [GitHub sponsorship](https://github.com/sponsors/Seldaek). Tidelift delivers commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. diff --git a/doc/01-usage.md b/doc/01-usage.md index 89e0fe7fa..54d7b36c9 100644 --- a/doc/01-usage.md +++ b/doc/01-usage.md @@ -90,7 +90,7 @@ use Monolog\Handler\FirePHPHandler; // Create the logger $logger = new Logger('my_logger'); // Now add some handlers -$logger->pushHandler(new StreamHandler(__DIR__.'/my_app.log', Logger::DEBUG)); +$logger->pushHandler(new StreamHandler(__DIR__.'/my_app.log', Level::Debug)); $logger->pushHandler(new FirePHPHandler()); // You can now use your logger @@ -170,7 +170,7 @@ use Monolog\Handler\StreamHandler; use Monolog\Handler\FirePHPHandler; // Create some handlers -$stream = new StreamHandler(__DIR__.'/my_app.log', Logger::DEBUG); +$stream = new StreamHandler(__DIR__.'/my_app.log', Level::Debug); $firephp = new FirePHPHandler(); // Create the main logger of the app @@ -205,7 +205,7 @@ You can choose between predefined formatter classes or write your own (e.g. a mu > A very useful formatter to look at, is the `LineFormatter`. > > This formatter, as its name might indicate, is able to return a lineal string representation of the log record provided. -> +> > It is also capable to interpolate values from the log record, into the output format template used by the formatter to generate the final result, and in order to do it, you need to provide the log record values you are interested in, in the output template string using the form %value%, e.g: "'%context.foo% => %extra.foo%'" , in this example the values $record->context["foo"] and $record->extra["foo"] will be rendered as part of th final result. In the following example, we demonstrate how to: @@ -229,7 +229,7 @@ $output = "%datetime% > %level_name% > %message% %context% %extra%\n"; $formatter = new LineFormatter($output, $dateFormat); // Create a handler -$stream = new StreamHandler(__DIR__.'/my_app.log', Logger::DEBUG); +$stream = new StreamHandler(__DIR__.'/my_app.log', Level::Debug); $stream->setFormatter($formatter); // bind it to a logger object diff --git a/doc/04-extending.md b/doc/04-extending.md index 0a2ad3386..49cded91b 100644 --- a/doc/04-extending.md +++ b/doc/04-extending.md @@ -30,7 +30,7 @@ class PDOHandler extends AbstractProcessingHandler private $pdo; private $statement; - public function __construct(PDO $pdo, $level = Logger::DEBUG, bool $bubble = true) + public function __construct(PDO $pdo, $level = Level::Debug, bool $bubble = true) { $this->pdo = $pdo; parent::__construct($level, $bubble); diff --git a/doc/sockets.md b/doc/sockets.md index c1190c235..d02f722de 100644 --- a/doc/sockets.md +++ b/doc/sockets.md @@ -26,7 +26,7 @@ $handler = new SocketHandler('unix:///var/log/httpd_app_log.socket'); $handler->setPersistent(true); // Now add the handler -$logger->pushHandler($handler, Logger::DEBUG); +$logger->pushHandler($handler, Level::Debug); // You can now use your logger $logger->info('My logger is now ready'); @@ -36,4 +36,3 @@ $logger->info('My logger is now ready'); In this example, using syslog-ng, you should see the log on the log server: cweb1 [2012-02-26 00:12:03] my_logger.INFO: My logger is now ready [] [] - diff --git a/src/Monolog/Formatter/ChromePHPFormatter.php b/src/Monolog/Formatter/ChromePHPFormatter.php index e855d64ac..0551e1a29 100644 --- a/src/Monolog/Formatter/ChromePHPFormatter.php +++ b/src/Monolog/Formatter/ChromePHPFormatter.php @@ -11,6 +11,7 @@ namespace Monolog\Formatter; +use Monolog\Level; use Monolog\Logger; use Monolog\LogRecord; @@ -24,18 +25,21 @@ class ChromePHPFormatter implements FormatterInterface /** * Translates Monolog log levels to Wildfire levels. * - * @var array + * @return 'log'|'info'|'warn'|'error' */ - private $logLevels = [ - Logger::DEBUG => 'log', - Logger::INFO => 'info', - Logger::NOTICE => 'info', - Logger::WARNING => 'warn', - Logger::ERROR => 'error', - Logger::CRITICAL => 'error', - Logger::ALERT => 'error', - Logger::EMERGENCY => 'error', - ]; + private function toWildfireLevel(Level $level): string + { + return match ($level) { + Level::Debug => 'log', + Level::Info => 'info', + Level::Notice => 'info', + Level::Warning => 'warn', + Level::Error => 'error', + Level::Critical => 'error', + Level::Alert => 'error', + Level::Emergency => 'error', + }; + } /** * {@inheritDoc} @@ -64,7 +68,7 @@ public function format(LogRecord $record) $record->channel, $message, $backtrace, - $this->logLevels[$record->level], + $this->toWildfireLevel($record->level), ]; } diff --git a/src/Monolog/Formatter/FlowdockFormatter.php b/src/Monolog/Formatter/FlowdockFormatter.php index 6518976e4..83a73c815 100644 --- a/src/Monolog/Formatter/FlowdockFormatter.php +++ b/src/Monolog/Formatter/FlowdockFormatter.php @@ -45,7 +45,7 @@ public function format(LogRecord $record): array { $tags = [ '#logs', - '#' . strtolower($record->levelName), + '#' . strtolower($record->levelName->value), '#' . $record->channel, ]; @@ -56,7 +56,7 @@ public function format(LogRecord $record): array $subject = sprintf( 'in %s: %s - %s', $this->source, - $record->levelName, + $record->levelName->value, $this->getShortMessage($record->message) ); diff --git a/src/Monolog/Formatter/FluentdFormatter.php b/src/Monolog/Formatter/FluentdFormatter.php index 31d4d5e2e..ce596df64 100644 --- a/src/Monolog/Formatter/FluentdFormatter.php +++ b/src/Monolog/Formatter/FluentdFormatter.php @@ -60,7 +60,7 @@ public function format(LogRecord $record): string { $tag = $record->channel; if ($this->levelTag) { - $tag .= '.' . strtolower($record->levelName); + $tag .= '.' . strtolower($record->levelName->value); } $message = [ @@ -70,8 +70,8 @@ public function format(LogRecord $record): string ]; if (!$this->levelTag) { - $message['level'] = $record->level; - $message['level_name'] = $record->levelName; + $message['level'] = $record->level->value; + $message['level_name'] = $record->levelName->value; } return Utils::jsonEncode([$tag, $record->datetime->getTimestamp(), $message]); diff --git a/src/Monolog/Formatter/GelfMessageFormatter.php b/src/Monolog/Formatter/GelfMessageFormatter.php index bf24b372c..5d2d9de89 100644 --- a/src/Monolog/Formatter/GelfMessageFormatter.php +++ b/src/Monolog/Formatter/GelfMessageFormatter.php @@ -11,6 +11,7 @@ namespace Monolog\Formatter; +use Monolog\Level; use Monolog\Logger; use Gelf\Message; use Monolog\Utils; @@ -21,8 +22,6 @@ * @see http://docs.graylog.org/en/latest/pages/gelf.html * * @author Matt Lehner - * - * @phpstan-import-type Level from \Monolog\Logger */ class GelfMessageFormatter extends NormalizerFormatter { @@ -50,21 +49,20 @@ class GelfMessageFormatter extends NormalizerFormatter /** * Translates Monolog log levels to Graylog2 log priorities. - * - * @var array - * - * @phpstan-var array */ - private $logLevels = [ - Logger::DEBUG => 7, - Logger::INFO => 6, - Logger::NOTICE => 5, - Logger::WARNING => 4, - Logger::ERROR => 3, - Logger::CRITICAL => 2, - Logger::ALERT => 1, - Logger::EMERGENCY => 0, - ]; + private function getGraylog2Priority(Level $level): int + { + return match ($level) { + Level::Debug => 7, + Level::Info => 6, + Level::Notice => 5, + Level::Warning => 4, + Level::Error => 3, + Level::Critical => 2, + Level::Alert => 1, + Level::Emergency => 0, + }; + } public function __construct(?string $systemName = null, ?string $extraPrefix = null, string $contextPrefix = 'ctxt_', ?int $maxLength = null) { @@ -101,7 +99,7 @@ public function format(LogRecord $record): Message ->setTimestamp($record->datetime) ->setShortMessage((string) $record->message) ->setHost($this->systemName) - ->setLevel($this->logLevels[$record->level]); + ->setLevel($this->getGraylog2Priority($record->level)); // message length + system name length + 200 for padding / metadata $len = 200 + strlen((string) $record->message) + strlen($this->systemName); diff --git a/src/Monolog/Formatter/HtmlFormatter.php b/src/Monolog/Formatter/HtmlFormatter.php index d534755e2..2841a38ec 100644 --- a/src/Monolog/Formatter/HtmlFormatter.php +++ b/src/Monolog/Formatter/HtmlFormatter.php @@ -11,6 +11,7 @@ namespace Monolog\Formatter; +use Monolog\Level; use Monolog\Logger; use Monolog\Utils; use Monolog\LogRecord; @@ -26,19 +27,20 @@ class HtmlFormatter extends NormalizerFormatter { /** * Translates Monolog log levels to html color priorities. - * - * @var array */ - protected $logLevels = [ - Logger::DEBUG => '#CCCCCC', - Logger::INFO => '#28A745', - Logger::NOTICE => '#17A2B8', - Logger::WARNING => '#FFC107', - Logger::ERROR => '#FD7E14', - Logger::CRITICAL => '#DC3545', - Logger::ALERT => '#821722', - Logger::EMERGENCY => '#000000', - ]; + protected function getLevelColor(Level $level): string + { + return match ($level) { + Level::Debug => '#CCCCCC', + Level::Info => '#28A745', + Level::Notice => '#17A2B8', + Level::Warning => '#FFC107', + Level::Error => '#FD7E14', + Level::Critical => '#DC3545', + Level::Alert => '#821722', + Level::Emergency => '#000000', + }; + } /** * @param string|null $dateFormat The format of the timestamp: one supported by DateTime::format @@ -69,14 +71,13 @@ protected function addRow(string $th, string $td = ' ', bool $escapeTd = true): * Create a HTML h1 tag * * @param string $title Text to be in the h1 - * @param int $level Error level * @return string */ - protected function addTitle(string $title, int $level): string + protected function addTitle(string $title, Level $level): string { $title = htmlspecialchars($title, ENT_NOQUOTES, 'UTF-8'); - return '

'.$title.'

'; + return '

'.$title.'

'; } /** @@ -86,7 +87,7 @@ protected function addTitle(string $title, int $level): string */ public function format(LogRecord $record): string { - $output = $this->addTitle($record->levelName, $record->level); + $output = $this->addTitle($record->levelName->value, $record->level); $output .= ''; $output .= $this->addRow('Message', (string) $record->message); diff --git a/src/Monolog/Formatter/WildfireFormatter.php b/src/Monolog/Formatter/WildfireFormatter.php index 0d7f23f09..7badab35a 100644 --- a/src/Monolog/Formatter/WildfireFormatter.php +++ b/src/Monolog/Formatter/WildfireFormatter.php @@ -11,6 +11,7 @@ namespace Monolog\Formatter; +use Monolog\Level; use Monolog\Logger; use Monolog\LogRecord; @@ -20,27 +21,9 @@ * @author Eric Clemmons (@ericclemmons) * @author Christophe Coevoet * @author Kirill chEbba Chebunin - * - * @phpstan-import-type Level from \Monolog\Logger */ class WildfireFormatter extends NormalizerFormatter { - /** - * Translates Monolog log levels to Wildfire levels. - * - * @var array - */ - private $logLevels = [ - Logger::DEBUG => 'LOG', - Logger::INFO => 'INFO', - Logger::NOTICE => 'INFO', - Logger::WARNING => 'WARN', - Logger::ERROR => 'ERROR', - Logger::CRITICAL => 'ERROR', - Logger::ALERT => 'ERROR', - Logger::EMERGENCY => 'ERROR', - ]; - /** * @param string|null $dateFormat The format of the timestamp: one supported by DateTime::format */ @@ -52,6 +35,25 @@ public function __construct(?string $dateFormat = null) $this->removeJsonEncodeOption(JSON_UNESCAPED_UNICODE); } + /** + * Translates Monolog log levels to Wildfire levels. + * + * @return 'LOG'|'INFO'|'WARN'|'ERROR' + */ + private function toWildfireLevel(Level $level): string + { + return match ($level) { + Level::Debug => 'LOG', + Level::Info => 'INFO', + Level::Notice => 'INFO', + Level::Warning => 'WARN', + Level::Error => 'ERROR', + Level::Critical => 'ERROR', + Level::Alert => 'ERROR', + Level::Emergency => 'ERROR', + }; + } + /** * {@inheritDoc} * @@ -89,7 +91,7 @@ public function format(LogRecord $record): string $label = $record->channel .': '. $record->message; $message = $message['context']['table']; } else { - $type = $this->logLevels[$record->level]; + $type = $this->toWildfireLevel($record->level); $label = $record->channel; } diff --git a/src/Monolog/Handler/AbstractHandler.php b/src/Monolog/Handler/AbstractHandler.php index 51f3db539..8d2486939 100644 --- a/src/Monolog/Handler/AbstractHandler.php +++ b/src/Monolog/Handler/AbstractHandler.php @@ -11,6 +11,8 @@ namespace Monolog\Handler; +use Monolog\Level; +use Monolog\LevelName; use Monolog\Logger; use Monolog\ResettableInterface; use Psr\Log\LogLevel; @@ -20,27 +22,20 @@ * Base Handler class providing basic level/bubble support * * @author Jordi Boggiano - * - * @phpstan-import-type Level from \Monolog\Logger - * @phpstan-import-type LevelName from \Monolog\Logger */ abstract class AbstractHandler extends Handler implements ResettableInterface { - /** - * @var int - * @phpstan-var Level - */ - protected $level = Logger::DEBUG; + protected Level $level = Level::Debug; /** @var bool */ protected $bubble = true; /** - * @param int|string $level The minimum logging level at which this handler will be triggered - * @param bool $bubble Whether the messages that are handled can bubble up the stack or not + * @param int|string|Level|LevelName|LogLevel::* $level The minimum logging level at which this handler will be triggered + * @param bool $bubble Whether the messages that are handled can bubble up the stack or not * - * @phpstan-param Level|LevelName|LogLevel::* $level + * @phpstan-param value-of|value-of|Level|LevelName|LogLevel::* $level */ - public function __construct($level = Logger::DEBUG, bool $bubble = true) + public function __construct(int|string|Level|LevelName $level = Level::Debug, bool $bubble = true) { $this->setLevel($level); $this->bubble = $bubble; @@ -51,7 +46,7 @@ public function __construct($level = Logger::DEBUG, bool $bubble = true) */ public function isHandling(LogRecord $record): bool { - return $record->level >= $this->level; + return $record->level->value >= $this->level->value; } /** @@ -59,8 +54,10 @@ public function isHandling(LogRecord $record): bool * * @param Level|LevelName|LogLevel::* $level Level or level name * @return self + * + * @phpstan-param value-of|value-of|Level|LevelName|LogLevel::* $level */ - public function setLevel($level): self + public function setLevel(int|string|Level|LevelName $level): self { $this->level = Logger::toMonologLevel($level); @@ -69,12 +66,8 @@ public function setLevel($level): self /** * Gets minimum logging level at which this handler will be triggered. - * - * @return int - * - * @phpstan-return Level */ - public function getLevel(): int + public function getLevel(): Level { return $this->level; } diff --git a/src/Monolog/Handler/AbstractProcessingHandler.php b/src/Monolog/Handler/AbstractProcessingHandler.php index 253200533..56a83cc16 100644 --- a/src/Monolog/Handler/AbstractProcessingHandler.php +++ b/src/Monolog/Handler/AbstractProcessingHandler.php @@ -20,9 +20,6 @@ * * @author Jordi Boggiano * @author Christophe Coevoet - * - * @phpstan-import-type LevelName from \Monolog\Logger - * @phpstan-import-type Level from \Monolog\Logger */ abstract class AbstractProcessingHandler extends AbstractHandler implements ProcessableHandlerInterface, FormattableHandlerInterface { diff --git a/src/Monolog/Handler/AbstractSyslogHandler.php b/src/Monolog/Handler/AbstractSyslogHandler.php index 5e5ad1c1f..0cba315d8 100644 --- a/src/Monolog/Handler/AbstractSyslogHandler.php +++ b/src/Monolog/Handler/AbstractSyslogHandler.php @@ -11,14 +11,12 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\LineFormatter; /** * Common syslog functionality - * - * @phpstan-import-type Level from \Monolog\Logger */ abstract class AbstractSyslogHandler extends AbstractProcessingHandler { @@ -27,54 +25,55 @@ abstract class AbstractSyslogHandler extends AbstractProcessingHandler /** * Translates Monolog log levels to syslog log priorities. - * @var array - * @phpstan-var array */ - protected $logLevels = [ - Logger::DEBUG => LOG_DEBUG, - Logger::INFO => LOG_INFO, - Logger::NOTICE => LOG_NOTICE, - Logger::WARNING => LOG_WARNING, - Logger::ERROR => LOG_ERR, - Logger::CRITICAL => LOG_CRIT, - Logger::ALERT => LOG_ALERT, - Logger::EMERGENCY => LOG_EMERG, - ]; + protected function toSyslogPriority(Level $level): int + { + return match ($level) { + Level::Debug => \LOG_DEBUG, + Level::Info => \LOG_INFO, + Level::Notice => \LOG_NOTICE, + Level::Warning => \LOG_WARNING, + Level::Error => \LOG_ERR, + Level::Critical => \LOG_CRIT, + Level::Alert => \LOG_ALERT, + Level::Emergency => \LOG_EMERG, + }; + } /** * List of valid log facility names. * @var array */ protected $facilities = [ - 'auth' => LOG_AUTH, - 'authpriv' => LOG_AUTHPRIV, - 'cron' => LOG_CRON, - 'daemon' => LOG_DAEMON, - 'kern' => LOG_KERN, - 'lpr' => LOG_LPR, - 'mail' => LOG_MAIL, - 'news' => LOG_NEWS, - 'syslog' => LOG_SYSLOG, - 'user' => LOG_USER, - 'uucp' => LOG_UUCP, + 'auth' => \LOG_AUTH, + 'authpriv' => \LOG_AUTHPRIV, + 'cron' => \LOG_CRON, + 'daemon' => \LOG_DAEMON, + 'kern' => \LOG_KERN, + 'lpr' => \LOG_LPR, + 'mail' => \LOG_MAIL, + 'news' => \LOG_NEWS, + 'syslog' => \LOG_SYSLOG, + 'user' => \LOG_USER, + 'uucp' => \LOG_UUCP, ]; /** * @param string|int $facility Either one of the names of the keys in $this->facilities, or a LOG_* facility constant */ - public function __construct($facility = LOG_USER, $level = Logger::DEBUG, bool $bubble = true) + public function __construct($facility = \LOG_USER, $level = Level::Debug, bool $bubble = true) { parent::__construct($level, $bubble); if (!defined('PHP_WINDOWS_VERSION_BUILD')) { - $this->facilities['local0'] = LOG_LOCAL0; - $this->facilities['local1'] = LOG_LOCAL1; - $this->facilities['local2'] = LOG_LOCAL2; - $this->facilities['local3'] = LOG_LOCAL3; - $this->facilities['local4'] = LOG_LOCAL4; - $this->facilities['local5'] = LOG_LOCAL5; - $this->facilities['local6'] = LOG_LOCAL6; - $this->facilities['local7'] = LOG_LOCAL7; + $this->facilities['local0'] = \LOG_LOCAL0; + $this->facilities['local1'] = \LOG_LOCAL1; + $this->facilities['local2'] = \LOG_LOCAL2; + $this->facilities['local3'] = \LOG_LOCAL3; + $this->facilities['local4'] = \LOG_LOCAL4; + $this->facilities['local5'] = \LOG_LOCAL5; + $this->facilities['local6'] = \LOG_LOCAL6; + $this->facilities['local7'] = \LOG_LOCAL7; } else { $this->facilities['local0'] = 128; // LOG_LOCAL0 $this->facilities['local1'] = 136; // LOG_LOCAL1 diff --git a/src/Monolog/Handler/AmqpHandler.php b/src/Monolog/Handler/AmqpHandler.php index 09c5b3d8a..3500732a2 100644 --- a/src/Monolog/Handler/AmqpHandler.php +++ b/src/Monolog/Handler/AmqpHandler.php @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\JsonFormatter; use PhpAmqpLib\Message\AMQPMessage; @@ -35,7 +35,7 @@ class AmqpHandler extends AbstractProcessingHandler * @param AMQPExchange|AMQPChannel $exchange AMQPExchange (php AMQP ext) or PHP AMQP lib channel, ready for use * @param string|null $exchangeName Optional exchange name, for AMQPChannel (PhpAmqpLib) only */ - public function __construct($exchange, ?string $exchangeName = null, $level = Logger::DEBUG, bool $bubble = true) + public function __construct($exchange, ?string $exchangeName = null, $level = Level::Debug, bool $bubble = true) { if ($exchange instanceof AMQPChannel) { $this->exchangeName = (string) $exchangeName; @@ -110,7 +110,7 @@ public function handleBatch(array $records): void */ protected function getRoutingKey(LogRecord $record): string { - $routingKey = sprintf('%s.%s', $record->levelName, $record->channel); + $routingKey = sprintf('%s.%s', $record->levelName->value, $record->channel); return strtolower($routingKey); } diff --git a/src/Monolog/Handler/BufferHandler.php b/src/Monolog/Handler/BufferHandler.php index 8edf6965f..26b3e7c1d 100644 --- a/src/Monolog/Handler/BufferHandler.php +++ b/src/Monolog/Handler/BufferHandler.php @@ -11,7 +11,8 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; +use Monolog\LevelName; use Monolog\ResettableInterface; use Monolog\Formatter\FormatterInterface; use Monolog\LogRecord; @@ -46,7 +47,7 @@ class BufferHandler extends AbstractHandler implements ProcessableHandlerInterfa * @param int $bufferLimit How many entries should be buffered at most, beyond that the oldest items are removed from the buffer. * @param bool $flushOnOverflow If true, the buffer is flushed when the max size has been reached, by default oldest entries are discarded */ - public function __construct(HandlerInterface $handler, int $bufferLimit = 0, $level = Logger::DEBUG, bool $bubble = true, bool $flushOnOverflow = false) + public function __construct(HandlerInterface $handler, int $bufferLimit = 0, int|string|Level|LevelName $level = Level::Debug, bool $bubble = true, bool $flushOnOverflow = false) { parent::__construct($level, $bubble); $this->handler = $handler; @@ -59,7 +60,7 @@ public function __construct(HandlerInterface $handler, int $bufferLimit = 0, $le */ public function handle(LogRecord $record): bool { - if ($record->level < $this->level) { + if ($record->level->isLowerThan($this->level)) { return false; } diff --git a/src/Monolog/Handler/ChromePHPHandler.php b/src/Monolog/Handler/ChromePHPHandler.php index 345ba90cf..b08f004c2 100644 --- a/src/Monolog/Handler/ChromePHPHandler.php +++ b/src/Monolog/Handler/ChromePHPHandler.php @@ -13,7 +13,7 @@ use Monolog\Formatter\ChromePHPFormatter; use Monolog\Formatter\FormatterInterface; -use Monolog\Logger; +use Monolog\Level; use Monolog\Utils; use Monolog\LogRecord; use Monolog\DateTimeImmutable; @@ -66,7 +66,7 @@ class ChromePHPHandler extends AbstractProcessingHandler /** @var bool */ protected static $sendHeaders = true; - public function __construct($level = Logger::DEBUG, bool $bubble = true) + public function __construct($level = Level::Debug, bool $bubble = true) { parent::__construct($level, $bubble); if (!function_exists('json_encode')) { @@ -155,7 +155,7 @@ protected function send(): void $record = new LogRecord( message: 'Incomplete logs, chrome header size limit reached', - level: Logger::WARNING, + level: Level::Warning, channel: 'monolog', datetime: new DateTimeImmutable(true), ); diff --git a/src/Monolog/Handler/CouchDBHandler.php b/src/Monolog/Handler/CouchDBHandler.php index abdce0b51..0369ee89c 100644 --- a/src/Monolog/Handler/CouchDBHandler.php +++ b/src/Monolog/Handler/CouchDBHandler.php @@ -13,7 +13,7 @@ use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\JsonFormatter; -use Monolog\Logger; +use Monolog\Level; use Monolog\LogRecord; /** @@ -29,7 +29,7 @@ class CouchDBHandler extends AbstractProcessingHandler /** * @param mixed[] $options */ - public function __construct(array $options = [], $level = Logger::DEBUG, bool $bubble = true) + public function __construct(array $options = [], $level = Level::Debug, bool $bubble = true) { $this->options = array_merge([ 'host' => 'localhost', diff --git a/src/Monolog/Handler/CubeHandler.php b/src/Monolog/Handler/CubeHandler.php index 40a16f5cf..d013671dd 100644 --- a/src/Monolog/Handler/CubeHandler.php +++ b/src/Monolog/Handler/CubeHandler.php @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Monolog\Utils; use Monolog\LogRecord; @@ -43,7 +43,7 @@ class CubeHandler extends AbstractProcessingHandler * A valid url must consist of three parts : protocol://host:port * Only valid protocols used by Cube are http and udp */ - public function __construct(string $url, $level = Logger::DEBUG, bool $bubble = true) + public function __construct(string $url, $level = Level::Debug, bool $bubble = true) { $urlInfo = parse_url($url); diff --git a/src/Monolog/Handler/DeduplicationHandler.php b/src/Monolog/Handler/DeduplicationHandler.php index f9d80f2d2..f1f01e3b4 100644 --- a/src/Monolog/Handler/DeduplicationHandler.php +++ b/src/Monolog/Handler/DeduplicationHandler.php @@ -11,6 +11,8 @@ namespace Monolog\Handler; +use Monolog\Level; +use Monolog\LevelName; use Monolog\Logger; use Psr\Log\LogLevel; use Monolog\LogRecord; @@ -34,8 +36,6 @@ * same way. * * @author Jordi Boggiano - * @phpstan-import-type LevelName from \Monolog\Logger - * @phpstan-import-type Level from \Monolog\Logger */ class DeduplicationHandler extends BufferHandler { @@ -62,15 +62,15 @@ class DeduplicationHandler extends BufferHandler /** * @param HandlerInterface $handler Handler. * @param string $deduplicationStore The file/path where the deduplication log should be kept - * @param string|int $deduplicationLevel The minimum logging level for log records to be looked at for deduplication purposes + * @param int|string|Level|LevelName|LogLevel::* $deduplicationLevel The minimum logging level for log records to be looked at for deduplication purposes * @param int $time The period (in seconds) during which duplicate entries should be suppressed after a given log is sent through * @param bool $bubble Whether the messages that are handled can bubble up the stack or not * - * @phpstan-param Level|LevelName|LogLevel::* $deduplicationLevel + * @phpstan-param value-of|value-of|Level|LevelName|LogLevel::* $deduplicationLevel */ - public function __construct(HandlerInterface $handler, ?string $deduplicationStore = null, $deduplicationLevel = Logger::ERROR, int $time = 60, bool $bubble = true) + public function __construct(HandlerInterface $handler, ?string $deduplicationStore = null, int|string|Level|LevelName $deduplicationLevel = Level::Error, int $time = 60, bool $bubble = true) { - parent::__construct($handler, 0, Logger::DEBUG, $bubble, false); + parent::__construct($handler, 0, Level::Debug, $bubble, false); $this->deduplicationStore = $deduplicationStore === null ? sys_get_temp_dir() . '/monolog-dedup-' . substr(md5(__FILE__), 0, 20) .'.log' : $deduplicationStore; $this->deduplicationLevel = Logger::toMonologLevel($deduplicationLevel); @@ -86,7 +86,7 @@ public function flush(): void $passthru = null; foreach ($this->buffer as $record) { - if ($record->level >= $this->deduplicationLevel) { + if ($record->level->value >= $this->deduplicationLevel->value) { $passthru = $passthru || !$this->isDuplicate($record); if ($passthru) { $this->appendRecord($record); @@ -124,7 +124,7 @@ private function isDuplicate(LogRecord $record): bool for ($i = count($store) - 1; $i >= 0; $i--) { list($timestamp, $level, $message) = explode(':', $store[$i], 3); - if ($level === $record->levelName && $message === $expectedMessage && $timestamp > $timestampValidity) { + if ($level === $record->levelName->value && $message === $expectedMessage && $timestamp > $timestampValidity) { return true; } @@ -174,6 +174,6 @@ private function collectLogs(): void private function appendRecord(LogRecord $record): void { - file_put_contents($this->deduplicationStore, $record->datetime->getTimestamp() . ':' . $record->levelName . ':' . preg_replace('{[\r\n].*}', '', $record->message) . "\n", FILE_APPEND); + file_put_contents($this->deduplicationStore, $record->datetime->getTimestamp() . ':' . $record->levelName->value . ':' . preg_replace('{[\r\n].*}', '', $record->message) . "\n", FILE_APPEND); } } diff --git a/src/Monolog/Handler/DoctrineCouchDBHandler.php b/src/Monolog/Handler/DoctrineCouchDBHandler.php index 9b3426f81..0ce3ae9f4 100644 --- a/src/Monolog/Handler/DoctrineCouchDBHandler.php +++ b/src/Monolog/Handler/DoctrineCouchDBHandler.php @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Monolog\Formatter\NormalizerFormatter; use Monolog\Formatter\FormatterInterface; use Doctrine\CouchDB\CouchDBClient; @@ -27,7 +27,7 @@ class DoctrineCouchDBHandler extends AbstractProcessingHandler /** @var CouchDBClient */ private $client; - public function __construct(CouchDBClient $client, $level = Logger::DEBUG, bool $bubble = true) + public function __construct(CouchDBClient $client, $level = Level::Debug, bool $bubble = true) { $this->client = $client; parent::__construct($level, $bubble); diff --git a/src/Monolog/Handler/DynamoDbHandler.php b/src/Monolog/Handler/DynamoDbHandler.php index 175ab71b7..c9c469f0d 100644 --- a/src/Monolog/Handler/DynamoDbHandler.php +++ b/src/Monolog/Handler/DynamoDbHandler.php @@ -16,7 +16,7 @@ use Monolog\Formatter\FormatterInterface; use Aws\DynamoDb\Marshaler; use Monolog\Formatter\ScalarFormatter; -use Monolog\Logger; +use Monolog\Level; use Monolog\LogRecord; /** @@ -44,7 +44,7 @@ class DynamoDbHandler extends AbstractProcessingHandler */ protected $marshaler; - public function __construct(DynamoDbClient $client, string $table, $level = Logger::DEBUG, bool $bubble = true) + public function __construct(DynamoDbClient $client, string $table, $level = Level::Debug, bool $bubble = true) { $this->marshaler = new Marshaler; diff --git a/src/Monolog/Handler/ElasticaHandler.php b/src/Monolog/Handler/ElasticaHandler.php index 838d9d2bb..29dc74b1b 100644 --- a/src/Monolog/Handler/ElasticaHandler.php +++ b/src/Monolog/Handler/ElasticaHandler.php @@ -14,7 +14,7 @@ use Elastica\Document; use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\ElasticaFormatter; -use Monolog\Logger; +use Monolog\Level; use Elastica\Client; use Elastica\Exception\ExceptionInterface; use Monolog\LogRecord; @@ -51,7 +51,7 @@ class ElasticaHandler extends AbstractProcessingHandler * @param Client $client Elastica Client object * @param mixed[] $options Handler configuration */ - public function __construct(Client $client, array $options = [], $level = Logger::DEBUG, bool $bubble = true) + public function __construct(Client $client, array $options = [], $level = Level::Debug, bool $bubble = true) { parent::__construct($level, $bubble); $this->client = $client; diff --git a/src/Monolog/Handler/ElasticsearchHandler.php b/src/Monolog/Handler/ElasticsearchHandler.php index 0694bcb08..a669dde70 100644 --- a/src/Monolog/Handler/ElasticsearchHandler.php +++ b/src/Monolog/Handler/ElasticsearchHandler.php @@ -13,7 +13,7 @@ use Throwable; use RuntimeException; -use Monolog\Logger; +use Monolog\Level; use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\ElasticsearchFormatter; use InvalidArgumentException; @@ -58,7 +58,7 @@ class ElasticsearchHandler extends AbstractProcessingHandler * @param Client $client Elasticsearch Client object * @param mixed[] $options Handler configuration */ - public function __construct(Client $client, array $options = [], $level = Logger::DEBUG, bool $bubble = true) + public function __construct(Client $client, array $options = [], $level = Level::Debug, bool $bubble = true) { parent::__construct($level, $bubble); $this->client = $client; diff --git a/src/Monolog/Handler/ErrorLogHandler.php b/src/Monolog/Handler/ErrorLogHandler.php index c0f622980..a80b63adf 100644 --- a/src/Monolog/Handler/ErrorLogHandler.php +++ b/src/Monolog/Handler/ErrorLogHandler.php @@ -13,7 +13,7 @@ use Monolog\Formatter\LineFormatter; use Monolog\Formatter\FormatterInterface; -use Monolog\Logger; +use Monolog\Level; use Monolog\Utils; use Monolog\LogRecord; @@ -36,7 +36,7 @@ class ErrorLogHandler extends AbstractProcessingHandler * @param int $messageType Says where the error should go. * @param bool $expandNewlines If set to true, newlines in the message will be expanded to be take multiple log entries */ - public function __construct(int $messageType = self::OPERATING_SYSTEM, $level = Logger::DEBUG, bool $bubble = true, bool $expandNewlines = false) + public function __construct(int $messageType = self::OPERATING_SYSTEM, $level = Level::Debug, bool $bubble = true, bool $expandNewlines = false) { parent::__construct($level, $bubble); diff --git a/src/Monolog/Handler/FilterHandler.php b/src/Monolog/Handler/FilterHandler.php index d6703fe16..b5dec9380 100644 --- a/src/Monolog/Handler/FilterHandler.php +++ b/src/Monolog/Handler/FilterHandler.php @@ -11,6 +11,8 @@ namespace Monolog\Handler; +use Monolog\Level; +use Monolog\LevelName; use Monolog\Logger; use Monolog\ResettableInterface; use Monolog\Formatter\FormatterInterface; @@ -24,8 +26,6 @@ * * @author Hennadiy Verkh * @author Jordi Boggiano - * @phpstan-import-type Level from \Monolog\Logger - * @phpstan-import-type LevelName from \Monolog\Logger */ class FilterHandler extends Handler implements ProcessableHandlerInterface, ResettableInterface, FormattableHandlerInterface { @@ -42,10 +42,10 @@ class FilterHandler extends Handler implements ProcessableHandlerInterface, Rese /** * Minimum level for logs that are passed to handler * - * @var int[] - * @phpstan-var array + * @var bool[] Map of Level value => true + * @phpstan-var array, true> */ - protected $acceptedLevels; + protected array $acceptedLevels; /** * Whether the messages that are handled can bubble up the stack or not @@ -58,14 +58,14 @@ class FilterHandler extends Handler implements ProcessableHandlerInterface, Rese * @phpstan-param (callable(LogRecord|null, HandlerInterface): HandlerInterface)|HandlerInterface $handler * * @param callable|HandlerInterface $handler Handler or factory callable($record|null, $filterHandler). - * @param int|array $minLevelOrList A list of levels to accept or a minimum level if maxLevel is provided - * @param int|string $maxLevel Maximum level to accept, only used if $minLevelOrList is not an array + * @param int|string|Level|LevelName|array $minLevelOrList A list of levels to accept or a minimum level if maxLevel is provided + * @param int|string|Level|LevelName|LogLevel::* $maxLevel Maximum level to accept, only used if $minLevelOrList is not an array * @param bool $bubble Whether the messages that are handled can bubble up the stack or not * - * @phpstan-param Level|LevelName|LogLevel::*|array $minLevelOrList - * @phpstan-param Level|LevelName|LogLevel::* $maxLevel + * @phpstan-param value-of|value-of|Level|LevelName|LogLevel::*|array|value-of|Level|LevelName|LogLevel::*> $minLevelOrList + * @phpstan-param value-of|value-of|Level|LevelName|LogLevel::* $maxLevel */ - public function __construct($handler, $minLevelOrList = Logger::DEBUG, $maxLevel = Logger::EMERGENCY, bool $bubble = true) + public function __construct($handler, int|string|Level|LevelName|array $minLevelOrList = Level::Debug, int|string|Level|LevelName $maxLevel = Level::Emergency, bool $bubble = true) { $this->handler = $handler; $this->bubble = $bubble; @@ -77,32 +77,33 @@ public function __construct($handler, $minLevelOrList = Logger::DEBUG, $maxLevel } /** - * @phpstan-return array + * @phpstan-return list List of levels */ public function getAcceptedLevels(): array { - return array_flip($this->acceptedLevels); + return array_map(fn(int $level) => Level::from($level), array_keys($this->acceptedLevels)); } /** - * @param int|string|array $minLevelOrList A list of levels to accept or a minimum level or level name if maxLevel is provided - * @param int|string $maxLevel Maximum level or level name to accept, only used if $minLevelOrList is not an array + * @param int|string|Level|LevelName|LogLevel::*|array $minLevelOrList A list of levels to accept or a minimum level or level name if maxLevel is provided + * @param int|string|Level|LevelName|LogLevel::* $maxLevel Maximum level or level name to accept, only used if $minLevelOrList is not an array * - * @phpstan-param Level|LevelName|LogLevel::*|array $minLevelOrList - * @phpstan-param Level|LevelName|LogLevel::* $maxLevel + * @phpstan-param value-of|value-of|Level|LevelName|LogLevel::*|array|value-of|Level|LevelName|LogLevel::*> $minLevelOrList + * @phpstan-param value-of|value-of|Level|LevelName|LogLevel::* $maxLevel */ - public function setAcceptedLevels($minLevelOrList = Logger::DEBUG, $maxLevel = Logger::EMERGENCY): self + public function setAcceptedLevels(int|string|Level|LevelName|array $minLevelOrList = Level::Debug, int|string|Level|LevelName $maxLevel = Level::Emergency): self { if (is_array($minLevelOrList)) { - $acceptedLevels = array_map('Monolog\Logger::toMonologLevel', $minLevelOrList); + $acceptedLevels = array_map(Logger::toMonologLevel(...), $minLevelOrList); } else { $minLevelOrList = Logger::toMonologLevel($minLevelOrList); $maxLevel = Logger::toMonologLevel($maxLevel); - $acceptedLevels = array_values(array_filter(Logger::getLevels(), function ($level) use ($minLevelOrList, $maxLevel) { - return $level >= $minLevelOrList && $level <= $maxLevel; - })); + $acceptedLevels = array_values(array_filter(Level::cases(), fn (Level $level) => $level->value >= $minLevelOrList->value && $level->value <= $maxLevel->value)); + } + $this->acceptedLevels = []; + foreach ($acceptedLevels as $level) { + $this->acceptedLevels[$level->value] = true; } - $this->acceptedLevels = array_flip($acceptedLevels); return $this; } @@ -112,7 +113,7 @@ public function setAcceptedLevels($minLevelOrList = Logger::DEBUG, $maxLevel = L */ public function isHandling(LogRecord $record): bool { - return isset($this->acceptedLevels[$record->level]); + return isset($this->acceptedLevels[$record->level->value]); } /** diff --git a/src/Monolog/Handler/FingersCrossed/ChannelLevelActivationStrategy.php b/src/Monolog/Handler/FingersCrossed/ChannelLevelActivationStrategy.php index ca34b3b78..4da75dff7 100644 --- a/src/Monolog/Handler/FingersCrossed/ChannelLevelActivationStrategy.php +++ b/src/Monolog/Handler/FingersCrossed/ChannelLevelActivationStrategy.php @@ -11,6 +11,8 @@ namespace Monolog\Handler\FingersCrossed; +use Monolog\Level; +use Monolog\LevelName; use Monolog\Logger; use Psr\Log\LogLevel; use Monolog\LogRecord; @@ -24,50 +26,45 @@ * * * $activationStrategy = new ChannelLevelActivationStrategy( - * Logger::CRITICAL, + * Level::Critical, * array( - * 'request' => Logger::ALERT, - * 'sensitive' => Logger::ERROR, + * 'request' => Level::Alert, + * 'sensitive' => Level::Error, * ) * ); * $handler = new FingersCrossedHandler(new StreamHandler('php://stderr'), $activationStrategy); * * * @author Mike Meessen - * @phpstan-import-type Level from \Monolog\Logger - * @phpstan-import-type LevelName from \Monolog\Logger */ class ChannelLevelActivationStrategy implements ActivationStrategyInterface { - /** - * @var Level - */ - private $defaultActionLevel; + private Level $defaultActionLevel; /** * @var array */ - private $channelToActionLevel; + private array $channelToActionLevel; /** - * @param int|string $defaultActionLevel The default action level to be used if the record's category doesn't match any - * @param array $channelToActionLevel An array that maps channel names to action levels. + * @param int|string|Level|LevelName|LogLevel::* $defaultActionLevel The default action level to be used if the record's category doesn't match any + * @param array $channelToActionLevel An array that maps channel names to action levels. * - * @phpstan-param array $channelToActionLevel - * @phpstan-param Level|LevelName|LogLevel::* $defaultActionLevel + * @phpstan-param value-of|value-of|Level|LevelName|LogLevel::* $defaultActionLevel + * @phpstan-param array|value-of|Level|LevelName|LogLevel::*> $channelToActionLevel */ - public function __construct($defaultActionLevel, array $channelToActionLevel = []) + public function __construct(int|string|Level|LevelName $defaultActionLevel, array $channelToActionLevel = []) { $this->defaultActionLevel = Logger::toMonologLevel($defaultActionLevel); - $this->channelToActionLevel = array_map('Monolog\Logger::toMonologLevel', $channelToActionLevel); + $this->channelToActionLevel = array_map(Logger::toMonologLevel(...), $channelToActionLevel); } public function isHandlerActivated(LogRecord $record): bool { if (isset($this->channelToActionLevel[$record->channel])) { - return $record->level >= $this->channelToActionLevel[$record->channel]; + return $record->level->value >= $this->channelToActionLevel[$record->channel]->value; } - return $record->level >= $this->defaultActionLevel; + return $record->level->value >= $this->defaultActionLevel->value; } } diff --git a/src/Monolog/Handler/FingersCrossed/ErrorLevelActivationStrategy.php b/src/Monolog/Handler/FingersCrossed/ErrorLevelActivationStrategy.php index ba98f5052..2b4e9ec71 100644 --- a/src/Monolog/Handler/FingersCrossed/ErrorLevelActivationStrategy.php +++ b/src/Monolog/Handler/FingersCrossed/ErrorLevelActivationStrategy.php @@ -11,37 +11,33 @@ namespace Monolog\Handler\FingersCrossed; +use Monolog\Level; +use Monolog\LevelName; +use Monolog\LogRecord; use Monolog\Logger; use Psr\Log\LogLevel; -use Monolog\LogRecord; /** * Error level based activation strategy. * * @author Johannes M. Schmitt - * - * @phpstan-import-type Level from \Monolog\Logger - * @phpstan-import-type LevelName from \Monolog\Logger */ class ErrorLevelActivationStrategy implements ActivationStrategyInterface { - /** - * @var Level - */ - private $actionLevel; + private Level $actionLevel; /** - * @param int|string $actionLevel Level or name or value + * @param int|string|Level|LevelName $actionLevel Level or name or value * - * @phpstan-param Level|LevelName|LogLevel::* $actionLevel + * @phpstan-param value-of|value-of|Level|LevelName|LogLevel::* $actionLevel */ - public function __construct($actionLevel) + public function __construct(int|string|Level|LevelName $actionLevel) { $this->actionLevel = Logger::toMonologLevel($actionLevel); } public function isHandlerActivated(LogRecord $record): bool { - return $record->level >= $this->actionLevel; + return $record->level->value >= $this->actionLevel->value; } } diff --git a/src/Monolog/Handler/FingersCrossedHandler.php b/src/Monolog/Handler/FingersCrossedHandler.php index 872b9a18e..fab57656c 100644 --- a/src/Monolog/Handler/FingersCrossedHandler.php +++ b/src/Monolog/Handler/FingersCrossedHandler.php @@ -13,6 +13,8 @@ use Monolog\Handler\FingersCrossed\ErrorLevelActivationStrategy; use Monolog\Handler\FingersCrossed\ActivationStrategyInterface; +use Monolog\Level; +use Monolog\LevelName; use Monolog\Logger; use Monolog\ResettableInterface; use Monolog\Formatter\FormatterInterface; @@ -34,8 +36,6 @@ * Monolog\Handler\FingersCrossed\ namespace. * * @author Jordi Boggiano - * @phpstan-import-type Level from \Monolog\Logger - * @phpstan-import-type LevelName from \Monolog\Logger */ class FingersCrossedHandler extends Handler implements ProcessableHandlerInterface, ResettableInterface, FormattableHandlerInterface { @@ -56,11 +56,7 @@ class FingersCrossedHandler extends Handler implements ProcessableHandlerInterfa protected $buffer = []; /** @var bool */ protected $stopBuffering; - /** - * @var ?int - * @phpstan-var ?Level - */ - protected $passthruLevel; + protected Level|null $passthruLevel = null; /** @var bool */ protected $bubble; @@ -68,19 +64,19 @@ class FingersCrossedHandler extends Handler implements ProcessableHandlerInterfa * @phpstan-param (callable(LogRecord|null, HandlerInterface): HandlerInterface)|HandlerInterface $handler * * @param callable|HandlerInterface $handler Handler or factory callable($record|null, $fingersCrossedHandler). - * @param int|string|ActivationStrategyInterface $activationStrategy Strategy which determines when this handler takes action, or a level name/value at which the handler is activated + * @param int|string|Level|LevelName|LogLevel::* $activationStrategy Strategy which determines when this handler takes action, or a level name/value at which the handler is activated * @param int $bufferSize How many entries should be buffered at most, beyond that the oldest items are removed from the buffer. * @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $stopBuffering Whether the handler should stop buffering after being triggered (default true) - * @param int|string $passthruLevel Minimum level to always flush to handler on close, even if strategy not triggered + * @param int|string|Level|LevelName|LogLevel::* $passthruLevel Minimum level to always flush to handler on close, even if strategy not triggered * - * @phpstan-param Level|LevelName|LogLevel::* $passthruLevel - * @phpstan-param Level|LevelName|LogLevel::*|ActivationStrategyInterface $activationStrategy + * @phpstan-param value-of|value-of|Level|LevelName|LogLevel::*|ActivationStrategyInterface $activationStrategy + * @phpstan-param value-of|value-of|Level|LevelName|LogLevel::* $passthruLevel */ - public function __construct($handler, $activationStrategy = null, int $bufferSize = 0, bool $bubble = true, bool $stopBuffering = true, $passthruLevel = null) + public function __construct($handler, int|string|Level|LevelName|ActivationStrategyInterface $activationStrategy = null, int $bufferSize = 0, bool $bubble = true, bool $stopBuffering = true, int|string|Level|LevelName $passthruLevel = null) { if (null === $activationStrategy) { - $activationStrategy = new ErrorLevelActivationStrategy(Logger::WARNING); + $activationStrategy = new ErrorLevelActivationStrategy(Level::Warning); } // convert simple int activationStrategy to an object diff --git a/src/Monolog/Handler/FleepHookHandler.php b/src/Monolog/Handler/FleepHookHandler.php index 82614cb8b..9f84c5bb2 100644 --- a/src/Monolog/Handler/FleepHookHandler.php +++ b/src/Monolog/Handler/FleepHookHandler.php @@ -13,7 +13,7 @@ use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\LineFormatter; -use Monolog\Logger; +use Monolog\Level; use Monolog\LogRecord; /** @@ -46,7 +46,7 @@ class FleepHookHandler extends SocketHandler */ public function __construct( string $token, - $level = Logger::DEBUG, + $level = Level::Debug, bool $bubble = true, bool $persistent = false, float $timeout = 0.0, diff --git a/src/Monolog/Handler/FlowdockHandler.php b/src/Monolog/Handler/FlowdockHandler.php index f15857ed6..dd3e61325 100644 --- a/src/Monolog/Handler/FlowdockHandler.php +++ b/src/Monolog/Handler/FlowdockHandler.php @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Monolog\Utils; use Monolog\Formatter\FlowdockFormatter; use Monolog\Formatter\FormatterInterface; @@ -40,7 +40,7 @@ class FlowdockHandler extends SocketHandler */ public function __construct( string $apiToken, - $level = Logger::DEBUG, + $level = Level::Debug, bool $bubble = true, bool $persistent = false, float $timeout = 0.0, diff --git a/src/Monolog/Handler/GelfHandler.php b/src/Monolog/Handler/GelfHandler.php index b29049c41..1b53dbdad 100644 --- a/src/Monolog/Handler/GelfHandler.php +++ b/src/Monolog/Handler/GelfHandler.php @@ -12,7 +12,7 @@ namespace Monolog\Handler; use Gelf\PublisherInterface; -use Monolog\Logger; +use Monolog\Level; use Monolog\Formatter\GelfMessageFormatter; use Monolog\Formatter\FormatterInterface; use Monolog\LogRecord; @@ -33,7 +33,7 @@ class GelfHandler extends AbstractProcessingHandler /** * @param PublisherInterface $publisher a gelf publisher object */ - public function __construct(PublisherInterface $publisher, $level = Logger::DEBUG, bool $bubble = true) + public function __construct(PublisherInterface $publisher, $level = Level::Debug, bool $bubble = true) { parent::__construct($level, $bubble); diff --git a/src/Monolog/Handler/HandlerInterface.php b/src/Monolog/Handler/HandlerInterface.php index c63ecbbf5..53bf28bf2 100644 --- a/src/Monolog/Handler/HandlerInterface.php +++ b/src/Monolog/Handler/HandlerInterface.php @@ -17,8 +17,6 @@ * Interface that all Monolog Handlers must implement * * @author Jordi Boggiano - * - * @phpstan-import-type Level from \Monolog\Logger */ interface HandlerInterface { diff --git a/src/Monolog/Handler/IFTTTHandler.php b/src/Monolog/Handler/IFTTTHandler.php index 4eaa1c951..da50bdd5e 100644 --- a/src/Monolog/Handler/IFTTTHandler.php +++ b/src/Monolog/Handler/IFTTTHandler.php @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Monolog\Utils; use Monolog\LogRecord; @@ -37,7 +37,7 @@ class IFTTTHandler extends AbstractProcessingHandler * @param string $eventName The name of the IFTTT Maker event that should be triggered * @param string $secretKey A valid IFTTT secret key */ - public function __construct(string $eventName, string $secretKey, $level = Logger::ERROR, bool $bubble = true) + public function __construct(string $eventName, string $secretKey, $level = Level::Error, bool $bubble = true) { if (!extension_loaded('curl')) { throw new MissingExtensionException('The curl extension is needed to use the IFTTTHandler'); diff --git a/src/Monolog/Handler/InsightOpsHandler.php b/src/Monolog/Handler/InsightOpsHandler.php index 0223d5bb4..f66321879 100644 --- a/src/Monolog/Handler/InsightOpsHandler.php +++ b/src/Monolog/Handler/InsightOpsHandler.php @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Monolog\LogRecord; /** @@ -38,7 +38,7 @@ public function __construct( string $token, string $region = 'us', bool $useSSL = true, - $level = Logger::DEBUG, + $level = Level::Debug, bool $bubble = true, bool $persistent = false, float $timeout = 0.0, diff --git a/src/Monolog/Handler/LogEntriesHandler.php b/src/Monolog/Handler/LogEntriesHandler.php index 8fe5d869a..ffa2b0a94 100644 --- a/src/Monolog/Handler/LogEntriesHandler.php +++ b/src/Monolog/Handler/LogEntriesHandler.php @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Monolog\LogRecord; /** @@ -34,7 +34,7 @@ class LogEntriesHandler extends SocketHandler public function __construct( string $token, bool $useSSL = true, - $level = Logger::DEBUG, + $level = Level::Debug, bool $bubble = true, string $host = 'data.logentries.com', bool $persistent = false, diff --git a/src/Monolog/Handler/LogglyHandler.php b/src/Monolog/Handler/LogglyHandler.php index ef74ee16c..07cad3914 100644 --- a/src/Monolog/Handler/LogglyHandler.php +++ b/src/Monolog/Handler/LogglyHandler.php @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\LogglyFormatter; use function array_key_exists; @@ -49,7 +49,7 @@ class LogglyHandler extends AbstractProcessingHandler * * @throws MissingExtensionException If the curl extension is missing */ - public function __construct(string $token, $level = Logger::DEBUG, bool $bubble = true) + public function __construct(string $token, $level = Level::Debug, bool $bubble = true) { if (!extension_loaded('curl')) { throw new MissingExtensionException('The curl extension is needed to use the LogglyHandler'); diff --git a/src/Monolog/Handler/LogmaticHandler.php b/src/Monolog/Handler/LogmaticHandler.php index b2799c2d4..b82bfbf19 100644 --- a/src/Monolog/Handler/LogmaticHandler.php +++ b/src/Monolog/Handler/LogmaticHandler.php @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\LogmaticFormatter; use Monolog\LogRecord; @@ -49,7 +49,7 @@ public function __construct( string $hostname = '', string $appname = '', bool $useSSL = true, - $level = Logger::DEBUG, + $level = Level::Debug, bool $bubble = true, bool $persistent = false, float $timeout = 0.0, diff --git a/src/Monolog/Handler/MailHandler.php b/src/Monolog/Handler/MailHandler.php index bfbe98fef..decd260cc 100644 --- a/src/Monolog/Handler/MailHandler.php +++ b/src/Monolog/Handler/MailHandler.php @@ -30,7 +30,7 @@ public function handleBatch(array $records): void $messages = []; foreach ($records as $record) { - if ($record->level < $this->level) { + if ($record->level->isLowerThan($this->level)) { continue; } @@ -68,7 +68,7 @@ protected function getHighestRecord(array $records): LogRecord { $highestRecord = null; foreach ($records as $record) { - if ($highestRecord === null || $highestRecord['level'] < $record->level) { + if ($highestRecord === null || $record->level->isHigherThan($highestRecord->level)) { $highestRecord = $record; } } diff --git a/src/Monolog/Handler/MandrillHandler.php b/src/Monolog/Handler/MandrillHandler.php index 9fe105474..07f85bbc4 100644 --- a/src/Monolog/Handler/MandrillHandler.php +++ b/src/Monolog/Handler/MandrillHandler.php @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Swift; use Swift_Message; @@ -33,7 +33,7 @@ class MandrillHandler extends MailHandler * @param string $apiKey A valid Mandrill API key * @param callable|Swift_Message $message An example message for real messages, only the body will be replaced */ - public function __construct(string $apiKey, $message, $level = Logger::ERROR, bool $bubble = true) + public function __construct(string $apiKey, $message, $level = Level::Error, bool $bubble = true) { parent::__construct($level, $bubble); diff --git a/src/Monolog/Handler/MongoDBHandler.php b/src/Monolog/Handler/MongoDBHandler.php index 50aaa1e68..d8248f999 100644 --- a/src/Monolog/Handler/MongoDBHandler.php +++ b/src/Monolog/Handler/MongoDBHandler.php @@ -14,7 +14,7 @@ use MongoDB\Driver\BulkWrite; use MongoDB\Driver\Manager; use MongoDB\Client; -use Monolog\Logger; +use Monolog\Level; use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\MongoDBFormatter; use Monolog\LogRecord; @@ -47,7 +47,7 @@ class MongoDBHandler extends AbstractProcessingHandler * @param string $database Database name * @param string $collection Collection name */ - public function __construct($mongodb, string $database, string $collection, $level = Logger::DEBUG, bool $bubble = true) + public function __construct($mongodb, string $database, string $collection, $level = Level::Debug, bool $bubble = true) { if (!($mongodb instanceof Client || $mongodb instanceof Manager)) { throw new \InvalidArgumentException('MongoDB\Client or MongoDB\Driver\Manager instance required'); diff --git a/src/Monolog/Handler/NativeMailerHandler.php b/src/Monolog/Handler/NativeMailerHandler.php index 0c0a3bdb1..6aad468ae 100644 --- a/src/Monolog/Handler/NativeMailerHandler.php +++ b/src/Monolog/Handler/NativeMailerHandler.php @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Monolog\Formatter\LineFormatter; /** @@ -70,7 +70,7 @@ class NativeMailerHandler extends MailHandler * @param string $from The sender of the mail * @param int $maxColumnWidth The maximum column width that the message lines will have */ - public function __construct($to, string $subject, string $from, $level = Logger::ERROR, bool $bubble = true, int $maxColumnWidth = 70) + public function __construct($to, string $subject, string $from, $level = Level::Error, bool $bubble = true, int $maxColumnWidth = 70) { parent::__construct($level, $bubble); $this->to = (array) $to; diff --git a/src/Monolog/Handler/NewRelicHandler.php b/src/Monolog/Handler/NewRelicHandler.php index 113aaa49e..3b3ae7588 100644 --- a/src/Monolog/Handler/NewRelicHandler.php +++ b/src/Monolog/Handler/NewRelicHandler.php @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Monolog\Utils; use Monolog\Formatter\NormalizerFormatter; use Monolog\Formatter\FormatterInterface; @@ -58,7 +58,7 @@ class NewRelicHandler extends AbstractProcessingHandler * @param string|null $transactionName */ public function __construct( - $level = Logger::ERROR, + $level = Level::Error, bool $bubble = true, ?string $appName = null, bool $explodeArrays = false, diff --git a/src/Monolog/Handler/NullHandler.php b/src/Monolog/Handler/NullHandler.php index 99c1e6596..923d59283 100644 --- a/src/Monolog/Handler/NullHandler.php +++ b/src/Monolog/Handler/NullHandler.php @@ -11,8 +11,10 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; +use Monolog\LevelName; use Psr\Log\LogLevel; +use Monolog\Logger; use Monolog\LogRecord; /** @@ -22,23 +24,17 @@ * to put on top of an existing stack to override it temporarily. * * @author Jordi Boggiano - * - * @phpstan-import-type Level from \Monolog\Logger - * @phpstan-import-type LevelName from \Monolog\Logger */ class NullHandler extends Handler { - /** - * @var int - */ - private $level; + private Level $level; /** - * @param string|int $level The minimum logging level at which this handler will be triggered + * @param string|int|Level|LevelName $level The minimum logging level at which this handler will be triggered * - * @phpstan-param Level|LevelName|LogLevel::* $level + * @phpstan-param value-of|value-of|Level|LevelName|LogLevel::* $level */ - public function __construct($level = Logger::DEBUG) + public function __construct(string|int|Level|LevelName $level = Level::Debug) { $this->level = Logger::toMonologLevel($level); } @@ -48,7 +44,7 @@ public function __construct($level = Logger::DEBUG) */ public function isHandling(LogRecord $record): bool { - return $record->level >= $this->level; + return $record->level->value >= $this->level->value; } /** @@ -56,6 +52,6 @@ public function isHandling(LogRecord $record): bool */ public function handle(LogRecord $record): bool { - return $record->level >= $this->level; + return $record->level->value >= $this->level->value; } } diff --git a/src/Monolog/Handler/OverflowHandler.php b/src/Monolog/Handler/OverflowHandler.php index af33424fe..d1f42781e 100644 --- a/src/Monolog/Handler/OverflowHandler.php +++ b/src/Monolog/Handler/OverflowHandler.php @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Monolog\Formatter\FormatterInterface; use Monolog\LogRecord; @@ -28,7 +28,7 @@ * $handler = new SomeHandler(...) * * // Pass all warnings to the handler when more than 10 & all error messages when more then 5 - * $overflow = new OverflowHandler($handler, [Logger::WARNING => 10, Logger::ERROR => 5]); + * $overflow = new OverflowHandler($handler, [Level::Warning->value => 10, Level::Error->value => 5]); * * $log->pushHandler($overflow); *``` @@ -40,17 +40,8 @@ class OverflowHandler extends AbstractHandler implements FormattableHandlerInter /** @var HandlerInterface */ private $handler; - /** @var int[] */ - private $thresholdMap = [ - Logger::DEBUG => 0, - Logger::INFO => 0, - Logger::NOTICE => 0, - Logger::WARNING => 0, - Logger::ERROR => 0, - Logger::CRITICAL => 0, - Logger::ALERT => 0, - Logger::EMERGENCY => 0, - ]; + /** @var array */ + private $thresholdMap = []; /** * Buffer of all messages passed to the handler before the threshold was reached @@ -61,12 +52,12 @@ class OverflowHandler extends AbstractHandler implements FormattableHandlerInter /** * @param HandlerInterface $handler - * @param int[] $thresholdMap Dictionary of logger level => threshold + * @param array $thresholdMap Dictionary of log level value => threshold */ public function __construct( HandlerInterface $handler, array $thresholdMap = [], - $level = Logger::DEBUG, + $level = Level::Debug, bool $bubble = true ) { $this->handler = $handler; @@ -90,11 +81,11 @@ public function __construct( */ public function handle(LogRecord $record): bool { - if ($record->level < $this->level) { + if ($record->level->isLowerThan($this->level)) { return false; } - $level = $record->level; + $level = $record->level->value; if (!isset($this->thresholdMap[$level])) { $this->thresholdMap[$level] = 0; diff --git a/src/Monolog/Handler/PHPConsoleHandler.php b/src/Monolog/Handler/PHPConsoleHandler.php index d4aeb9e96..ff6c707f3 100644 --- a/src/Monolog/Handler/PHPConsoleHandler.php +++ b/src/Monolog/Handler/PHPConsoleHandler.php @@ -13,7 +13,7 @@ use Monolog\Formatter\LineFormatter; use Monolog\Formatter\FormatterInterface; -use Monolog\Logger; +use Monolog\Level; use Monolog\Utils; use PhpConsole\Connector; use PhpConsole\Handler as VendorPhpConsoleHandler; @@ -73,7 +73,7 @@ class PHPConsoleHandler extends AbstractProcessingHandler * @param Connector|null $connector Instance of \PhpConsole\Connector class (optional) * @throws \RuntimeException */ - public function __construct(array $options = [], ?Connector $connector = null, $level = Logger::DEBUG, bool $bubble = true) + public function __construct(array $options = [], ?Connector $connector = null, $level = Level::Debug, bool $bubble = true) { if (!class_exists('PhpConsole\Connector')) { throw new \RuntimeException('PHP Console library not found. See https://github.com/barbushin/php-console#installation'); @@ -180,7 +180,7 @@ public function handle(LogRecord $record): bool */ protected function write(LogRecord $record): void { - if ($record->level < Logger::NOTICE) { + if ($record->level->isLowerThan(Level::Notice)) { $this->handleDebugRecord($record); } elseif (isset($record->context['exception']) && $record->context['exception'] instanceof \Throwable) { $this->handleExceptionRecord($record); @@ -239,7 +239,7 @@ private function getRecordTags(LogRecord $record): array } } - return [$tags ?: strtolower($record->levelName), $filteredContext]; + return [$tags ?: strtolower($record->levelName->value), $filteredContext]; } /** diff --git a/src/Monolog/Handler/ProcessHandler.php b/src/Monolog/Handler/ProcessHandler.php index d2c3cea90..c43b88631 100644 --- a/src/Monolog/Handler/ProcessHandler.php +++ b/src/Monolog/Handler/ProcessHandler.php @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Monolog\LogRecord; /** @@ -64,7 +64,7 @@ class ProcessHandler extends AbstractProcessingHandler * @param string|null $cwd "Current working directory" (CWD) for the process to be executed in. * @throws \InvalidArgumentException */ - public function __construct(string $command, $level = Logger::DEBUG, bool $bubble = true, ?string $cwd = null) + public function __construct(string $command, $level = Level::Debug, bool $bubble = true, ?string $cwd = null) { if ($command === '') { throw new \InvalidArgumentException('The command argument must be a non-empty string.'); diff --git a/src/Monolog/Handler/PsrHandler.php b/src/Monolog/Handler/PsrHandler.php index 50fee1725..30369e27a 100644 --- a/src/Monolog/Handler/PsrHandler.php +++ b/src/Monolog/Handler/PsrHandler.php @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Psr\Log\LoggerInterface; use Monolog\Formatter\FormatterInterface; use Monolog\LogRecord; @@ -42,7 +42,7 @@ class PsrHandler extends AbstractHandler implements FormattableHandlerInterface /** * @param LoggerInterface $logger The underlying PSR-3 compliant logger to which messages will be proxied */ - public function __construct(LoggerInterface $logger, $level = Logger::DEBUG, bool $bubble = true) + public function __construct(LoggerInterface $logger, $level = Level::Debug, bool $bubble = true) { parent::__construct($level, $bubble); @@ -60,9 +60,9 @@ public function handle(LogRecord $record): bool if ($this->formatter) { $formatted = $this->formatter->format($record); - $this->logger->log(strtolower($record->levelName), (string) $formatted, $record->context); + $this->logger->log(strtolower($record->levelName->value), (string) $formatted, $record->context); } else { - $this->logger->log(strtolower($record->levelName), $record->message, $record->context); + $this->logger->log(strtolower($record->levelName->value), $record->message, $record->context); } return false === $this->bubble; diff --git a/src/Monolog/Handler/PushoverHandler.php b/src/Monolog/Handler/PushoverHandler.php index 57bdff8df..0e3db9dce 100644 --- a/src/Monolog/Handler/PushoverHandler.php +++ b/src/Monolog/Handler/PushoverHandler.php @@ -11,6 +11,8 @@ namespace Monolog\Handler; +use Monolog\Level; +use Monolog\LevelName; use Monolog\Logger; use Monolog\Utils; use Psr\Log\LogLevel; @@ -21,9 +23,6 @@ * * @author Sebastian Göttschkes * @see https://www.pushover.net/api - * - * @phpstan-import-type Level from \Monolog\Logger - * @phpstan-import-type LevelName from \Monolog\Logger */ class PushoverHandler extends SocketHandler { @@ -40,10 +39,8 @@ class PushoverHandler extends SocketHandler /** @var int */ private $expire; - /** @var int */ - private $highPriorityLevel; - /** @var int */ - private $emergencyLevel; + private Level $highPriorityLevel; + private Level $emergencyLevel; /** @var bool */ private $useFormattedMessage = false; @@ -85,28 +82,30 @@ class PushoverHandler extends SocketHandler * @param string|null $title Title sent to the Pushover API * @param bool $useSSL Whether to connect via SSL. Required when pushing messages to users that are not * the pushover.net app owner. OpenSSL is required for this option. - * @param string|int $highPriorityLevel The minimum logging level at which this handler will start - * sending "high priority" requests to the Pushover API - * @param string|int $emergencyLevel The minimum logging level at which this handler will start - * sending "emergency" requests to the Pushover API * @param int $retry The retry parameter specifies how often (in seconds) the Pushover servers will * send the same notification to the user. * @param int $expire The expire parameter specifies how many seconds your notification will continue * to be retried for (every retry seconds). * + * @param int|string|Level|LevelName|LogLevel::* $highPriorityLevel The minimum logging level at which this handler will start + * sending "high priority" requests to the Pushover API + * @param int|string|Level|LevelName|LogLevel::* $emergencyLevel The minimum logging level at which this handler will start + * sending "emergency" requests to the Pushover API + * + * * @phpstan-param string|array $users - * @phpstan-param Level|LevelName|LogLevel::* $highPriorityLevel - * @phpstan-param Level|LevelName|LogLevel::* $emergencyLevel + * @phpstan-param value-of|value-of|Level|LevelName|LogLevel::* $highPriorityLevel + * @phpstan-param value-of|value-of|Level|LevelName|LogLevel::* $emergencyLevel */ public function __construct( string $token, $users, ?string $title = null, - $level = Logger::CRITICAL, + int|string|Level|LevelName $level = Level::Critical, bool $bubble = true, bool $useSSL = true, - $highPriorityLevel = Logger::CRITICAL, - $emergencyLevel = Logger::EMERGENCY, + int|string|Level|LevelName $highPriorityLevel = Level::Critical, + int|string|Level|LevelName $emergencyLevel = Level::Emergency, int $retry = 30, int $expire = 25200, bool $persistent = false, @@ -161,11 +160,11 @@ private function buildContent(LogRecord $record): string 'timestamp' => $timestamp, ]; - if (isset($record->level) && $record->level >= $this->emergencyLevel) { + if ($record->level->value >= $this->emergencyLevel->value) { $dataArray['priority'] = 2; $dataArray['retry'] = $this->retry; $dataArray['expire'] = $this->expire; - } elseif (isset($record->level) && $record->level >= $this->highPriorityLevel) { + } elseif ($record->level->value >= $this->highPriorityLevel->value) { $dataArray['priority'] = 1; } @@ -208,25 +207,25 @@ protected function write(LogRecord $record): void } /** - * @param int|string $value + * @param int|string|Level|LevelName|LogLevel::* $level * - * @phpstan-param Level|LevelName|LogLevel::* $value + * @phpstan-param value-of|value-of|Level|LevelName|LogLevel::* $level */ - public function setHighPriorityLevel($value): self + public function setHighPriorityLevel(int|string|Level|LevelName $level): self { - $this->highPriorityLevel = Logger::toMonologLevel($value); + $this->highPriorityLevel = Logger::toMonologLevel($level); return $this; } /** - * @param int|string $value + * @param int|string|Level|LevelName|LogLevel::* $level * - * @phpstan-param Level|LevelName|LogLevel::* $value + * @phpstan-param value-of|value-of|Level|LevelName|LogLevel::* $level */ - public function setEmergencyLevel($value): self + public function setEmergencyLevel(int|string|Level|LevelName $level): self { - $this->emergencyLevel = Logger::toMonologLevel($value); + $this->emergencyLevel = Logger::toMonologLevel($level); return $this; } @@ -234,9 +233,9 @@ public function setEmergencyLevel($value): self /** * Use the formatted message? */ - public function useFormattedMessage(bool $value): self + public function useFormattedMessage(bool $useFormattedMessage): self { - $this->useFormattedMessage = $value; + $this->useFormattedMessage = $useFormattedMessage; return $this; } diff --git a/src/Monolog/Handler/RedisHandler.php b/src/Monolog/Handler/RedisHandler.php index 6b652ce57..eecbf837a 100644 --- a/src/Monolog/Handler/RedisHandler.php +++ b/src/Monolog/Handler/RedisHandler.php @@ -13,7 +13,7 @@ use Monolog\Formatter\LineFormatter; use Monolog\Formatter\FormatterInterface; -use Monolog\Logger; +use Monolog\Level; use Monolog\LogRecord; /** @@ -41,7 +41,7 @@ class RedisHandler extends AbstractProcessingHandler * @param string $key The key name to push records to * @param int $capSize Number of entries to limit list size to, 0 = unlimited */ - public function __construct($redis, string $key, $level = Logger::DEBUG, bool $bubble = true, int $capSize = 0) + public function __construct($redis, string $key, $level = Level::Debug, bool $bubble = true, int $capSize = 0) { if (!(($redis instanceof \Predis\Client) || ($redis instanceof \Redis))) { throw new \InvalidArgumentException('Predis\Client or Redis instance required'); diff --git a/src/Monolog/Handler/RedisPubSubHandler.php b/src/Monolog/Handler/RedisPubSubHandler.php index 0d58ed288..01138cc7c 100644 --- a/src/Monolog/Handler/RedisPubSubHandler.php +++ b/src/Monolog/Handler/RedisPubSubHandler.php @@ -13,7 +13,7 @@ use Monolog\Formatter\LineFormatter; use Monolog\Formatter\FormatterInterface; -use Monolog\Logger; +use Monolog\Level; use Monolog\LogRecord; /** @@ -22,7 +22,7 @@ * usage example: * * $log = new Logger('application'); - * $redis = new RedisPubSubHandler(new Predis\Client("tcp://localhost:6379"), "logs", Logger::WARNING); + * $redis = new RedisPubSubHandler(new Predis\Client("tcp://localhost:6379"), "logs", Level::Warning); * $log->pushHandler($redis); * * @author Gaëtan Faugère @@ -38,7 +38,7 @@ class RedisPubSubHandler extends AbstractProcessingHandler * @param \Predis\Client<\Predis\Client>|\Redis $redis The redis instance * @param string $key The channel key to publish records to */ - public function __construct($redis, string $key, $level = Logger::DEBUG, bool $bubble = true) + public function __construct($redis, string $key, $level = Level::Debug, bool $bubble = true) { if (!(($redis instanceof \Predis\Client) || ($redis instanceof \Redis))) { throw new \InvalidArgumentException('Predis\Client or Redis instance required'); diff --git a/src/Monolog/Handler/RollbarHandler.php b/src/Monolog/Handler/RollbarHandler.php index 76b320543..1f082cd61 100644 --- a/src/Monolog/Handler/RollbarHandler.php +++ b/src/Monolog/Handler/RollbarHandler.php @@ -11,9 +11,10 @@ namespace Monolog\Handler; +use Monolog\Level; +use Monolog\LevelName; use Rollbar\RollbarLogger; use Throwable; -use Monolog\Logger; use Monolog\LogRecord; /** @@ -39,18 +40,6 @@ class RollbarHandler extends AbstractProcessingHandler */ protected $rollbarLogger; - /** @var string[] */ - protected $levelMap = [ - Logger::DEBUG => 'debug', - Logger::INFO => 'info', - Logger::NOTICE => 'info', - Logger::WARNING => 'warning', - Logger::ERROR => 'error', - Logger::CRITICAL => 'critical', - Logger::ALERT => 'critical', - Logger::EMERGENCY => 'critical', - ]; - /** * Records whether any log records have been added since the last flush of the rollbar notifier * @@ -64,13 +53,32 @@ class RollbarHandler extends AbstractProcessingHandler /** * @param RollbarLogger $rollbarLogger RollbarLogger object constructed with valid token */ - public function __construct(RollbarLogger $rollbarLogger, $level = Logger::ERROR, bool $bubble = true) + public function __construct(RollbarLogger $rollbarLogger, int|string|Level|LevelName $level = Level::Error, bool $bubble = true) { $this->rollbarLogger = $rollbarLogger; parent::__construct($level, $bubble); } + /** + * Translates Monolog log levels to Rollbar levels. + * + * @return 'debug'|'info'|'warning'|'error'|'critical' + */ + protected function toRollbarLevel(Level $level): string + { + return match ($level) { + Level::Debug => 'debug', + Level::Info => 'info', + Level::Notice => 'info', + Level::Warning => 'warning', + Level::Error => 'error', + Level::Critical => 'critical', + Level::Alert => 'critical', + Level::Emergency => 'critical', + }; + } + /** * {@inheritDoc} */ @@ -84,7 +92,7 @@ protected function write(LogRecord $record): void $context = $record->context; $context = array_merge($context, $record->extra, [ - 'level' => $this->levelMap[$record->level], + 'level' => $this->toRollbarLevel($record->level), 'monolog_level' => $record->levelName, 'channel' => $record->channel, 'datetime' => $record->datetime->format('U'), diff --git a/src/Monolog/Handler/RotatingFileHandler.php b/src/Monolog/Handler/RotatingFileHandler.php index 39abfc95e..e7d27aace 100644 --- a/src/Monolog/Handler/RotatingFileHandler.php +++ b/src/Monolog/Handler/RotatingFileHandler.php @@ -12,7 +12,7 @@ namespace Monolog\Handler; use InvalidArgumentException; -use Monolog\Logger; +use Monolog\Level; use Monolog\Utils; use Monolog\LogRecord; @@ -50,7 +50,7 @@ class RotatingFileHandler extends StreamHandler * @param int|null $filePermission Optional file permissions (default (0644) are only for owner read/write) * @param bool $useLocking Try to lock log file before doing any writes */ - public function __construct(string $filename, int $maxFiles = 0, $level = Logger::DEBUG, bool $bubble = true, ?int $filePermission = null, bool $useLocking = false) + public function __construct(string $filename, int $maxFiles = 0, $level = Level::Debug, bool $bubble = true, ?int $filePermission = null, bool $useLocking = false) { $this->filename = Utils::canonicalizePath($filename); $this->maxFiles = $maxFiles; diff --git a/src/Monolog/Handler/SamplingHandler.php b/src/Monolog/Handler/SamplingHandler.php index 39f1e0d7c..8238de846 100644 --- a/src/Monolog/Handler/SamplingHandler.php +++ b/src/Monolog/Handler/SamplingHandler.php @@ -27,7 +27,6 @@ * * @author Bryan Davis * @author Kunal Mehta - * @phpstan-import-type Level from \Monolog\Logger */ class SamplingHandler extends AbstractHandler implements ProcessableHandlerInterface, FormattableHandlerInterface { diff --git a/src/Monolog/Handler/SendGridHandler.php b/src/Monolog/Handler/SendGridHandler.php index 1280ee703..50b23e2c7 100644 --- a/src/Monolog/Handler/SendGridHandler.php +++ b/src/Monolog/Handler/SendGridHandler.php @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; /** * SendGridrHandler uses the SendGrid API v2 function to send Log emails, more information in https://sendgrid.com/docs/API_Reference/Web_API/mail.html @@ -57,7 +57,7 @@ class SendGridHandler extends MailHandler * @param string|string[] $to The recipients of the email * @param string $subject The subject of the mail */ - public function __construct(string $apiUser, string $apiKey, string $from, $to, string $subject, $level = Logger::ERROR, bool $bubble = true) + public function __construct(string $apiUser, string $apiKey, string $from, $to, string $subject, $level = Level::Error, bool $bubble = true) { if (!extension_loaded('curl')) { throw new MissingExtensionException('The curl extension is needed to use the SendGridHandler'); diff --git a/src/Monolog/Handler/Slack/SlackRecord.php b/src/Monolog/Handler/Slack/SlackRecord.php index 7e9e3233a..0a87babf6 100644 --- a/src/Monolog/Handler/Slack/SlackRecord.php +++ b/src/Monolog/Handler/Slack/SlackRecord.php @@ -11,7 +11,7 @@ namespace Monolog\Handler\Slack; -use Monolog\Logger; +use Monolog\Level; use Monolog\Utils; use Monolog\Formatter\NormalizerFormatter; use Monolog\Formatter\FormatterInterface; @@ -145,7 +145,7 @@ public function getSlackData(LogRecord $record): array $attachment = array( 'fallback' => $message, 'text' => $message, - 'color' => $this->getAttachmentColor($recordData['level']), + 'color' => $this->getAttachmentColor($record->level), 'fields' => array(), 'mrkdwn_in' => array('fields'), 'ts' => $recordData['datetime']->getTimestamp(), @@ -201,18 +201,14 @@ public function getSlackData(LogRecord $record): array * Returns a Slack message attachment color associated with * provided level. */ - public function getAttachmentColor(int $level): string + public function getAttachmentColor(Level $level): string { - switch (true) { - case $level >= Logger::ERROR: - return static::COLOR_DANGER; - case $level >= Logger::WARNING: - return static::COLOR_WARNING; - case $level >= Logger::INFO: - return static::COLOR_GOOD; - default: - return static::COLOR_DEFAULT; - } + return match ($level) { + Level::Error, Level::Critical, Level::Alert, Level::Emergency => static::COLOR_DANGER, + Level::Warning => static::COLOR_WARNING, + Level::Info, Level::Notice => static::COLOR_GOOD, + Level::Debug => static::COLOR_DEFAULT + }; } /** diff --git a/src/Monolog/Handler/SlackHandler.php b/src/Monolog/Handler/SlackHandler.php index 4f57daee1..fb85cd014 100644 --- a/src/Monolog/Handler/SlackHandler.php +++ b/src/Monolog/Handler/SlackHandler.php @@ -12,7 +12,7 @@ namespace Monolog\Handler; use Monolog\Formatter\FormatterInterface; -use Monolog\Logger; +use Monolog\Level; use Monolog\Utils; use Monolog\Handler\Slack\SlackRecord; use Monolog\LogRecord; @@ -54,7 +54,7 @@ public function __construct( ?string $username = null, bool $useAttachment = true, ?string $iconEmoji = null, - $level = Logger::CRITICAL, + $level = Level::Critical, bool $bubble = true, bool $useShortAttachment = false, bool $includeContextAndExtra = false, diff --git a/src/Monolog/Handler/SlackWebhookHandler.php b/src/Monolog/Handler/SlackWebhookHandler.php index 269b6995c..c98c1c3d9 100644 --- a/src/Monolog/Handler/SlackWebhookHandler.php +++ b/src/Monolog/Handler/SlackWebhookHandler.php @@ -12,7 +12,7 @@ namespace Monolog\Handler; use Monolog\Formatter\FormatterInterface; -use Monolog\Logger; +use Monolog\Level; use Monolog\Utils; use Monolog\Handler\Slack\SlackRecord; use Monolog\LogRecord; @@ -55,7 +55,7 @@ public function __construct( ?string $iconEmoji = null, bool $useShortAttachment = false, bool $includeContextAndExtra = false, - $level = Logger::CRITICAL, + $level = Level::Critical, bool $bubble = true, array $excludeFields = array() ) { diff --git a/src/Monolog/Handler/SocketHandler.php b/src/Monolog/Handler/SocketHandler.php index 1d8a68f2d..727666c45 100644 --- a/src/Monolog/Handler/SocketHandler.php +++ b/src/Monolog/Handler/SocketHandler.php @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Monolog\LogRecord; /** @@ -58,7 +58,7 @@ class SocketHandler extends AbstractProcessingHandler */ public function __construct( string $connectionString, - $level = Logger::DEBUG, + $level = Level::Debug, bool $bubble = true, bool $persistent = false, float $timeout = 0.0, diff --git a/src/Monolog/Handler/SqsHandler.php b/src/Monolog/Handler/SqsHandler.php index 727c20a8c..fe9e1ecdc 100644 --- a/src/Monolog/Handler/SqsHandler.php +++ b/src/Monolog/Handler/SqsHandler.php @@ -12,7 +12,7 @@ namespace Monolog\Handler; use Aws\Sqs\SqsClient; -use Monolog\Logger; +use Monolog\Level; use Monolog\Utils; use Monolog\LogRecord; @@ -33,7 +33,7 @@ class SqsHandler extends AbstractProcessingHandler /** @var string */ private $queueUrl; - public function __construct(SqsClient $sqsClient, string $queueUrl, $level = Logger::DEBUG, bool $bubble = true) + public function __construct(SqsClient $sqsClient, string $queueUrl, $level = Level::Debug, bool $bubble = true) { parent::__construct($level, $bubble); diff --git a/src/Monolog/Handler/StreamHandler.php b/src/Monolog/Handler/StreamHandler.php index 0053db156..328c4ea65 100644 --- a/src/Monolog/Handler/StreamHandler.php +++ b/src/Monolog/Handler/StreamHandler.php @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Monolog\Utils; use Monolog\LogRecord; @@ -50,7 +50,7 @@ class StreamHandler extends AbstractProcessingHandler * * @throws \InvalidArgumentException If stream is not a resource or string */ - public function __construct($stream, $level = Logger::DEBUG, bool $bubble = true, ?int $filePermission = null, bool $useLocking = false) + public function __construct($stream, $level = Level::Debug, bool $bubble = true, ?int $filePermission = null, bool $useLocking = false) { parent::__construct($level, $bubble); diff --git a/src/Monolog/Handler/SyslogHandler.php b/src/Monolog/Handler/SyslogHandler.php index 77ceaa1d0..73d286811 100644 --- a/src/Monolog/Handler/SyslogHandler.php +++ b/src/Monolog/Handler/SyslogHandler.php @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Monolog\Utils; use Monolog\LogRecord; @@ -40,7 +40,7 @@ class SyslogHandler extends AbstractSyslogHandler * @param string|int $facility Either one of the names of the keys in $this->facilities, or a LOG_* facility constant * @param int $logopts Option flags for the openlog() call, defaults to LOG_PID */ - public function __construct(string $ident, $facility = LOG_USER, $level = Logger::DEBUG, bool $bubble = true, int $logopts = LOG_PID) + public function __construct(string $ident, $facility = LOG_USER, $level = Level::Debug, bool $bubble = true, int $logopts = LOG_PID) { parent::__construct($facility, $level, $bubble); @@ -64,6 +64,6 @@ protected function write(LogRecord $record): void if (!openlog($this->ident, $this->logopts, $this->facility)) { throw new \LogicException('Can\'t open syslog for ident "'.$this->ident.'" and facility "'.$this->facility.'"' . Utils::getRecordMessageForException($record)); } - syslog($this->logLevels[$record->level], (string) $record->formatted); + syslog($this->toSyslogPriority($record->level), (string) $record->formatted); } } diff --git a/src/Monolog/Handler/SyslogUdpHandler.php b/src/Monolog/Handler/SyslogUdpHandler.php index 07feaa567..7fe92b149 100644 --- a/src/Monolog/Handler/SyslogUdpHandler.php +++ b/src/Monolog/Handler/SyslogUdpHandler.php @@ -12,7 +12,7 @@ namespace Monolog\Handler; use DateTimeInterface; -use Monolog\Logger; +use Monolog\Level; use Monolog\Handler\SyslogUdp\UdpSocket; use Monolog\Utils; use Monolog\LogRecord; @@ -54,7 +54,7 @@ class SyslogUdpHandler extends AbstractSyslogHandler * * @phpstan-param self::RFC* $rfc */ - public function __construct(string $host, int $port = 514, $facility = LOG_USER, $level = Logger::DEBUG, bool $bubble = true, string $ident = 'php', int $rfc = self::RFC5424) + public function __construct(string $host, int $port = 514, $facility = LOG_USER, $level = Level::Debug, bool $bubble = true, string $ident = 'php', int $rfc = self::RFC5424) { if (!extension_loaded('sockets')) { throw new MissingExtensionException('The sockets extension is required to use the SyslogUdpHandler'); @@ -72,7 +72,7 @@ protected function write(LogRecord $record): void { $lines = $this->splitMessageIntoLines($record->formatted); - $header = $this->makeCommonSyslogHeader($this->logLevels[$record->level], $record->datetime); + $header = $this->makeCommonSyslogHeader($this->toSyslogPriority($record->level), $record->datetime); foreach ($lines as $line) { $this->socket->write($line, $header); diff --git a/src/Monolog/Handler/TelegramBotHandler.php b/src/Monolog/Handler/TelegramBotHandler.php index e2812c997..0d22455c3 100644 --- a/src/Monolog/Handler/TelegramBotHandler.php +++ b/src/Monolog/Handler/TelegramBotHandler.php @@ -12,7 +12,7 @@ namespace Monolog\Handler; use RuntimeException; -use Monolog\Logger; +use Monolog\Level; use Monolog\Utils; use Monolog\LogRecord; @@ -105,7 +105,7 @@ class TelegramBotHandler extends AbstractProcessingHandler public function __construct( string $apiKey, string $channel, - $level = Logger::DEBUG, + $level = Level::Debug, bool $bubble = true, string $parseMode = null, bool $disableWebPagePreview = null, diff --git a/src/Monolog/Handler/TestHandler.php b/src/Monolog/Handler/TestHandler.php index 2395889e1..531435981 100644 --- a/src/Monolog/Handler/TestHandler.php +++ b/src/Monolog/Handler/TestHandler.php @@ -11,10 +11,11 @@ namespace Monolog\Handler; +use Monolog\Level; +use Monolog\LevelName; use Monolog\Logger; use Psr\Log\LogLevel; use Monolog\LogRecord; -use Monolog\DateTimeImmutable; /** * Used for testing purposes. @@ -67,16 +68,13 @@ * @method bool hasNoticeThatPasses($message) * @method bool hasInfoThatPasses($message) * @method bool hasDebugThatPasses($message) - * - * @phpstan-import-type Level from \Monolog\Logger - * @phpstan-import-type LevelName from \Monolog\Logger */ class TestHandler extends AbstractProcessingHandler { /** @var LogRecord[] */ protected $records = []; - /** @var array */ - protected $recordsByLevel = []; + /** @phpstan-var array, LogRecord[]> */ + protected array $recordsByLevel = []; /** @var bool */ private $skipReset = false; @@ -116,23 +114,21 @@ public function setSkipReset(bool $skipReset) } /** - * @param string|int $level Logging level value or name + * @param int|string|Level|LevelName|LogLevel::* $level Logging level value or name * - * @phpstan-param Level|LevelName|LogLevel::* $level + * @phpstan-param value-of|value-of|Level|LevelName|LogLevel::* $level */ - public function hasRecords($level): bool + public function hasRecords(int|string|Level|LevelName $level): bool { - return isset($this->recordsByLevel[Logger::toMonologLevel($level)]); + return isset($this->recordsByLevel[Logger::toMonologLevel($level)->value]); } /** * @param string|array $recordAssertions 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 * * @phpstan-param array{message: string, context?: mixed[]}|string $recordAssertions - * @phpstan-param Level|LevelName|LogLevel::* $level */ - public function hasRecord(string|array $recordAssertions, $level): bool + public function hasRecord(string|array $recordAssertions, Level $level): bool { if (is_string($recordAssertions)) { $recordAssertions = ['message' => $recordAssertions]; @@ -150,42 +146,28 @@ public function hasRecord(string|array $recordAssertions, $level): bool }, $level); } - /** - * @param string|int $level Logging level value or name - * - * @phpstan-param Level|LevelName|LogLevel::* $level - */ - public function hasRecordThatContains(string $message, $level): bool + public function hasRecordThatContains(string $message, Level $level): bool { return $this->hasRecordThatPasses(fn (LogRecord $rec) => str_contains($rec->message, $message), $level); } - /** - * @param string|int $level Logging level value or name - * - * @phpstan-param Level|LevelName|LogLevel::* $level - */ - public function hasRecordThatMatches(string $regex, $level): bool + public function hasRecordThatMatches(string $regex, Level $level): bool { return $this->hasRecordThatPasses(fn (LogRecord $rec) => preg_match($regex, $rec->message) > 0, $level); } /** - * @param string|int $level Logging level value or name - * @return bool - * * @phpstan-param callable(LogRecord, int): mixed $predicate - * @phpstan-param Level|LevelName|LogLevel::* $level */ - public function hasRecordThatPasses(callable $predicate, $level) + public function hasRecordThatPasses(callable $predicate, Level $level): bool { $level = Logger::toMonologLevel($level); - if (!isset($this->recordsByLevel[$level])) { + if (!isset($this->recordsByLevel[$level->value])) { return false; } - foreach ($this->recordsByLevel[$level] as $i => $rec) { + foreach ($this->recordsByLevel[$level->value] as $i => $rec) { if ($predicate($rec, $i)) { return true; } @@ -199,7 +181,7 @@ public function hasRecordThatPasses(callable $predicate, $level) */ protected function write(LogRecord $record): void { - $this->recordsByLevel[$record->level][] = $record; + $this->recordsByLevel[$record->level->value][] = $record; $this->records[] = $record; } @@ -212,11 +194,10 @@ public function __call($method, $args) { if (preg_match('/(.*)(Debug|Info|Notice|Warning|Error|Critical|Alert|Emergency)(.*)/', $method, $matches) > 0) { $genericMethod = $matches[1] . ('Records' !== $matches[3] ? 'Record' : '') . $matches[3]; - $level = constant('Monolog\Logger::' . strtoupper($matches[2])); + $level = constant(Level::class.'::' . $matches[2]); $callback = [$this, $genericMethod]; if (is_callable($callback)) { $args[] = $level; - return call_user_func_array($callback, $args); } } diff --git a/src/Monolog/Handler/ZendMonitorHandler.php b/src/Monolog/Handler/ZendMonitorHandler.php index b881f4920..32f9c6112 100644 --- a/src/Monolog/Handler/ZendMonitorHandler.php +++ b/src/Monolog/Handler/ZendMonitorHandler.php @@ -13,7 +13,7 @@ use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\NormalizerFormatter; -use Monolog\Logger; +use Monolog\Level; use Monolog\LogRecord; /** @@ -24,47 +24,48 @@ */ class ZendMonitorHandler extends AbstractProcessingHandler { - /** - * Monolog level / ZendMonitor Custom Event priority map - * - * @var array - */ - protected $levelMap = []; - /** * @throws MissingExtensionException */ - public function __construct($level = Logger::DEBUG, bool $bubble = true) + public function __construct($level = Level::Debug, bool $bubble = true) { if (!function_exists('zend_monitor_custom_event')) { throw new MissingExtensionException( 'You must have Zend Server installed with Zend Monitor enabled in order to use this handler' ); } - //zend monitor constants are not defined if zend monitor is not enabled. - $this->levelMap = [ - Logger::DEBUG => \ZEND_MONITOR_EVENT_SEVERITY_INFO, - Logger::INFO => \ZEND_MONITOR_EVENT_SEVERITY_INFO, - Logger::NOTICE => \ZEND_MONITOR_EVENT_SEVERITY_INFO, - Logger::WARNING => \ZEND_MONITOR_EVENT_SEVERITY_WARNING, - Logger::ERROR => \ZEND_MONITOR_EVENT_SEVERITY_ERROR, - Logger::CRITICAL => \ZEND_MONITOR_EVENT_SEVERITY_ERROR, - Logger::ALERT => \ZEND_MONITOR_EVENT_SEVERITY_ERROR, - Logger::EMERGENCY => \ZEND_MONITOR_EVENT_SEVERITY_ERROR, - ]; + parent::__construct($level, $bubble); } + /** + * Translates Monolog log levels to ZendMonitor levels. + */ + protected function toZendMonitorLevel(Level $level): int + { + return match ($level) { + Level::Debug => \ZEND_MONITOR_EVENT_SEVERITY_INFO, + Level::Info => \ZEND_MONITOR_EVENT_SEVERITY_INFO, + Level::Notice => \ZEND_MONITOR_EVENT_SEVERITY_INFO, + Level::Warning => \ZEND_MONITOR_EVENT_SEVERITY_WARNING, + Level::Error => \ZEND_MONITOR_EVENT_SEVERITY_ERROR, + Level::Critical => \ZEND_MONITOR_EVENT_SEVERITY_ERROR, + Level::Alert => \ZEND_MONITOR_EVENT_SEVERITY_ERROR, + Level::Emergency => \ZEND_MONITOR_EVENT_SEVERITY_ERROR, + }; + } + + /** * {@inheritDoc} */ protected function write(LogRecord $record): void { $this->writeZendMonitorCustomEvent( - Logger::getLevelName($record->level), + $record->level->toLevelName()->value, $record->message, $record->formatted, - $this->levelMap[$record->level] + $this->toZendMonitorLevel($record->level) ); } @@ -87,12 +88,4 @@ public function getDefaultFormatter(): FormatterInterface { return new NormalizerFormatter(); } - - /** - * @return array - */ - public function getLevelMap(): array - { - return $this->levelMap; - } } diff --git a/src/Monolog/Level.php b/src/Monolog/Level.php new file mode 100644 index 000000000..70c394862 --- /dev/null +++ b/src/Monolog/Level.php @@ -0,0 +1,127 @@ + self::Debug, + LevelName::Info => self::Info, + LevelName::Notice => self::Notice, + LevelName::Warning => self::Warning, + LevelName::Error => self::Error, + LevelName::Critical => self::Critical, + LevelName::Alert => self::Alert, + LevelName::Emergency => self::Emergency, + }; + } + + /** + * Returns true if the passed $level is higher or equal to $this + */ + public function includes(Level $level): bool + { + return $this->value <= $level->value; + } + + public function isHigherThan(Level $level): bool + { + return $this->value > $level->value; + } + + public function isLowerThan(Level $level): bool + { + return $this->value < $level->value; + } + + public function toLevelName(): LevelName + { + return LevelName::fromLevel($this); + } + + /** + * @return string + * @phpstan-return \Psr\Log\LogLevel::* + */ + public function toPsrLogLevel(): string + { + return match ($this) { + self::Debug => LogLevel::DEBUG, + self::Info => LogLevel::INFO, + self::Notice => LogLevel::NOTICE, + self::Warning => LogLevel::WARNING, + self::Error => LogLevel::ERROR, + self::Critical => LogLevel::CRITICAL, + self::Alert => LogLevel::ALERT, + self::Emergency => LogLevel::EMERGENCY, + }; + } + + public const VALUES = [ + 100, + 200, + 250, + 300, + 400, + 500, + 550, + 600, + ]; +} diff --git a/src/Monolog/LevelName.php b/src/Monolog/LevelName.php new file mode 100644 index 000000000..7d26d9f18 --- /dev/null +++ b/src/Monolog/LevelName.php @@ -0,0 +1,53 @@ + self::Debug, + Level::Info => self::Info, + Level::Notice => self::Notice, + Level::Warning => self::Warning, + Level::Error => self::Error, + Level::Critical => self::Critical, + Level::Alert => self::Alert, + Level::Emergency => self::Emergency, + }; + } + + public function toLevel(): Level + { + return Level::fromLevelName($this); + } + + public const VALUES = [ + 'DEBUG', + 'INFO', + 'NOTICE', + 'WARNING', + 'ERROR', + 'CRITICAL', + 'ALERT', + 'EMERGENCY', + ]; + + public function jsonSerialize(): mixed + { + return $this->value; + } +} diff --git a/src/Monolog/LogRecord.php b/src/Monolog/LogRecord.php index 1e6aa07ae..47fc66c73 100644 --- a/src/Monolog/LogRecord.php +++ b/src/Monolog/LogRecord.php @@ -17,25 +17,21 @@ * Monolog log record * * @author Jordi Boggiano - * @template-implements \ArrayAccess<'message'|'level'|'context'|'level_name'|'channel'|'datetime'|'extra', int|string|\DateTimeImmutable|array> - * @phpstan-import-type Level from Logger - * @phpstan-import-type LevelName from Logger + * @template-implements ArrayAccess<'message'|'level'|'context'|'level_name'|'channel'|'datetime'|'extra', int|string|\DateTimeImmutable|array> */ -class LogRecord implements \ArrayAccess +class LogRecord implements ArrayAccess { private const MODIFIABLE_FIELDS = [ 'extra' => true, 'formatted' => true, ]; - /** @var 'DEBUG'|'INFO'|'NOTICE'|'WARNING'|'ERROR'|'CRITICAL'|'ALERT'|'EMERGENCY' */ - public readonly string $levelName; // TODO enum? + public readonly LevelName $levelName; public function __construct( public readonly \DateTimeImmutable $datetime, public readonly string $channel, - /** @var Logger::DEBUG|Logger::INFO|Logger::NOTICE|Logger::WARNING|Logger::ERROR|Logger::CRITICAL|Logger::ALERT|Logger::EMERGENCY */ - public readonly int $level, // TODO enum? + public readonly Level $level, public readonly string $message, /** @var array */ public readonly array $context = [], @@ -43,7 +39,7 @@ public function __construct( public array $extra = [], public mixed $formatted = null, ) { - $this->levelName = Logger::getLevelName($level); + $this->levelName = LevelName::fromLevel($level); } public function offsetSet(mixed $offset, mixed $value): void @@ -81,8 +77,15 @@ public function offsetUnset(mixed $offset): void public function &offsetGet(mixed $offset): mixed { - if ($offset === 'level_name') { - $offset = 'levelName'; + if ($offset === 'level_name' || $offset === 'level') { + if ($offset === 'level_name') { + $offset = 'levelName'; + } + + // avoid returning readonly props by ref as this is illegal + $copy = $this->{$offset}->value; + + return $copy; } if (isset(self::MODIFIABLE_FIELDS[$offset])) { @@ -96,15 +99,15 @@ public function &offsetGet(mixed $offset): mixed } /** - * @phpstan-return array{message: string, context: mixed[], level: Level, level_name: LevelName, channel: string, datetime: \DateTimeImmutable, extra: mixed[]} + * @phpstan-return array{message: string, context: mixed[], level: value-of, level_name: value-of, channel: string, datetime: \DateTimeImmutable, extra: mixed[]} */ public function toArray(): array { return [ 'message' => $this->message, 'context' => $this->context, - 'level' => $this->level, - 'level_name' => $this->levelName, + 'level' => $this->level->value, + 'level_name' => $this->levelName->value, 'channel' => $this->channel, 'datetime' => $this->datetime, 'extra' => $this->extra, diff --git a/src/Monolog/Logger.php b/src/Monolog/Logger.php index 882438448..bf985d2c6 100644 --- a/src/Monolog/Logger.php +++ b/src/Monolog/Logger.php @@ -27,14 +27,13 @@ * and uses them to store records that are added to it. * * @author Jordi Boggiano - * - * @phpstan-type Level Logger::DEBUG|Logger::INFO|Logger::NOTICE|Logger::WARNING|Logger::ERROR|Logger::CRITICAL|Logger::ALERT|Logger::EMERGENCY - * @phpstan-type LevelName 'DEBUG'|'INFO'|'NOTICE'|'WARNING'|'ERROR'|'CRITICAL'|'ALERT'|'EMERGENCY' */ class Logger implements LoggerInterface, ResettableInterface { /** * Detailed debug information + * + * @deprecated Use \Monolog\Level::Debug */ public const DEBUG = 100; @@ -42,11 +41,15 @@ class Logger implements LoggerInterface, ResettableInterface * Interesting events * * Examples: User logs in, SQL logs. + * + * @deprecated Use \Monolog\Level::Info */ public const INFO = 200; /** * Uncommon events + * + * @deprecated Use \Monolog\Level::Notice */ public const NOTICE = 250; @@ -55,11 +58,15 @@ class Logger implements LoggerInterface, ResettableInterface * * Examples: Use of deprecated APIs, poor use of an API, * undesirable things that are not necessarily wrong. + * + * @deprecated Use \Monolog\Level::Warning */ public const WARNING = 300; /** * Runtime errors + * + * @deprecated Use \Monolog\Level::Error */ public const ERROR = 400; @@ -67,6 +74,8 @@ class Logger implements LoggerInterface, ResettableInterface * Critical conditions * * Example: Application component unavailable, unexpected exception. + * + * @deprecated Use \Monolog\Level::Critical */ public const CRITICAL = 500; @@ -75,11 +84,15 @@ class Logger implements LoggerInterface, ResettableInterface * * Example: Entire website down, database unavailable, etc. * This should trigger the SMS alerts and wake you up. + * + * @deprecated Use \Monolog\Level::Alert */ public const ALERT = 550; /** * Urgent alert. + * + * @deprecated Use \Monolog\Level::Emergency */ public const EMERGENCY = 600; @@ -91,25 +104,7 @@ class Logger implements LoggerInterface, ResettableInterface * * @var int */ - public const API = 2; - - /** - * This is a static variable and not a constant to serve as an extension point for custom levels - * - * @var array $levels Logging levels with the levels as key - * - * @phpstan-var array $levels Logging levels with the levels as key - */ - protected static $levels = [ - self::DEBUG => 'DEBUG', - self::INFO => 'INFO', - self::NOTICE => 'NOTICE', - self::WARNING => 'WARNING', - self::ERROR => 'ERROR', - self::CRITICAL => 'CRITICAL', - self::ALERT => 'ALERT', - self::EMERGENCY => 'EMERGENCY', - ]; + public const API = 3; /** * @var string @@ -287,16 +282,16 @@ public function useMicrosecondTimestamps(bool $micro): self * @param mixed[] $context The log context * @return bool Whether the record has been processed * - * @phpstan-param Level $level + * @phpstan-param value-of|Level $level */ - public function addRecord(int $level, string $message, array $context = []): bool + public function addRecord(int|Level $level, string $message, array $context = []): bool { $recordInitialized = count($this->processors) === 0; $record = new LogRecord( message: $message, context: $context, - level: $level, + level: self::toMonologLevel($level), channel: $this->name, datetime: new DateTimeImmutable($this->microsecondTimestamps, $this->timezone), extra: [], @@ -381,78 +376,63 @@ public function reset(): void } /** - * Gets all supported logging levels. - * - * @return array Assoc array with human-readable level names => level codes. - * @phpstan-return array - */ - public static function getLevels(): array - { - return array_flip(static::$levels); - } - - /** - * Gets the name of the logging level. + * Converts PSR-3 levels to Monolog ones if necessary * + * @param int|string|Level|LevelName|LogLevel::* $level Level number (monolog) or name (PSR-3) * @throws \Psr\Log\InvalidArgumentException If level is not defined * - * @phpstan-param Level $level - * @phpstan-return LevelName + * @phpstan-param value-of|value-of|Level|LevelName|LogLevel::* $level */ - public static function getLevelName(int $level): string + public static function toMonologLevel(string|int|Level|LevelName $level): Level { - if (!isset(static::$levels[$level])) { - throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', array_keys(static::$levels))); + if ($level instanceof Level) { + return $level; } - return static::$levels[$level]; - } + if ($level instanceof LevelName) { + return $level->toLevel(); + } - /** - * Converts PSR-3 levels to Monolog ones if necessary - * - * @param string|int $level Level number (monolog) or name (PSR-3) - * @throws \Psr\Log\InvalidArgumentException If level is not defined - * - * @phpstan-param Level|LevelName|LogLevel::* $level - * @phpstan-return Level - */ - public static function toMonologLevel($level): int - { - if (is_string($level)) { - if (is_numeric($level)) { - return intval($level); + if (\is_string($level)) { + if (\is_numeric($level)) { + $levelEnum = Level::tryFrom((int) $level); + if ($levelEnum === null) { + throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', LevelName::VALUES + Level::VALUES)); + } + + return $levelEnum; } - // Contains chars of all log levels and avoids using strtoupper() which may have + // Contains first char of all log levels and avoids using strtoupper() which may have // strange results depending on locale (for example, "i" will become "İ" in Turkish locale) - $upper = strtr($level, 'abcdefgilmnortuwy', 'ABCDEFGILMNORTUWY'); - if (defined(__CLASS__.'::'.$upper)) { - return constant(__CLASS__ . '::' . $upper); + $upper = strtr(substr($level, 0, 1), 'dinweca', 'DINWECA') . strtolower(substr($level, 1)); + if (defined(Level::class.'::'.$upper)) { + return constant(Level::class . '::' . $upper); } - throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', array_keys(static::$levels) + static::$levels)); + throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', LevelName::VALUES + Level::VALUES)); } - if (!is_int($level)) { - throw new InvalidArgumentException('Level "'.var_export($level, true).'" is not defined, use one of: '.implode(', ', array_keys(static::$levels) + static::$levels)); + $levelEnum = Level::tryFrom($level); + if ($levelEnum === null) { + throw new InvalidArgumentException('Level "'.var_export($level, true).'" is not defined, use one of: '.implode(', ', LevelName::VALUES + Level::VALUES)); } - return $level; + return $levelEnum; } /** * Checks whether the Logger has a handler that listens on the given level * - * @phpstan-param Level $level + * @phpstan-param value-of|value-of|Level|LevelName|LogLevel::* $level */ - public function isHandling(int $level): bool + public function isHandling(int|string|LevelName|Level $level): bool { $record = new LogRecord( datetime: new DateTimeImmutable($this->microsecondTimestamps, $this->timezone), channel: $this->name, message: '', - level: $level, + level: self::toMonologLevel($level), ); foreach ($this->handlers as $handler) { @@ -494,8 +474,8 @@ public function getExceptionHandler(): ?callable */ public function log($level, string|\Stringable $message, array $context = []): void { - if (!is_int($level) && !is_string($level)) { - throw new \InvalidArgumentException('$level is expected to be a string or int'); + if (!is_string($level) && !is_int($level) && !$level instanceof Level) { + throw new \InvalidArgumentException('$level is expected to be a string, int or '.Level::class.' instance'); } $level = static::toMonologLevel($level); diff --git a/src/Monolog/Processor/GitProcessor.php b/src/Monolog/Processor/GitProcessor.php index 920cbc3f4..2cefe4521 100644 --- a/src/Monolog/Processor/GitProcessor.php +++ b/src/Monolog/Processor/GitProcessor.php @@ -11,6 +11,8 @@ namespace Monolog\Processor; +use Monolog\Level; +use Monolog\LevelName; use Monolog\Logger; use Psr\Log\LogLevel; use Monolog\LogRecord; @@ -20,23 +22,19 @@ * * @author Nick Otter * @author Jordi Boggiano - * - * @phpstan-import-type Level from \Monolog\Logger - * @phpstan-import-type LevelName from \Monolog\Logger */ class GitProcessor implements ProcessorInterface { - /** @var int */ - private $level; + private Level $level; /** @var array{branch: string, commit: string}|array|null */ private static $cache = null; /** - * @param string|int $level The minimum logging level at which this Processor will be triggered + * @param int|string|Level|LevelName|LogLevel::* $level The minimum logging level at which this Processor will be triggered * - * @phpstan-param Level|LevelName|LogLevel::* $level + * @phpstan-param value-of|value-of|Level|LevelName|LogLevel::* $level */ - public function __construct($level = Logger::DEBUG) + public function __construct(int|string|Level|LevelName $level = Level::Debug) { $this->level = Logger::toMonologLevel($level); } diff --git a/src/Monolog/Processor/IntrospectionProcessor.php b/src/Monolog/Processor/IntrospectionProcessor.php index 2cbc83b47..357bd71fe 100644 --- a/src/Monolog/Processor/IntrospectionProcessor.php +++ b/src/Monolog/Processor/IntrospectionProcessor.php @@ -11,6 +11,8 @@ namespace Monolog\Processor; +use Monolog\Level; +use Monolog\LevelName; use Monolog\Logger; use Psr\Log\LogLevel; use Monolog\LogRecord; @@ -25,13 +27,10 @@ * triggered the FingersCrossedHandler. * * @author Jordi Boggiano - * - * @phpstan-import-type Level from \Monolog\Logger - * @phpstan-import-type LevelName from \Monolog\Logger */ class IntrospectionProcessor implements ProcessorInterface { - private int $level; + private Level $level; /** @var string[] */ private array $skipClassesPartials; @@ -44,12 +43,12 @@ class IntrospectionProcessor implements ProcessorInterface ]; /** - * @param string|int $level The minimum logging level at which this Processor will be triggered + * @param string|int|Level|LevelName $level The minimum logging level at which this Processor will be triggered * @param string[] $skipClassesPartials * - * @phpstan-param Level|LevelName|LogLevel::* $level + * @phpstan-param value-of|value-of|Level|LevelName|LogLevel::* $level */ - public function __construct($level = Logger::DEBUG, array $skipClassesPartials = [], int $skipStackFramesCount = 0) + public function __construct(int|string|Level|LevelName $level = Level::Debug, array $skipClassesPartials = [], int $skipStackFramesCount = 0) { $this->level = Logger::toMonologLevel($level); $this->skipClassesPartials = array_merge(['Monolog\\'], $skipClassesPartials); @@ -62,7 +61,7 @@ public function __construct($level = Logger::DEBUG, array $skipClassesPartials = public function __invoke(LogRecord $record): LogRecord { // return if the level is not high enough - if ($record->level < $this->level) { + if ($record->level->isLowerThan($this->level)) { return $record; } diff --git a/src/Monolog/Processor/MercurialProcessor.php b/src/Monolog/Processor/MercurialProcessor.php index 7fb1340dd..37222a344 100644 --- a/src/Monolog/Processor/MercurialProcessor.php +++ b/src/Monolog/Processor/MercurialProcessor.php @@ -11,6 +11,8 @@ namespace Monolog\Processor; +use Monolog\Level; +use Monolog\LevelName; use Monolog\Logger; use Psr\Log\LogLevel; use Monolog\LogRecord; @@ -19,23 +21,19 @@ * Injects Hg branch and Hg revision number in all records * * @author Jonathan A. Schweder - * - * @phpstan-import-type LevelName from \Monolog\Logger - * @phpstan-import-type Level from \Monolog\Logger */ class MercurialProcessor implements ProcessorInterface { - /** @var Level */ - private $level; + private Level $level; /** @var array{branch: string, revision: string}|array|null */ private static $cache = null; /** - * @param int|string $level The minimum logging level at which this Processor will be triggered + * @param int|string|Level|LevelName $level The minimum logging level at which this Processor will be triggered * - * @phpstan-param Level|LevelName|LogLevel::* $level + * @phpstan-param value-of|value-of|Level|LevelName|LogLevel::* $level */ - public function __construct($level = Logger::DEBUG) + public function __construct(int|string|Level|LevelName $level = Level::Debug) { $this->level = Logger::toMonologLevel($level); } @@ -46,7 +44,7 @@ public function __construct($level = Logger::DEBUG) public function __invoke(LogRecord $record): LogRecord { // return if the level is not high enough - if ($record->level < $this->level) { + if ($record->level->isLowerThan($this->level)) { return $record; } diff --git a/src/Monolog/SignalHandler.php b/src/Monolog/SignalHandler.php index d730eea3a..b9f92abd2 100644 --- a/src/Monolog/SignalHandler.php +++ b/src/Monolog/SignalHandler.php @@ -19,9 +19,6 @@ * Monolog POSIX signal handler * * @author Robert Gust-Bardon - * - * @phpstan-import-type Level from \Monolog\Logger - * @phpstan-import-type LevelName from \Monolog\Logger */ class SignalHandler { @@ -30,7 +27,7 @@ class SignalHandler /** @var array SIG_DFL, SIG_IGN or previous callable */ private $previousSignalHandler = []; - /** @var array */ + /** @var array */ private $signalLevelMap = []; /** @var array */ private $signalRestartSyscalls = []; @@ -41,21 +38,21 @@ public function __construct(LoggerInterface $logger) } /** - * @param int|string $level Level or level name + * @param int|string|Level|LevelName $level Level or level name * @param bool $callPrevious * @param bool $restartSyscalls * @param bool|null $async * @return $this * - * @phpstan-param Level|LevelName|LogLevel::* $level + * @phpstan-param value-of|value-of|Level|LevelName|LogLevel::* $level */ - public function registerSignalHandler(int $signo, $level = LogLevel::CRITICAL, bool $callPrevious = true, bool $restartSyscalls = true, ?bool $async = true): self + public function registerSignalHandler(int $signo, int|string|Level|LevelName $level = LogLevel::CRITICAL, bool $callPrevious = true, bool $restartSyscalls = true, ?bool $async = true): self { if (!extension_loaded('pcntl') || !function_exists('pcntl_signal')) { return $this; } - $level = Logger::toMonologLevel($level); + $level = Logger::toMonologLevel($level)->toPsrLogLevel(); if ($callPrevious) { $handler = pcntl_signal_get_handler($signo); diff --git a/src/Monolog/Test/TestCase.php b/src/Monolog/Test/TestCase.php index 839816367..aa7144882 100644 --- a/src/Monolog/Test/TestCase.php +++ b/src/Monolog/Test/TestCase.php @@ -11,17 +11,18 @@ namespace Monolog\Test; +use Monolog\Level; +use Monolog\LevelName; use Monolog\Logger; use Monolog\LogRecord; use Monolog\DateTimeImmutable; use Monolog\Formatter\FormatterInterface; +use Psr\Log\LogLevel; /** * Lets you easily generate log records and a dummy formatter for testing purposes * * @author Jordi Boggiano - * - * @phpstan-import-type Level from \Monolog\Logger */ class TestCase extends \PHPUnit\Framework\TestCase { @@ -29,14 +30,14 @@ class TestCase extends \PHPUnit\Framework\TestCase * @param array $context * @param array $extra * - * @phpstan-param Level $level + * @phpstan-param value-of|value-of|Level|LevelName|LogLevel::* $level */ - protected function getRecord(int $level = Logger::WARNING, string|\Stringable $message = 'test', array $context = [], string $channel = 'test', \DateTimeImmutable $datetime = new DateTimeImmutable(true), array $extra = []): LogRecord + protected function getRecord(int|string|LevelName|Level $level = Level::Warning, string|\Stringable $message = 'test', array $context = [], string $channel = 'test', \DateTimeImmutable $datetime = new DateTimeImmutable(true), array $extra = []): LogRecord { return new LogRecord( message: (string) $message, context: $context, - level: $level, + level: Logger::toMonologLevel($level), channel: $channel, datetime: $datetime, extra: $extra, @@ -49,11 +50,11 @@ protected function getRecord(int $level = Logger::WARNING, string|\Stringable $m protected function getMultipleRecords(): array { return [ - $this->getRecord(Logger::DEBUG, 'debug message 1'), - $this->getRecord(Logger::DEBUG, 'debug message 2'), - $this->getRecord(Logger::INFO, 'information'), - $this->getRecord(Logger::WARNING, 'warning'), - $this->getRecord(Logger::ERROR, 'error'), + $this->getRecord(Level::Debug, 'debug message 1'), + $this->getRecord(Level::Debug, 'debug message 2'), + $this->getRecord(Level::Info, 'information'), + $this->getRecord(Level::Warning, 'warning'), + $this->getRecord(Level::Error, 'error'), ]; } diff --git a/tests/Monolog/ErrorHandlerTest.php b/tests/Monolog/ErrorHandlerTest.php index 05123f2af..bc637efdf 100644 --- a/tests/Monolog/ErrorHandlerTest.php +++ b/tests/Monolog/ErrorHandlerTest.php @@ -37,7 +37,7 @@ public function testHandleError() $this->assertTrue(is_callable($prop)); $this->assertSame($prevHandler, $prop); - $resHandler = $errHandler->registerErrorHandler([E_USER_NOTICE => Logger::EMERGENCY], false); + $resHandler = $errHandler->registerErrorHandler([E_USER_NOTICE => LogLevel::EMERGENCY], false); $this->assertSame($errHandler, $resHandler); trigger_error('Foo', E_USER_ERROR); $this->assertCount(1, $handler->getRecords()); diff --git a/tests/Monolog/Formatter/ChromePHPFormatterTest.php b/tests/Monolog/Formatter/ChromePHPFormatterTest.php index cdfcae254..f290ba699 100644 --- a/tests/Monolog/Formatter/ChromePHPFormatterTest.php +++ b/tests/Monolog/Formatter/ChromePHPFormatterTest.php @@ -11,7 +11,7 @@ namespace Monolog\Formatter; -use Monolog\Logger; +use Monolog\Level; use Monolog\Test\TestCase; class ChromePHPFormatterTest extends TestCase @@ -23,7 +23,7 @@ public function testDefaultFormat() { $formatter = new ChromePHPFormatter(); $record = $this->getRecord( - Logger::ERROR, + Level::Error, 'log', channel: 'meh', context: ['from' => 'logger'], @@ -55,7 +55,7 @@ public function testFormatWithFileAndLine() { $formatter = new ChromePHPFormatter(); $record = $this->getRecord( - Logger::CRITICAL, + Level::Critical, 'log', channel: 'meh', context: ['from' => 'logger'], @@ -87,7 +87,7 @@ public function testFormatWithoutContext() { $formatter = new ChromePHPFormatter(); $record = $this->getRecord( - Logger::DEBUG, + Level::Debug, 'log', channel: 'meh', datetime: new \DateTimeImmutable("@0"), @@ -114,13 +114,13 @@ public function testBatchFormatThrowException() $formatter = new ChromePHPFormatter(); $records = [ $this->getRecord( - Logger::INFO, + Level::Info, 'log', channel: 'meh', datetime: new \DateTimeImmutable("@0"), ), $this->getRecord( - Logger::WARNING, + Level::Warning, 'log2', channel: 'foo', datetime: new \DateTimeImmutable("@0"), diff --git a/tests/Monolog/Formatter/ElasticaFormatterTest.php b/tests/Monolog/Formatter/ElasticaFormatterTest.php index 17d29382d..64b642861 100644 --- a/tests/Monolog/Formatter/ElasticaFormatterTest.php +++ b/tests/Monolog/Formatter/ElasticaFormatterTest.php @@ -11,7 +11,7 @@ namespace Monolog\Formatter; -use Monolog\Logger; +use Monolog\Level; use Monolog\LogRecord; use Monolog\Test\TestCase; @@ -33,7 +33,7 @@ public function testFormat() { // test log message $msg = $this->getRecord( - Logger::ERROR, + Level::Error, 'log', channel: 'meh', context: ['foo' => 7, 'bar', 'class' => new \stdClass], diff --git a/tests/Monolog/Formatter/ElasticsearchFormatterTest.php b/tests/Monolog/Formatter/ElasticsearchFormatterTest.php index 2dc89be6c..438bbfd39 100644 --- a/tests/Monolog/Formatter/ElasticsearchFormatterTest.php +++ b/tests/Monolog/Formatter/ElasticsearchFormatterTest.php @@ -11,7 +11,7 @@ namespace Monolog\Formatter; -use Monolog\Logger; +use Monolog\Level; use Monolog\Test\TestCase; class ElasticsearchFormatterTest extends TestCase @@ -25,7 +25,7 @@ public function testFormat() { // Test log message $msg = $this->getRecord( - Logger::ERROR, + Level::Error, 'log', channel: 'meh', context: ['foo' => 7, 'bar', 'class' => new \stdClass], diff --git a/tests/Monolog/Formatter/FlowdockFormatterTest.php b/tests/Monolog/Formatter/FlowdockFormatterTest.php index 322e6ed39..1b4e81768 100644 --- a/tests/Monolog/Formatter/FlowdockFormatterTest.php +++ b/tests/Monolog/Formatter/FlowdockFormatterTest.php @@ -11,7 +11,7 @@ namespace Monolog\Formatter; -use Monolog\Logger; +use Monolog\Level; use Monolog\Test\TestCase; class FlowdockFormatterTest extends TestCase @@ -44,8 +44,8 @@ public function testFormatBatch() { $formatter = new FlowdockFormatter('test_source', 'source@test.com'); $records = [ - $this->getRecord(Logger::WARNING), - $this->getRecord(Logger::DEBUG), + $this->getRecord(Level::Warning), + $this->getRecord(Level::Debug), ]; $formatted = $formatter->formatBatch($records); diff --git a/tests/Monolog/Formatter/FluentdFormatterTest.php b/tests/Monolog/Formatter/FluentdFormatterTest.php index dbebd787c..318a5ca04 100644 --- a/tests/Monolog/Formatter/FluentdFormatterTest.php +++ b/tests/Monolog/Formatter/FluentdFormatterTest.php @@ -11,7 +11,7 @@ namespace Monolog\Formatter; -use Monolog\Logger; +use Monolog\Level; use Monolog\Test\TestCase; class FluentdFormatterTest extends TestCase @@ -35,7 +35,7 @@ public function testConstruct() */ public function testFormat() { - $record = $this->getRecord(Logger::WARNING, datetime: new \DateTimeImmutable("@0")); + $record = $this->getRecord(Level::Warning, datetime: new \DateTimeImmutable("@0")); $formatter = new FluentdFormatter(); $this->assertEquals( @@ -49,7 +49,7 @@ public function testFormat() */ public function testFormatWithTag() { - $record = $this->getRecord(Logger::ERROR, datetime: new \DateTimeImmutable("@0")); + $record = $this->getRecord(Level::Error, datetime: new \DateTimeImmutable("@0")); $formatter = new FluentdFormatter(true); $this->assertEquals( diff --git a/tests/Monolog/Formatter/GelfMessageFormatterTest.php b/tests/Monolog/Formatter/GelfMessageFormatterTest.php index fd1adb7df..b33687a68 100644 --- a/tests/Monolog/Formatter/GelfMessageFormatterTest.php +++ b/tests/Monolog/Formatter/GelfMessageFormatterTest.php @@ -11,7 +11,7 @@ namespace Monolog\Formatter; -use Monolog\Logger; +use Monolog\Level; use Monolog\Test\TestCase; class GelfMessageFormatterTest extends TestCase @@ -30,7 +30,7 @@ public function testDefaultFormatter() { $formatter = new GelfMessageFormatter(); $record = $this->getRecord( - Logger::ERROR, + Level::Error, 'log', channel: 'meh', datetime: new \DateTimeImmutable("@0"), @@ -62,7 +62,7 @@ public function testFormatWithFileAndLine() { $formatter = new GelfMessageFormatter(); $record = $this->getRecord( - Logger::ERROR, + Level::Error, 'log', channel: 'meh', context: ['from' => 'logger'], @@ -84,7 +84,7 @@ public function testFormatWithContext() { $formatter = new GelfMessageFormatter(); $record = $this->getRecord( - Logger::ERROR, + Level::Error, 'log', channel: 'meh', context: ['from' => 'logger'], @@ -120,7 +120,7 @@ public function testFormatWithContextContainingException() { $formatter = new GelfMessageFormatter(); $record = $this->getRecord( - Logger::ERROR, + Level::Error, 'log', channel: 'meh', context: ['from' => 'logger', 'exception' => [ @@ -146,7 +146,7 @@ public function testFormatWithExtra() { $formatter = new GelfMessageFormatter(); $record = $this->getRecord( - Logger::ERROR, + Level::Error, 'log', channel: 'meh', context: ['from' => 'logger'], @@ -179,7 +179,7 @@ public function testFormatWithLargeData() { $formatter = new GelfMessageFormatter(); $record = $this->getRecord( - Logger::ERROR, + Level::Error, 'log', channel: 'meh', context: ['exception' => str_repeat(' ', 32767)], @@ -205,7 +205,7 @@ public function testFormatWithUnlimitedLength() { $formatter = new GelfMessageFormatter('LONG_SYSTEM_NAME', null, 'ctxt_', PHP_INT_MAX); $record = $this->getRecord( - Logger::ERROR, + Level::Error, 'log', channel: 'meh', context: ['exception' => str_repeat(' ', 32767 * 2)], @@ -231,7 +231,7 @@ public function testFormatWithLargeCyrillicData() { $formatter = new GelfMessageFormatter(); $record = $this->getRecord( - Logger::ERROR, + Level::Error, str_repeat('в', 32767), channel: 'meh', context: ['exception' => str_repeat('а', 32767)], diff --git a/tests/Monolog/Formatter/JsonFormatterTest.php b/tests/Monolog/Formatter/JsonFormatterTest.php index 38fd66c83..cab71f936 100644 --- a/tests/Monolog/Formatter/JsonFormatterTest.php +++ b/tests/Monolog/Formatter/JsonFormatterTest.php @@ -11,7 +11,7 @@ namespace Monolog\Formatter; -use Monolog\Logger; +use Monolog\Level; use Monolog\LogRecord; use Monolog\Test\TestCase; @@ -85,8 +85,8 @@ public function testFormatBatch() { $formatter = new JsonFormatter(); $records = [ - $this->getRecord(Logger::WARNING), - $this->getRecord(Logger::DEBUG), + $this->getRecord(Level::Warning), + $this->getRecord(Level::Debug), ]; $this->assertEquals(json_encode($records), $formatter->formatBatch($records)); } @@ -99,8 +99,8 @@ public function testFormatBatchNewlines() { $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_NEWLINES); $records = [ - $this->getRecord(Logger::WARNING), - $this->getRecord(Logger::DEBUG), + $this->getRecord(Level::Warning), + $this->getRecord(Level::Debug), ]; $expected = array_map(fn (LogRecord $record) => json_encode($record->toArray(), JSON_FORCE_OBJECT), $records); $this->assertEquals(implode("\n", $expected), $formatter->formatBatch($records)); @@ -213,7 +213,7 @@ private function assertContextContainsFormattedException($expected, $actual) private function formatRecordWithExceptionInContext(JsonFormatter $formatter, \Throwable $exception) { $message = $formatter->format($this->getRecord( - Logger::CRITICAL, + Level::Critical, 'foobar', channel: 'core', context: ['exception' => $exception], @@ -262,7 +262,7 @@ public function testNormalizeHandleLargeArraysWithExactly1000Items() $largeArray = range(1, 1000); $res = $formatter->format($this->getRecord( - Logger::CRITICAL, + Level::Critical, 'bar', channel: 'test', context: array($largeArray), @@ -278,7 +278,7 @@ public function testNormalizeHandleLargeArrays() $largeArray = range(1, 2000); $res = $formatter->format($this->getRecord( - Logger::CRITICAL, + Level::Critical, 'bar', channel: 'test', context: array($largeArray), @@ -293,7 +293,7 @@ public function testEmptyContextAndExtraFieldsCanBeIgnored() $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, true, true); $record = $formatter->format($this->getRecord( - Logger::DEBUG, + Level::Debug, 'Testing', channel: 'test', datetime: new \DateTimeImmutable('2022-02-22 00:00:00'), diff --git a/tests/Monolog/Formatter/LineFormatterTest.php b/tests/Monolog/Formatter/LineFormatterTest.php index f3128a772..0cc5d246f 100644 --- a/tests/Monolog/Formatter/LineFormatterTest.php +++ b/tests/Monolog/Formatter/LineFormatterTest.php @@ -12,7 +12,7 @@ namespace Monolog\Formatter; use Monolog\Test\TestCase; -use Monolog\Logger; +use Monolog\Level; /** * @covers Monolog\Formatter\LineFormatter @@ -23,7 +23,7 @@ public function testDefFormatWithString() { $formatter = new LineFormatter(null, 'Y-m-d'); $message = $formatter->format($this->getRecord( - Logger::WARNING, + Level::Warning, 'foo', channel: 'log', )); @@ -34,7 +34,7 @@ public function testDefFormatWithArrayContext() { $formatter = new LineFormatter(null, 'Y-m-d'); $message = $formatter->format($this->getRecord( - Logger::ERROR, + Level::Error, 'foo', channel: 'meh', context: [ @@ -51,7 +51,7 @@ public function testDefFormatExtras() { $formatter = new LineFormatter(null, 'Y-m-d'); $message = $formatter->format($this->getRecord( - Logger::ERROR, + Level::Error, 'log', channel: 'meh', extra: ['ip' => '127.0.0.1'], @@ -63,7 +63,7 @@ public function testFormatExtras() { $formatter = new LineFormatter("[%datetime%] %channel%.%level_name%: %message% %context% %extra.file% %extra%\n", 'Y-m-d'); $message = $formatter->format($this->getRecord( - Logger::ERROR, + Level::Error, 'log', channel: 'meh', extra: ['ip' => '127.0.0.1', 'file' => 'test'], @@ -75,7 +75,7 @@ public function testContextAndExtraOptionallyNotShownIfEmpty() { $formatter = new LineFormatter(null, 'Y-m-d', false, true); $message = $formatter->format($this->getRecord( - Logger::ERROR, + Level::Error, 'log', channel: 'meh', )); @@ -86,7 +86,7 @@ public function testContextAndExtraReplacement() { $formatter = new LineFormatter('%context.foo% => %extra.foo%'); $message = $formatter->format($this->getRecord( - Logger::ERROR, + Level::Error, 'log', channel: 'meh', context: ['foo' => 'bar'], @@ -100,7 +100,7 @@ public function testDefFormatWithObject() { $formatter = new LineFormatter(null, 'Y-m-d'); $message = $formatter->format($this->getRecord( - Logger::ERROR, + Level::Error, 'foobar', channel: 'meh', context: [], @@ -114,7 +114,7 @@ public function testDefFormatWithException() { $formatter = new LineFormatter(null, 'Y-m-d'); $message = $formatter->format($this->getRecord( - Logger::CRITICAL, + Level::Critical, 'foobar', channel: 'core', context: ['exception' => new \RuntimeException('Foo')], @@ -130,7 +130,7 @@ public function testDefFormatWithExceptionAndStacktrace() $formatter = new LineFormatter(null, 'Y-m-d'); $formatter->includeStacktraces(); $message = $formatter->format($this->getRecord( - Logger::CRITICAL, + Level::Critical, 'foobar', channel: 'core', context: ['exception' => new \RuntimeException('Foo')], @@ -146,7 +146,7 @@ public function testDefFormatWithPreviousException() $formatter = new LineFormatter(null, 'Y-m-d'); $previous = new \LogicException('Wut?'); $message = $formatter->format($this->getRecord( - Logger::CRITICAL, + Level::Critical, 'foobar', channel: 'core', context: ['exception' => new \RuntimeException('Foo', 0, $previous)], @@ -165,7 +165,7 @@ public function testDefFormatWithSoapFaultException() $formatter = new LineFormatter(null, 'Y-m-d'); $message = $formatter->format($this->getRecord( - Logger::CRITICAL, + Level::Critical, 'foobar', channel: 'core', context: ['exception' => new \SoapFault('foo', 'bar', 'hello', 'world')], @@ -176,7 +176,7 @@ public function testDefFormatWithSoapFaultException() $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($this->getRecord( - Logger::CRITICAL, + Level::Critical, 'foobar', channel: 'core', context: ['exception' => new \SoapFault('foo', 'bar', 'hello', (object) ['bar' => (object) ['biz' => 'baz'], 'foo' => 'world'])], @@ -192,12 +192,12 @@ public function testBatchFormat() $formatter = new LineFormatter(null, 'Y-m-d'); $message = $formatter->formatBatch([ $this->getRecord( - Logger::CRITICAL, + Level::Critical, 'bar', channel: 'test', ), $this->getRecord( - Logger::WARNING, + Level::Warning, 'foo', channel: 'log', ), diff --git a/tests/Monolog/Formatter/LogstashFormatterTest.php b/tests/Monolog/Formatter/LogstashFormatterTest.php index f2d134225..81683e73f 100644 --- a/tests/Monolog/Formatter/LogstashFormatterTest.php +++ b/tests/Monolog/Formatter/LogstashFormatterTest.php @@ -11,7 +11,8 @@ namespace Monolog\Formatter; -use Monolog\Logger; +use Monolog\Level; +use Monolog\LevelName; use Monolog\Test\TestCase; class LogstashFormatterTest extends TestCase @@ -23,7 +24,7 @@ public function testDefaultFormatterV1() { $formatter = new LogstashFormatter('test', 'hostname'); $record = $this->getRecord( - Logger::ERROR, + Level::Error, 'log', channel: 'meh', datetime: new \DateTimeImmutable("@0"), @@ -35,8 +36,8 @@ public function testDefaultFormatterV1() $this->assertEquals("1", $message['@version']); $this->assertEquals('log', $message['message']); $this->assertEquals('meh', $message['channel']); - $this->assertEquals('ERROR', $message['level']); - $this->assertEquals(Logger::ERROR, $message['monolog_level']); + $this->assertEquals(LevelName::Error->value, $message['level']); + $this->assertEquals(Level::Error->value, $message['monolog_level']); $this->assertEquals('test', $message['type']); $this->assertEquals('hostname', $message['host']); @@ -54,7 +55,7 @@ public function testFormatWithFileAndLineV1() { $formatter = new LogstashFormatter('test'); $record = $this->getRecord( - Logger::ERROR, + Level::Error, 'log', channel: 'meh', context: ['from' => 'logger'], @@ -75,7 +76,7 @@ public function testFormatWithContextV1() { $formatter = new LogstashFormatter('test'); $record = $this->getRecord( - Logger::ERROR, + Level::Error, 'log', channel: 'meh', context: ['from' => 'logger'], @@ -105,7 +106,7 @@ public function testFormatWithExtraV1() { $formatter = new LogstashFormatter('test'); $record = $this->getRecord( - Logger::ERROR, + Level::Error, 'log', channel: 'meh', context: ['from' => 'logger'], @@ -132,7 +133,7 @@ public function testFormatWithApplicationNameV1() { $formatter = new LogstashFormatter('app', 'test'); $record = $this->getRecord( - Logger::ERROR, + Level::Error, 'log', channel: 'meh', context: ['from' => 'logger'], @@ -150,7 +151,7 @@ public function testFormatWithLatin9Data() { $formatter = new LogstashFormatter('test', 'hostname'); $record = $this->getRecord( - Logger::ERROR, + Level::Error, 'log', channel: '¯\_(ツ)_/¯', datetime: new \DateTimeImmutable("@0"), diff --git a/tests/Monolog/Formatter/MongoDBFormatterTest.php b/tests/Monolog/Formatter/MongoDBFormatterTest.php index 4874755fa..73d7ea992 100644 --- a/tests/Monolog/Formatter/MongoDBFormatterTest.php +++ b/tests/Monolog/Formatter/MongoDBFormatterTest.php @@ -14,7 +14,8 @@ use MongoDB\BSON\ObjectId; use MongoDB\BSON\Regex; use MongoDB\BSON\UTCDateTime; -use Monolog\Logger; +use Monolog\Level; +use Monolog\LevelName; use Monolog\Test\TestCase; /** @@ -62,7 +63,7 @@ public function testSimpleFormat() { $record = $this->getRecord( message: 'some log message', - level: Logger::WARNING, + level: Level::Warning, channel: 'test', datetime: new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'), ); @@ -73,8 +74,8 @@ public function testSimpleFormat() $this->assertCount(7, $formattedRecord); $this->assertEquals('some log message', $formattedRecord['message']); $this->assertEquals([], $formattedRecord['context']); - $this->assertEquals(Logger::WARNING, $formattedRecord['level']); - $this->assertEquals(Logger::getLevelName(Logger::WARNING), $formattedRecord['level_name']); + $this->assertEquals(Level::Warning->value, $formattedRecord['level']); + $this->assertEquals(LevelName::Warning->value, $formattedRecord['level_name']); $this->assertEquals('test', $formattedRecord['channel']); $this->assertInstanceOf('MongoDB\BSON\UTCDateTime', $formattedRecord['datetime']); $this->assertEquals('1453410690123', $formattedRecord['datetime']->__toString()); @@ -96,7 +97,7 @@ public function testRecursiveFormat() 'context_int' => 123456, 'except' => new \Exception('exception message', 987), ], - level: Logger::WARNING, + level: Level::Warning, channel: 'test', datetime: new \DateTimeImmutable('2016-01-21T21:11:30.213000+00:00'), ); @@ -140,7 +141,7 @@ public function testFormatDepthArray() ], ], ], - level: Logger::WARNING, + level: Level::Warning, channel: 'test', datetime: new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'), ); @@ -174,7 +175,7 @@ public function testFormatDepthArrayInfiniteNesting() ], ], ], - level: Logger::WARNING, + level: Level::Warning, channel: 'test', datetime: new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'), ); @@ -211,7 +212,7 @@ public function testFormatDepthObjects() context: [ 'nest2' => $someObject, ], - level: Logger::WARNING, + level: Level::Warning, channel: 'test', datetime: new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'), ); @@ -238,7 +239,7 @@ public function testFormatDepthException() context: [ 'nest2' => new \Exception('exception message', 987), ], - level: Logger::WARNING, + level: Level::Warning, channel: 'test', datetime: new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'), ); @@ -262,7 +263,7 @@ public function testBsonTypes() 'regex' => new Regex('pattern'), ], ], - level: Logger::WARNING, + level: Level::Warning, channel: 'test', datetime: new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'), ); diff --git a/tests/Monolog/Formatter/NormalizerFormatterTest.php b/tests/Monolog/Formatter/NormalizerFormatterTest.php index ab8d7b172..e13bb2ce3 100644 --- a/tests/Monolog/Formatter/NormalizerFormatterTest.php +++ b/tests/Monolog/Formatter/NormalizerFormatterTest.php @@ -11,8 +11,9 @@ namespace Monolog\Formatter; +use Monolog\LevelName; use Monolog\Test\TestCase; -use Monolog\Logger; +use Monolog\Level; /** * @covers Monolog\Formatter\NormalizerFormatter @@ -23,7 +24,7 @@ public function testFormat() { $formatter = new NormalizerFormatter('Y-m-d'); $formatted = $formatter->format($this->getRecord( - Logger::ERROR, + Level::Error, 'foo', channel: 'meh', extra: ['foo' => new TestFooNorm, 'bar' => new TestBarNorm, 'baz' => [], 'res' => fopen('php://memory', 'rb')], @@ -37,8 +38,8 @@ public function testFormat() )); $this->assertEquals([ - 'level_name' => 'ERROR', - 'level' => Logger::ERROR, + 'level_name' => LevelName::Error->value, + 'level' => Level::Error->value, 'channel' => 'meh', 'message' => 'foo', 'datetime' => date('Y-m-d'), @@ -142,13 +143,13 @@ public function testBatchFormat() { $formatter = new NormalizerFormatter('Y-m-d'); $formatted = $formatter->formatBatch([ - $this->getRecord(Logger::CRITICAL, 'bar', channel: 'test'), - $this->getRecord(Logger::WARNING, 'foo', channel: 'log'), + $this->getRecord(Level::Critical, 'bar', channel: 'test'), + $this->getRecord(Level::Warning, 'foo', channel: 'log'), ]); $this->assertEquals([ [ - 'level_name' => 'CRITICAL', - 'level' => Logger::CRITICAL, + 'level_name' => LevelName::Critical->value, + 'level' => Level::Critical->value, 'channel' => 'test', 'message' => 'bar', 'context' => [], @@ -156,8 +157,8 @@ public function testBatchFormat() 'extra' => [], ], [ - 'level_name' => 'WARNING', - 'level' => Logger::WARNING, + 'level_name' => LevelName::Warning->value, + 'level' => Level::Warning->value, 'channel' => 'log', 'message' => 'foo', 'context' => [], @@ -241,7 +242,7 @@ public function testNormalizeHandleLargeArraysWithExactly1000Items() $largeArray = range(1, 1000); $res = $formatter->format($this->getRecord( - Logger::CRITICAL, + Level::Critical, 'bar', channel: 'test', context: [$largeArray], @@ -257,7 +258,7 @@ public function testNormalizeHandleLargeArrays() $largeArray = range(1, 2000); $res = $formatter->format($this->getRecord( - Logger::CRITICAL, + Level::Critical, 'bar', channel: 'test', context: [$largeArray], @@ -379,7 +380,7 @@ public function testExceptionTraceWithArgs() private function formatRecordWithExceptionInContext(NormalizerFormatter $formatter, \Throwable $exception) { $message = $formatter->format($this->getRecord( - Logger::CRITICAL, + Level::Critical, 'foobar', channel: 'core', context: ['exception' => $exception], diff --git a/tests/Monolog/Formatter/WildfireFormatterTest.php b/tests/Monolog/Formatter/WildfireFormatterTest.php index a3babee0d..06a0fa70f 100644 --- a/tests/Monolog/Formatter/WildfireFormatterTest.php +++ b/tests/Monolog/Formatter/WildfireFormatterTest.php @@ -11,7 +11,7 @@ namespace Monolog\Formatter; -use Monolog\Logger; +use Monolog\Level; use Monolog\Test\TestCase; class WildfireFormatterTest extends TestCase @@ -23,7 +23,7 @@ public function testDefaultFormat() { $wildfire = new WildfireFormatter(); $record = $this->getRecord( - Logger::ERROR, + Level::Error, 'log', channel: 'meh', context: ['from' => 'logger'], @@ -46,7 +46,7 @@ public function testFormatWithFileAndLine() { $wildfire = new WildfireFormatter(); $record = $this->getRecord( - Logger::ERROR, + Level::Error, 'log', channel: 'meh', context: ['from' => 'logger'], @@ -69,7 +69,7 @@ public function testFormatWithoutContext() { $wildfire = new WildfireFormatter(); $record = $this->getRecord( - Logger::ERROR, + Level::Error, 'log', channel: 'meh', ); @@ -91,7 +91,7 @@ public function testBatchFormatThrowException() $wildfire = new WildfireFormatter(); $record = $this->getRecord( - Logger::ERROR, + Level::Error, 'log', channel: 'meh', ); @@ -106,7 +106,7 @@ public function testTableFormat() { $wildfire = new WildfireFormatter(); $record = $this->getRecord( - Logger::ERROR, + Level::Error, 'table-message', channel: 'table-channel', context: [ diff --git a/tests/Monolog/Handler/AbstractHandlerTest.php b/tests/Monolog/Handler/AbstractHandlerTest.php index b7451a73e..58de1dd9f 100644 --- a/tests/Monolog/Handler/AbstractHandlerTest.php +++ b/tests/Monolog/Handler/AbstractHandlerTest.php @@ -11,8 +11,8 @@ namespace Monolog\Handler; +use Monolog\Level; use Monolog\Test\TestCase; -use Monolog\Logger; class AbstractHandlerTest extends TestCase { @@ -25,13 +25,13 @@ class AbstractHandlerTest extends TestCase */ public function testConstructAndGetSet() { - $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler', [Logger::WARNING, false]); - $this->assertEquals(Logger::WARNING, $handler->getLevel()); + $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler', [Level::Warning, false]); + $this->assertEquals(Level::Warning, $handler->getLevel()); $this->assertEquals(false, $handler->getBubble()); - $handler->setLevel(Logger::ERROR); + $handler->setLevel(Level::Error); $handler->setBubble(true); - $this->assertEquals(Logger::ERROR, $handler->getLevel()); + $this->assertEquals(Level::Error, $handler->getLevel()); $this->assertEquals(true, $handler->getBubble()); } @@ -51,9 +51,9 @@ public function testHandleBatch() */ public function testIsHandling() { - $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler', [Logger::WARNING, false]); + $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler', [Level::Warning, false]); $this->assertTrue($handler->isHandling($this->getRecord())); - $this->assertFalse($handler->isHandling($this->getRecord(Logger::DEBUG))); + $this->assertFalse($handler->isHandling($this->getRecord(Level::Debug))); } /** @@ -62,8 +62,8 @@ public function testIsHandling() public function testHandlesPsrStyleLevels() { $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler', ['warning', false]); - $this->assertFalse($handler->isHandling($this->getRecord(Logger::DEBUG))); + $this->assertFalse($handler->isHandling($this->getRecord(Level::Debug))); $handler->setLevel('debug'); - $this->assertTrue($handler->isHandling($this->getRecord(Logger::DEBUG))); + $this->assertTrue($handler->isHandling($this->getRecord(Level::Debug))); } } diff --git a/tests/Monolog/Handler/AbstractProcessingHandlerTest.php b/tests/Monolog/Handler/AbstractProcessingHandlerTest.php index 7d732b39d..6fc3c38b8 100644 --- a/tests/Monolog/Handler/AbstractProcessingHandlerTest.php +++ b/tests/Monolog/Handler/AbstractProcessingHandlerTest.php @@ -12,7 +12,7 @@ namespace Monolog\Handler; use Monolog\Test\TestCase; -use Monolog\Logger; +use Monolog\Level; use Monolog\Processor\WebProcessor; use Monolog\Formatter\LineFormatter; @@ -24,7 +24,7 @@ class AbstractProcessingHandlerTest extends TestCase */ public function testConstructAndGetSet() { - $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', [Logger::WARNING, false]); + $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', [Level::Warning, false]); $handler->setFormatter($formatter = new LineFormatter); $this->assertSame($formatter, $handler->getFormatter()); } @@ -34,8 +34,8 @@ public function testConstructAndGetSet() */ public function testHandleLowerLevelMessage() { - $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', [Logger::WARNING, true]); - $this->assertFalse($handler->handle($this->getRecord(Logger::DEBUG))); + $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', [Level::Warning, true]); + $this->assertFalse($handler->handle($this->getRecord(Level::Debug))); } /** @@ -43,7 +43,7 @@ public function testHandleLowerLevelMessage() */ public function testHandleBubbling() { - $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', [Logger::DEBUG, true]); + $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', [Level::Debug, true]); $this->assertFalse($handler->handle($this->getRecord())); } @@ -52,7 +52,7 @@ public function testHandleBubbling() */ public function testHandleNotBubbling() { - $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', [Logger::DEBUG, false]); + $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', [Level::Debug, false]); $this->assertTrue($handler->handle($this->getRecord())); } @@ -61,9 +61,9 @@ public function testHandleNotBubbling() */ public function testHandleIsFalseWhenNotHandled() { - $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', [Logger::WARNING, false]); + $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', [Level::Warning, false]); $this->assertTrue($handler->handle($this->getRecord())); - $this->assertFalse($handler->handle($this->getRecord(Logger::DEBUG))); + $this->assertFalse($handler->handle($this->getRecord(Level::Debug))); } /** diff --git a/tests/Monolog/Handler/AmqpHandlerTest.php b/tests/Monolog/Handler/AmqpHandlerTest.php index c2de874c6..321727050 100644 --- a/tests/Monolog/Handler/AmqpHandlerTest.php +++ b/tests/Monolog/Handler/AmqpHandlerTest.php @@ -12,7 +12,7 @@ namespace Monolog\Handler; use Monolog\Test\TestCase; -use Monolog\Logger; +use Monolog\Level; use PhpAmqpLib\Message\AMQPMessage; /** @@ -46,7 +46,7 @@ public function testHandleAmqpExt() $handler = new AmqpHandler($exchange); - $record = $this->getRecord(Logger::WARNING, 'test', ['data' => new \stdClass, 'foo' => 34]); + $record = $this->getRecord(Level::Warning, 'test', ['data' => new \stdClass, 'foo' => 34]); $expected = [ [ @@ -103,7 +103,7 @@ public function testHandlePhpAmqpLib() $handler = new AmqpHandler($exchange, 'log'); - $record = $this->getRecord(Logger::WARNING, 'test', ['data' => new \stdClass, 'foo' => 34]); + $record = $this->getRecord(Level::Warning, 'test', ['data' => new \stdClass, 'foo' => 34]); $expected = [ [ diff --git a/tests/Monolog/Handler/BrowserConsoleHandlerTest.php b/tests/Monolog/Handler/BrowserConsoleHandlerTest.php index 5bda6b00c..1628a4b61 100644 --- a/tests/Monolog/Handler/BrowserConsoleHandlerTest.php +++ b/tests/Monolog/Handler/BrowserConsoleHandlerTest.php @@ -12,7 +12,7 @@ namespace Monolog\Handler; use Monolog\Test\TestCase; -use Monolog\Logger; +use Monolog\Level; /** * @covers Monolog\Handler\BrowserConsoleHandlerTest @@ -37,7 +37,7 @@ public function testStyling() $handler = new BrowserConsoleHandler(); $handler->setFormatter($this->getIdentityFormatter()); - $handler->handle($this->getRecord(Logger::DEBUG, 'foo[[bar]]{color: red}')); + $handler->handle($this->getRecord(Level::Debug, 'foo[[bar]]{color: red}')); $expected = <<setFormatter($this->getIdentityFormatter()); - $handler->handle($this->getRecord(Logger::DEBUG, 'foo[[bar]]{color: red}[[baz]]{color: blue}')); + $handler->handle($this->getRecord(Level::Debug, 'foo[[bar]]{color: red}[[baz]]{color: blue}')); $expected = <<setFormatter($this->getIdentityFormatter()); - $handler->handle($this->getRecord(Logger::DEBUG, "[foo] [[\"bar\n[baz]\"]]{color: red}")); + $handler->handle($this->getRecord(Level::Debug, "[foo] [[\"bar\n[baz]\"]]{color: red}")); $expected = <<setFormatter($this->getIdentityFormatter()); - $handler->handle($this->getRecord(Logger::DEBUG, '[[foo]]{macro: autolabel}')); - $handler->handle($this->getRecord(Logger::DEBUG, '[[bar]]{macro: autolabel}')); - $handler->handle($this->getRecord(Logger::DEBUG, '[[foo]]{macro: autolabel}')); + $handler->handle($this->getRecord(Level::Debug, '[[foo]]{macro: autolabel}')); + $handler->handle($this->getRecord(Level::Debug, '[[bar]]{macro: autolabel}')); + $handler->handle($this->getRecord(Level::Debug, '[[foo]]{macro: autolabel}')); $expected = <<setFormatter($this->getIdentityFormatter()); - $handler->handle($this->getRecord(Logger::DEBUG, 'test', ['foo' => 'bar', 0 => 'oop'])); + $handler->handle($this->getRecord(Level::Debug, 'test', ['foo' => 'bar', 0 => 'oop'])); $expected = <<setFormatter($this->getIdentityFormatter()); - $handler1->handle($this->getRecord(Logger::DEBUG, 'test1')); - $handler2->handle($this->getRecord(Logger::DEBUG, 'test2')); - $handler1->handle($this->getRecord(Logger::DEBUG, 'test3')); - $handler2->handle($this->getRecord(Logger::DEBUG, 'test4')); + $handler1->handle($this->getRecord(Level::Debug, 'test1')); + $handler2->handle($this->getRecord(Level::Debug, 'test2')); + $handler1->handle($this->getRecord(Level::Debug, 'test3')); + $handler2->handle($this->getRecord(Level::Debug, 'test4')); $expected = <<handle($this->getRecord(Logger::DEBUG)); - $handler->handle($this->getRecord(Logger::INFO)); + $handler->handle($this->getRecord(Level::Debug)); + $handler->handle($this->getRecord(Level::Info)); $this->assertFalse($test->hasDebugRecords()); $this->assertFalse($test->hasInfoRecords()); $handler->close(); @@ -44,8 +44,8 @@ public function testPropagatesRecordsAtEndOfRequest() { $test = new TestHandler(); $handler = new BufferHandler($test); - $handler->handle($this->getRecord(Logger::WARNING)); - $handler->handle($this->getRecord(Logger::DEBUG)); + $handler->handle($this->getRecord(Level::Warning)); + $handler->handle($this->getRecord(Level::Debug)); $this->shutdownCheckHandler = $test; register_shutdown_function([$this, 'checkPropagation']); } @@ -65,10 +65,10 @@ public function testHandleBufferLimit() { $test = new TestHandler(); $handler = new BufferHandler($test, 2); - $handler->handle($this->getRecord(Logger::DEBUG)); - $handler->handle($this->getRecord(Logger::DEBUG)); - $handler->handle($this->getRecord(Logger::INFO)); - $handler->handle($this->getRecord(Logger::WARNING)); + $handler->handle($this->getRecord(Level::Debug)); + $handler->handle($this->getRecord(Level::Debug)); + $handler->handle($this->getRecord(Level::Info)); + $handler->handle($this->getRecord(Level::Warning)); $handler->close(); $this->assertTrue($test->hasWarningRecords()); $this->assertTrue($test->hasInfoRecords()); @@ -81,22 +81,22 @@ public function testHandleBufferLimit() public function testHandleBufferLimitWithFlushOnOverflow() { $test = new TestHandler(); - $handler = new BufferHandler($test, 3, Logger::DEBUG, true, true); + $handler = new BufferHandler($test, 3, Level::Debug, true, true); // send two records - $handler->handle($this->getRecord(Logger::DEBUG)); - $handler->handle($this->getRecord(Logger::DEBUG)); - $handler->handle($this->getRecord(Logger::DEBUG)); + $handler->handle($this->getRecord(Level::Debug)); + $handler->handle($this->getRecord(Level::Debug)); + $handler->handle($this->getRecord(Level::Debug)); $this->assertFalse($test->hasDebugRecords()); $this->assertCount(0, $test->getRecords()); // overflow - $handler->handle($this->getRecord(Logger::INFO)); + $handler->handle($this->getRecord(Level::Info)); $this->assertTrue($test->hasDebugRecords()); $this->assertCount(3, $test->getRecords()); // should buffer again - $handler->handle($this->getRecord(Logger::WARNING)); + $handler->handle($this->getRecord(Level::Warning)); $this->assertCount(3, $test->getRecords()); $handler->close(); @@ -111,11 +111,11 @@ public function testHandleBufferLimitWithFlushOnOverflow() public function testHandleLevel() { $test = new TestHandler(); - $handler = new BufferHandler($test, 0, Logger::INFO); - $handler->handle($this->getRecord(Logger::DEBUG)); - $handler->handle($this->getRecord(Logger::INFO)); - $handler->handle($this->getRecord(Logger::WARNING)); - $handler->handle($this->getRecord(Logger::DEBUG)); + $handler = new BufferHandler($test, 0, Level::Info); + $handler->handle($this->getRecord(Level::Debug)); + $handler->handle($this->getRecord(Level::Info)); + $handler->handle($this->getRecord(Level::Warning)); + $handler->handle($this->getRecord(Level::Debug)); $handler->close(); $this->assertTrue($test->hasWarningRecords()); $this->assertTrue($test->hasInfoRecords()); @@ -129,8 +129,8 @@ public function testFlush() { $test = new TestHandler(); $handler = new BufferHandler($test, 0); - $handler->handle($this->getRecord(Logger::DEBUG)); - $handler->handle($this->getRecord(Logger::INFO)); + $handler->handle($this->getRecord(Level::Debug)); + $handler->handle($this->getRecord(Level::Info)); $handler->flush(); $this->assertTrue($test->hasInfoRecords()); $this->assertTrue($test->hasDebugRecords()); @@ -149,7 +149,7 @@ public function testHandleUsesProcessors() return $record; }); - $handler->handle($this->getRecord(Logger::WARNING)); + $handler->handle($this->getRecord(Level::Warning)); $handler->flush(); $this->assertTrue($test->hasWarningRecords()); $records = $test->getRecords(); diff --git a/tests/Monolog/Handler/ChromePHPHandlerTest.php b/tests/Monolog/Handler/ChromePHPHandlerTest.php index 1ee581959..5600cd288 100644 --- a/tests/Monolog/Handler/ChromePHPHandlerTest.php +++ b/tests/Monolog/Handler/ChromePHPHandlerTest.php @@ -12,7 +12,7 @@ namespace Monolog\Handler; use Monolog\Test\TestCase; -use Monolog\Logger; +use Monolog\Level; /** * @covers Monolog\Handler\ChromePHPHandler @@ -34,8 +34,8 @@ public function testHeaders($agent) $handler = new TestChromePHPHandler(); $handler->setFormatter($this->getIdentityFormatter()); - $handler->handle($this->getRecord(Logger::DEBUG)); - $handler->handle($this->getRecord(Logger::WARNING)); + $handler->handle($this->getRecord(Level::Debug)); + $handler->handle($this->getRecord(Level::Warning)); $expected = [ 'X-ChromeLogger-Data' => base64_encode(utf8_encode(json_encode([ @@ -65,11 +65,11 @@ public static function agentsProvider() public function testHeadersOverflow() { $handler = new TestChromePHPHandler(); - $handler->handle($this->getRecord(Logger::DEBUG)); - $handler->handle($this->getRecord(Logger::WARNING, str_repeat('a', 2 * 1024))); + $handler->handle($this->getRecord(Level::Debug)); + $handler->handle($this->getRecord(Level::Warning, str_repeat('a', 2 * 1024))); // overflow chrome headers limit - $handler->handle($this->getRecord(Logger::WARNING, str_repeat('b', 2 * 1024))); + $handler->handle($this->getRecord(Level::Warning, str_repeat('b', 2 * 1024))); $expected = [ 'X-ChromeLogger-Data' => base64_encode(utf8_encode(json_encode([ @@ -106,13 +106,13 @@ public function testConcurrentHandlers() { $handler = new TestChromePHPHandler(); $handler->setFormatter($this->getIdentityFormatter()); - $handler->handle($this->getRecord(Logger::DEBUG)); - $handler->handle($this->getRecord(Logger::WARNING)); + $handler->handle($this->getRecord(Level::Debug)); + $handler->handle($this->getRecord(Level::Warning)); $handler2 = new TestChromePHPHandler(); $handler2->setFormatter($this->getIdentityFormatter()); - $handler2->handle($this->getRecord(Logger::DEBUG)); - $handler2->handle($this->getRecord(Logger::WARNING)); + $handler2->handle($this->getRecord(Level::Debug)); + $handler2->handle($this->getRecord(Level::Warning)); $expected = [ 'X-ChromeLogger-Data' => base64_encode(utf8_encode(json_encode([ diff --git a/tests/Monolog/Handler/CouchDBHandlerTest.php b/tests/Monolog/Handler/CouchDBHandlerTest.php index f89a130b5..289bcf5ab 100644 --- a/tests/Monolog/Handler/CouchDBHandlerTest.php +++ b/tests/Monolog/Handler/CouchDBHandlerTest.php @@ -12,13 +12,13 @@ namespace Monolog\Handler; use Monolog\Test\TestCase; -use Monolog\Logger; +use Monolog\Level; class CouchDBHandlerTest extends TestCase { public function testHandle() { - $record = $this->getRecord(Logger::WARNING, 'test', ['data' => new \stdClass, 'foo' => 34]); + $record = $this->getRecord(Level::Warning, 'test', ['data' => new \stdClass, 'foo' => 34]); $handler = new CouchDBHandler(); diff --git a/tests/Monolog/Handler/DeduplicationHandlerTest.php b/tests/Monolog/Handler/DeduplicationHandlerTest.php index 86c7c8a5d..f617e019f 100644 --- a/tests/Monolog/Handler/DeduplicationHandlerTest.php +++ b/tests/Monolog/Handler/DeduplicationHandlerTest.php @@ -11,8 +11,8 @@ namespace Monolog\Handler; +use Monolog\Level; use Monolog\Test\TestCase; -use Monolog\Logger; class DeduplicationHandlerTest extends TestCase { @@ -23,10 +23,10 @@ public function testFlushPassthruIfAllRecordsUnderTrigger() { $test = new TestHandler(); @unlink(sys_get_temp_dir().'/monolog_dedup.log'); - $handler = new DeduplicationHandler($test, sys_get_temp_dir().'/monolog_dedup.log', 0); + $handler = new DeduplicationHandler($test, sys_get_temp_dir().'/monolog_dedup.log', Level::Debug); - $handler->handle($this->getRecord(Logger::DEBUG)); - $handler->handle($this->getRecord(Logger::INFO)); + $handler->handle($this->getRecord(Level::Debug)); + $handler->handle($this->getRecord(Level::Info)); $handler->flush(); @@ -43,10 +43,10 @@ public function testFlushPassthruIfEmptyLog() { $test = new TestHandler(); @unlink(sys_get_temp_dir().'/monolog_dedup.log'); - $handler = new DeduplicationHandler($test, sys_get_temp_dir().'/monolog_dedup.log', 0); + $handler = new DeduplicationHandler($test, sys_get_temp_dir().'/monolog_dedup.log', Level::Debug); - $handler->handle($this->getRecord(Logger::ERROR, 'Foo:bar')); - $handler->handle($this->getRecord(Logger::CRITICAL, "Foo\nbar")); + $handler->handle($this->getRecord(Level::Error, 'Foo:bar')); + $handler->handle($this->getRecord(Level::Critical, "Foo\nbar")); $handler->flush(); @@ -64,10 +64,10 @@ public function testFlushPassthruIfEmptyLog() public function testFlushSkipsIfLogExists() { $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', Level::Debug); - $handler->handle($this->getRecord(Logger::ERROR, 'Foo:bar')); - $handler->handle($this->getRecord(Logger::CRITICAL, "Foo\nbar")); + $handler->handle($this->getRecord(Level::Error, 'Foo:bar')); + $handler->handle($this->getRecord(Level::Critical, "Foo\nbar")); $handler->flush(); @@ -85,11 +85,11 @@ public function testFlushSkipsIfLogExists() public function testFlushPassthruIfLogTooOld() { $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', Level::Debug); - $record = $this->getRecord(Logger::ERROR, datetime: new \DateTimeImmutable('+62seconds')); + $record = $this->getRecord(Level::Error, datetime: new \DateTimeImmutable('+62seconds')); $handler->handle($record); - $record = $this->getRecord(Logger::CRITICAL, datetime: new \DateTimeImmutable('+62seconds')); + $record = $this->getRecord(Level::Critical, datetime: new \DateTimeImmutable('+62seconds')); $handler->handle($record); $handler->flush(); @@ -109,14 +109,14 @@ public function testGcOldLogs() { $test = new TestHandler(); @unlink(sys_get_temp_dir().'/monolog_dedup.log'); - $handler = new DeduplicationHandler($test, sys_get_temp_dir().'/monolog_dedup.log', 0); + $handler = new DeduplicationHandler($test, sys_get_temp_dir().'/monolog_dedup.log', Level::Debug); // handle two records from yesterday, and one recent - $record = $this->getRecord(Logger::ERROR, datetime: new \DateTimeImmutable('-1day -10seconds')); + $record = $this->getRecord(Level::Error, datetime: new \DateTimeImmutable('-1day -10seconds')); $handler->handle($record); - $record2 = $this->getRecord(Logger::CRITICAL, datetime: new \DateTimeImmutable('-1day -10seconds')); + $record2 = $this->getRecord(Level::Critical, datetime: new \DateTimeImmutable('-1day -10seconds')); $handler->handle($record2); - $record3 = $this->getRecord(Logger::CRITICAL, datetime: new \DateTimeImmutable('-30seconds')); + $record3 = $this->getRecord(Level::Critical, datetime: new \DateTimeImmutable('-30seconds')); $handler->handle($record3); // log is written as none of them are duplicate @@ -137,8 +137,8 @@ public function testGcOldLogs() $this->assertFalse($test->hasCriticalRecords()); // log new records, duplicate log gets GC'd at the end of this flush call - $handler->handle($record = $this->getRecord(Logger::ERROR)); - $handler->handle($record2 = $this->getRecord(Logger::CRITICAL)); + $handler->handle($record = $this->getRecord(Level::Error)); + $handler->handle($record2 = $this->getRecord(Level::Critical)); $handler->flush(); // log should now contain the new errors and the previous one that was recent enough diff --git a/tests/Monolog/Handler/DoctrineCouchDBHandlerTest.php b/tests/Monolog/Handler/DoctrineCouchDBHandlerTest.php index 35330681e..1f6f2ffb8 100644 --- a/tests/Monolog/Handler/DoctrineCouchDBHandlerTest.php +++ b/tests/Monolog/Handler/DoctrineCouchDBHandlerTest.php @@ -12,7 +12,7 @@ namespace Monolog\Handler; use Monolog\Test\TestCase; -use Monolog\Logger; +use Monolog\Level; class DoctrineCouchDBHandlerTest extends TestCase { @@ -30,12 +30,12 @@ public function testHandle() ->disableOriginalConstructor() ->getMock(); - $record = $this->getRecord(Logger::WARNING, 'test', ['data' => new \stdClass, 'foo' => 34]); + $record = $this->getRecord(Level::Warning, 'test', ['data' => new \stdClass, 'foo' => 34]); $expected = [ 'message' => 'test', 'context' => ['data' => ['stdClass' => []], 'foo' => 34], - 'level' => Logger::WARNING, + 'level' => Level::Warning->value, 'level_name' => 'WARNING', 'channel' => 'test', 'datetime' => (string) $record->datetime, diff --git a/tests/Monolog/Handler/ElasticaHandlerTest.php b/tests/Monolog/Handler/ElasticaHandlerTest.php index 1fa3be3b4..706e417f3 100644 --- a/tests/Monolog/Handler/ElasticaHandlerTest.php +++ b/tests/Monolog/Handler/ElasticaHandlerTest.php @@ -14,7 +14,7 @@ use Monolog\Formatter\ElasticaFormatter; use Monolog\Formatter\NormalizerFormatter; use Monolog\Test\TestCase; -use Monolog\Logger; +use Monolog\Level; use Monolog\LogRecord; use Elastica\Client; use Elastica\Request; @@ -58,7 +58,7 @@ public function setUp(): void public function testHandle() { // log message - $msg = $this->getRecord(Logger::ERROR, 'log', context: ['foo' => 7, 'bar', 'class' => new \stdClass], datetime: new \DateTimeImmutable("@0")); + $msg = $this->getRecord(Level::Error, 'log', context: ['foo' => 7, 'bar', 'class' => new \stdClass], datetime: new \DateTimeImmutable("@0")); // format expected result $formatter = new ElasticaFormatter($this->options['index'], $this->options['type']); @@ -158,7 +158,7 @@ public function providerTestConnectionErrors() */ public function testHandleIntegration() { - $msg = $this->getRecord(Logger::ERROR, 'log', context: ['foo' => 7, 'bar', 'class' => new \stdClass], datetime: new \DateTimeImmutable("@0")); + $msg = $this->getRecord(Level::Error, 'log', context: ['foo' => 7, 'bar', 'class' => new \stdClass], datetime: new \DateTimeImmutable("@0")); $expected = $msg->toArray(); $expected['datetime'] = $msg['datetime']->format(\DateTime::ISO8601); @@ -204,7 +204,7 @@ public function testHandleIntegration() */ public function testHandleIntegrationNewESVersion() { - $msg = $this->getRecord(Logger::ERROR, 'log', context: ['foo' => 7, 'bar', 'class' => new \stdClass], datetime: new \DateTimeImmutable("@0")); + $msg = $this->getRecord(Level::Error, 'log', context: ['foo' => 7, 'bar', 'class' => new \stdClass], datetime: new \DateTimeImmutable("@0")); $expected = (array) $msg; $expected['datetime'] = $msg['datetime']->format(\DateTime::ISO8601); diff --git a/tests/Monolog/Handler/ElasticsearchHandlerTest.php b/tests/Monolog/Handler/ElasticsearchHandlerTest.php index ba4de76bb..9009b71d4 100644 --- a/tests/Monolog/Handler/ElasticsearchHandlerTest.php +++ b/tests/Monolog/Handler/ElasticsearchHandlerTest.php @@ -15,7 +15,7 @@ use Monolog\Formatter\ElasticsearchFormatter; use Monolog\Formatter\NormalizerFormatter; use Monolog\Test\TestCase; -use Monolog\Logger; +use Monolog\Level; use Elasticsearch\Client; class ElasticsearchHandlerTest extends TestCase @@ -56,7 +56,7 @@ public function setUp(): void public function testHandle() { // log message - $msg = $this->getRecord(Logger::ERROR, 'log', context: ['foo' => 7, 'bar', 'class' => new \stdClass], datetime: new \DateTimeImmutable("@0")); + $msg = $this->getRecord(Level::Error, 'log', context: ['foo' => 7, 'bar', 'class' => new \stdClass], datetime: new \DateTimeImmutable("@0")); // format expected result $formatter = new ElasticsearchFormatter($this->options['index'], $this->options['type']); @@ -172,7 +172,7 @@ public function providerTestConnectionErrors() */ public function testHandleIntegration() { - $msg = $this->getRecord(Logger::ERROR, 'log', context: ['foo' => 7, 'bar', 'class' => new \stdClass], datetime: new \DateTimeImmutable("@0")); + $msg = $this->getRecord(Level::Error, 'log', context: ['foo' => 7, 'bar', 'class' => new \stdClass], datetime: new \DateTimeImmutable("@0")); $expected = $msg->toArray(); $expected['datetime'] = $msg['datetime']->format(\DateTime::ISO8601); diff --git a/tests/Monolog/Handler/ErrorLogHandlerTest.php b/tests/Monolog/Handler/ErrorLogHandlerTest.php index 10e8ec206..37bf58c56 100644 --- a/tests/Monolog/Handler/ErrorLogHandlerTest.php +++ b/tests/Monolog/Handler/ErrorLogHandlerTest.php @@ -12,7 +12,7 @@ namespace Monolog\Handler; use Monolog\Test\TestCase; -use Monolog\Logger; +use Monolog\Level; use Monolog\Formatter\LineFormatter; function error_log() @@ -46,14 +46,14 @@ public function testShouldLogMessagesUsingErrorLogFunction() $type = ErrorLogHandler::OPERATING_SYSTEM; $handler = new ErrorLogHandler($type); $handler->setFormatter(new LineFormatter('%channel%.%level_name%: %message% %context% %extra%', null, true)); - $handler->handle($this->getRecord(Logger::ERROR, "Foo\nBar\r\n\r\nBaz")); + $handler->handle($this->getRecord(Level::Error, "Foo\nBar\r\n\r\nBaz")); $this->assertSame("test.ERROR: Foo\nBar\r\n\r\nBaz [] []", $GLOBALS['error_log'][0][0]); $this->assertSame($GLOBALS['error_log'][0][1], $type); - $handler = new ErrorLogHandler($type, Logger::DEBUG, true, true); + $handler = new ErrorLogHandler($type, Level::Debug, true, true); $handler->setFormatter(new LineFormatter(null, null, true)); - $handler->handle($this->getRecord(Logger::ERROR, "Foo\nBar\r\n\r\nBaz")); + $handler->handle($this->getRecord(Level::Error, "Foo\nBar\r\n\r\nBaz")); $this->assertStringMatchesFormat('[%s] test.ERROR: Foo', $GLOBALS['error_log'][1][0]); $this->assertSame($GLOBALS['error_log'][1][1], $type); diff --git a/tests/Monolog/Handler/FallbackGroupHandlerTest.php b/tests/Monolog/Handler/FallbackGroupHandlerTest.php index 0cb149bcb..b364c0ff3 100644 --- a/tests/Monolog/Handler/FallbackGroupHandlerTest.php +++ b/tests/Monolog/Handler/FallbackGroupHandlerTest.php @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Monolog\Test\TestCase; class FallbackGroupHandlerTest extends TestCase @@ -26,8 +26,8 @@ public function testHandle() $testHandlerTwo = new TestHandler(); $testHandlers = [$testHandlerOne, $testHandlerTwo]; $handler = new FallbackGroupHandler($testHandlers); - $handler->handle($this->getRecord(Logger::DEBUG)); - $handler->handle($this->getRecord(Logger::INFO)); + $handler->handle($this->getRecord(Level::Debug)); + $handler->handle($this->getRecord(Level::Info)); $this->assertCount(2, $testHandlerOne->getRecords()); $this->assertCount(0, $testHandlerTwo->getRecords()); @@ -43,8 +43,8 @@ public function testHandleExceptionThrown() $testHandlerTwo = new TestHandler(); $testHandlers = [$testHandlerOne, $testHandlerTwo]; $handler = new FallbackGroupHandler($testHandlers); - $handler->handle($this->getRecord(Logger::DEBUG)); - $handler->handle($this->getRecord(Logger::INFO)); + $handler->handle($this->getRecord(Level::Debug)); + $handler->handle($this->getRecord(Level::Info)); $this->assertCount(0, $testHandlerOne->getRecords()); $this->assertCount(2, $testHandlerTwo->getRecords()); @@ -59,7 +59,7 @@ public function testHandleBatch() $testHandlerTwo = new TestHandler(); $testHandlers = [$testHandlerOne, $testHandlerTwo]; $handler = new FallbackGroupHandler($testHandlers); - $handler->handleBatch([$this->getRecord(Logger::DEBUG), $this->getRecord(Logger::INFO)]); + $handler->handleBatch([$this->getRecord(Level::Debug), $this->getRecord(Level::Info)]); $this->assertCount(2, $testHandlerOne->getRecords()); $this->assertCount(0, $testHandlerTwo->getRecords()); } @@ -73,7 +73,7 @@ public function testHandleBatchExceptionThrown() $testHandlerTwo = new TestHandler(); $testHandlers = [$testHandlerOne, $testHandlerTwo]; $handler = new FallbackGroupHandler($testHandlers); - $handler->handleBatch([$this->getRecord(Logger::DEBUG), $this->getRecord(Logger::INFO)]); + $handler->handleBatch([$this->getRecord(Level::Debug), $this->getRecord(Level::Info)]); $this->assertCount(0, $testHandlerOne->getRecords()); $this->assertCount(2, $testHandlerTwo->getRecords()); } @@ -83,11 +83,11 @@ public function testHandleBatchExceptionThrown() */ public function testIsHandling() { - $testHandlers = [new TestHandler(Logger::ERROR), new TestHandler(Logger::WARNING)]; + $testHandlers = [new TestHandler(Level::Error), new TestHandler(Level::Warning)]; $handler = new FallbackGroupHandler($testHandlers); - $this->assertTrue($handler->isHandling($this->getRecord(Logger::ERROR))); - $this->assertTrue($handler->isHandling($this->getRecord(Logger::WARNING))); - $this->assertFalse($handler->isHandling($this->getRecord(Logger::DEBUG))); + $this->assertTrue($handler->isHandling($this->getRecord(Level::Error))); + $this->assertTrue($handler->isHandling($this->getRecord(Level::Warning))); + $this->assertFalse($handler->isHandling($this->getRecord(Level::Debug))); } /** @@ -102,7 +102,7 @@ public function testHandleUsesProcessors() return $record; }); - $handler->handle($this->getRecord(Logger::WARNING)); + $handler->handle($this->getRecord(Level::Warning)); $this->assertTrue($test->hasWarningRecords()); $records = $test->getRecords(); $this->assertTrue($records[0]['extra']['foo']); @@ -127,7 +127,7 @@ public function testHandleBatchUsesProcessors() return $record; }); - $handler->handleBatch([$this->getRecord(Logger::DEBUG), $this->getRecord(Logger::INFO)]); + $handler->handleBatch([$this->getRecord(Level::Debug), $this->getRecord(Level::Info)]); $this->assertEmpty($testHandlerOne->getRecords()); $this->assertTrue($testHandlerTwo->hasDebugRecords()); $this->assertTrue($testHandlerTwo->hasInfoRecords()); diff --git a/tests/Monolog/Handler/FilterHandlerTest.php b/tests/Monolog/Handler/FilterHandlerTest.php index 49ecb12b8..4fa2eb79e 100644 --- a/tests/Monolog/Handler/FilterHandlerTest.php +++ b/tests/Monolog/Handler/FilterHandlerTest.php @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Monolog\Test\TestCase; class FilterHandlerTest extends TestCase @@ -22,15 +22,15 @@ class FilterHandlerTest extends TestCase public function testIsHandling() { $test = new TestHandler(); - $handler = new FilterHandler($test, Logger::INFO, Logger::NOTICE); - $this->assertFalse($handler->isHandling($this->getRecord(Logger::DEBUG))); - $this->assertTrue($handler->isHandling($this->getRecord(Logger::INFO))); - $this->assertTrue($handler->isHandling($this->getRecord(Logger::NOTICE))); - $this->assertFalse($handler->isHandling($this->getRecord(Logger::WARNING))); - $this->assertFalse($handler->isHandling($this->getRecord(Logger::ERROR))); - $this->assertFalse($handler->isHandling($this->getRecord(Logger::CRITICAL))); - $this->assertFalse($handler->isHandling($this->getRecord(Logger::ALERT))); - $this->assertFalse($handler->isHandling($this->getRecord(Logger::EMERGENCY))); + $handler = new FilterHandler($test, Level::Info, Level::Notice); + $this->assertFalse($handler->isHandling($this->getRecord(Level::Debug))); + $this->assertTrue($handler->isHandling($this->getRecord(Level::Info))); + $this->assertTrue($handler->isHandling($this->getRecord(Level::Notice))); + $this->assertFalse($handler->isHandling($this->getRecord(Level::Warning))); + $this->assertFalse($handler->isHandling($this->getRecord(Level::Error))); + $this->assertFalse($handler->isHandling($this->getRecord(Level::Critical))); + $this->assertFalse($handler->isHandling($this->getRecord(Level::Alert))); + $this->assertFalse($handler->isHandling($this->getRecord(Level::Emergency))); } /** @@ -41,39 +41,39 @@ public function testIsHandling() public function testHandleProcessOnlyNeededLevels() { $test = new TestHandler(); - $handler = new FilterHandler($test, Logger::INFO, Logger::NOTICE); + $handler = new FilterHandler($test, Level::Info, Level::Notice); - $handler->handle($this->getRecord(Logger::DEBUG)); + $handler->handle($this->getRecord(Level::Debug)); $this->assertFalse($test->hasDebugRecords()); - $handler->handle($this->getRecord(Logger::INFO)); + $handler->handle($this->getRecord(Level::Info)); $this->assertTrue($test->hasInfoRecords()); - $handler->handle($this->getRecord(Logger::NOTICE)); + $handler->handle($this->getRecord(Level::Notice)); $this->assertTrue($test->hasNoticeRecords()); - $handler->handle($this->getRecord(Logger::WARNING)); + $handler->handle($this->getRecord(Level::Warning)); $this->assertFalse($test->hasWarningRecords()); - $handler->handle($this->getRecord(Logger::ERROR)); + $handler->handle($this->getRecord(Level::Error)); $this->assertFalse($test->hasErrorRecords()); - $handler->handle($this->getRecord(Logger::CRITICAL)); + $handler->handle($this->getRecord(Level::Critical)); $this->assertFalse($test->hasCriticalRecords()); - $handler->handle($this->getRecord(Logger::ALERT)); + $handler->handle($this->getRecord(Level::Alert)); $this->assertFalse($test->hasAlertRecords()); - $handler->handle($this->getRecord(Logger::EMERGENCY)); + $handler->handle($this->getRecord(Level::Emergency)); $this->assertFalse($test->hasEmergencyRecords()); $test = new TestHandler(); - $handler = new FilterHandler($test, [Logger::INFO, Logger::ERROR]); + $handler = new FilterHandler($test, [Level::Info, Level::Error]); - $handler->handle($this->getRecord(Logger::DEBUG)); + $handler->handle($this->getRecord(Level::Debug)); $this->assertFalse($test->hasDebugRecords()); - $handler->handle($this->getRecord(Logger::INFO)); + $handler->handle($this->getRecord(Level::Info)); $this->assertTrue($test->hasInfoRecords()); - $handler->handle($this->getRecord(Logger::NOTICE)); + $handler->handle($this->getRecord(Level::Notice)); $this->assertFalse($test->hasNoticeRecords()); - $handler->handle($this->getRecord(Logger::ERROR)); + $handler->handle($this->getRecord(Level::Error)); $this->assertTrue($test->hasErrorRecords()); - $handler->handle($this->getRecord(Logger::CRITICAL)); + $handler->handle($this->getRecord(Level::Critical)); $this->assertFalse($test->hasCriticalRecords()); } @@ -86,15 +86,16 @@ public function testAcceptedLevelApi() $test = new TestHandler(); $handler = new FilterHandler($test); - $levels = [Logger::INFO, Logger::ERROR]; + $levels = [Level::Info, Level::Error]; + $levelsExpect = [Level::Info, Level::Error]; $handler->setAcceptedLevels($levels); - $this->assertSame($levels, $handler->getAcceptedLevels()); + $this->assertSame($levelsExpect, $handler->getAcceptedLevels()); $handler->setAcceptedLevels(['info', 'error']); - $this->assertSame($levels, $handler->getAcceptedLevels()); + $this->assertSame($levelsExpect, $handler->getAcceptedLevels()); - $levels = [Logger::CRITICAL, Logger::ALERT, Logger::EMERGENCY]; - $handler->setAcceptedLevels(Logger::CRITICAL, Logger::EMERGENCY); + $levels = [Level::Critical, Level::Alert, Level::Emergency]; + $handler->setAcceptedLevels(Level::Critical, Level::Emergency); $this->assertSame($levels, $handler->getAcceptedLevels()); $handler->setAcceptedLevels('critical', 'emergency'); @@ -107,7 +108,7 @@ public function testAcceptedLevelApi() public function testHandleUsesProcessors() { $test = new TestHandler(); - $handler = new FilterHandler($test, Logger::DEBUG, Logger::EMERGENCY); + $handler = new FilterHandler($test, Level::Debug, Level::Emergency); $handler->pushProcessor( function ($record) { $record->extra['foo'] = true; @@ -115,7 +116,7 @@ function ($record) { return $record; } ); - $handler->handle($this->getRecord(Logger::WARNING)); + $handler->handle($this->getRecord(Level::Warning)); $this->assertTrue($test->hasWarningRecords()); $records = $test->getRecords(); $this->assertTrue($records[0]['extra']['foo']); @@ -128,13 +129,13 @@ public function testHandleRespectsBubble() { $test = new TestHandler(); - $handler = new FilterHandler($test, Logger::INFO, Logger::NOTICE, false); - $this->assertTrue($handler->handle($this->getRecord(Logger::INFO))); - $this->assertFalse($handler->handle($this->getRecord(Logger::WARNING))); + $handler = new FilterHandler($test, Level::Info, Level::Notice, false); + $this->assertTrue($handler->handle($this->getRecord(Level::Info))); + $this->assertFalse($handler->handle($this->getRecord(Level::Warning))); - $handler = new FilterHandler($test, Logger::INFO, Logger::NOTICE, true); - $this->assertFalse($handler->handle($this->getRecord(Logger::INFO))); - $this->assertFalse($handler->handle($this->getRecord(Logger::WARNING))); + $handler = new FilterHandler($test, Level::Info, Level::Notice, true); + $this->assertFalse($handler->handle($this->getRecord(Level::Info))); + $this->assertFalse($handler->handle($this->getRecord(Level::Warning))); } /** @@ -147,12 +148,12 @@ public function testHandleWithCallback() function ($record, $handler) use ($test) { return $test; }, - Logger::INFO, - Logger::NOTICE, + Level::Info, + Level::Notice, false ); - $handler->handle($this->getRecord(Logger::DEBUG)); - $handler->handle($this->getRecord(Logger::INFO)); + $handler->handle($this->getRecord(Level::Debug)); + $handler->handle($this->getRecord(Level::Info)); $this->assertFalse($test->hasDebugRecords()); $this->assertTrue($test->hasInfoRecords()); } @@ -170,7 +171,7 @@ function ($record, $handler) { $this->expectException(\RuntimeException::class); - $handler->handle($this->getRecord(Logger::WARNING)); + $handler->handle($this->getRecord(Level::Warning)); } public function testHandleEmptyBatch() @@ -188,12 +189,12 @@ public function testHandleEmptyBatch() public function testResetTestHandler() { $test = new TestHandler(); - $handler = new FilterHandler($test, [Logger::INFO, Logger::ERROR]); + $handler = new FilterHandler($test, [Level::Info, Level::Error]); - $handler->handle($this->getRecord(Logger::INFO)); + $handler->handle($this->getRecord(Level::Info)); $this->assertTrue($test->hasInfoRecords()); - $handler->handle($this->getRecord(Logger::ERROR)); + $handler->handle($this->getRecord(Level::Error)); $this->assertTrue($test->hasErrorRecords()); $handler->reset(); diff --git a/tests/Monolog/Handler/FingersCrossedHandlerTest.php b/tests/Monolog/Handler/FingersCrossedHandlerTest.php index 8847a16d8..702a5f081 100644 --- a/tests/Monolog/Handler/FingersCrossedHandlerTest.php +++ b/tests/Monolog/Handler/FingersCrossedHandlerTest.php @@ -11,8 +11,8 @@ namespace Monolog\Handler; +use Monolog\Level; use Monolog\Test\TestCase; -use Monolog\Logger; use Monolog\Handler\FingersCrossed\ErrorLevelActivationStrategy; use Monolog\Handler\FingersCrossed\ChannelLevelActivationStrategy; use Psr\Log\LogLevel; @@ -28,11 +28,11 @@ public function testHandleBuffers() { $test = new TestHandler(); $handler = new FingersCrossedHandler($test); - $handler->handle($this->getRecord(Logger::DEBUG)); - $handler->handle($this->getRecord(Logger::INFO)); + $handler->handle($this->getRecord(Level::Debug)); + $handler->handle($this->getRecord(Level::Info)); $this->assertFalse($test->hasDebugRecords()); $this->assertFalse($test->hasInfoRecords()); - $handler->handle($this->getRecord(Logger::WARNING)); + $handler->handle($this->getRecord(Level::Warning)); $handler->close(); $this->assertTrue($test->hasInfoRecords()); $this->assertCount(3, $test->getRecords()); @@ -46,8 +46,8 @@ public function testHandleStopsBufferingAfterTrigger() { $test = new TestHandler(); $handler = new FingersCrossedHandler($test); - $handler->handle($this->getRecord(Logger::WARNING)); - $handler->handle($this->getRecord(Logger::DEBUG)); + $handler->handle($this->getRecord(Level::Warning)); + $handler->handle($this->getRecord(Level::Debug)); $handler->close(); $this->assertTrue($test->hasWarningRecords()); $this->assertTrue($test->hasDebugRecords()); @@ -63,10 +63,10 @@ public function testHandleResetBufferingAfterReset() $test = new TestHandler(); $test->setSkipReset(true); $handler = new FingersCrossedHandler($test); - $handler->handle($this->getRecord(Logger::WARNING)); - $handler->handle($this->getRecord(Logger::DEBUG)); + $handler->handle($this->getRecord(Level::Warning)); + $handler->handle($this->getRecord(Level::Debug)); $handler->reset(); - $handler->handle($this->getRecord(Logger::INFO)); + $handler->handle($this->getRecord(Level::Info)); $handler->close(); $this->assertTrue($test->hasWarningRecords()); $this->assertTrue($test->hasDebugRecords()); @@ -80,10 +80,10 @@ public function testHandleResetBufferingAfterReset() public function testHandleResetBufferingAfterBeingTriggeredWhenStopBufferingIsDisabled() { $test = new TestHandler(); - $handler = new FingersCrossedHandler($test, Logger::WARNING, 0, false, false); - $handler->handle($this->getRecord(Logger::DEBUG)); - $handler->handle($this->getRecord(Logger::WARNING)); - $handler->handle($this->getRecord(Logger::INFO)); + $handler = new FingersCrossedHandler($test, Level::Warning, 0, false, false); + $handler->handle($this->getRecord(Level::Debug)); + $handler->handle($this->getRecord(Level::Warning)); + $handler->handle($this->getRecord(Level::Info)); $handler->close(); $this->assertTrue($test->hasWarningRecords()); $this->assertTrue($test->hasDebugRecords()); @@ -97,11 +97,11 @@ public function testHandleResetBufferingAfterBeingTriggeredWhenStopBufferingIsDi public function testHandleBufferLimit() { $test = new TestHandler(); - $handler = new FingersCrossedHandler($test, Logger::WARNING, 2); - $handler->handle($this->getRecord(Logger::DEBUG)); - $handler->handle($this->getRecord(Logger::DEBUG)); - $handler->handle($this->getRecord(Logger::INFO)); - $handler->handle($this->getRecord(Logger::WARNING)); + $handler = new FingersCrossedHandler($test, Level::Warning, 2); + $handler->handle($this->getRecord(Level::Debug)); + $handler->handle($this->getRecord(Level::Debug)); + $handler->handle($this->getRecord(Level::Info)); + $handler->handle($this->getRecord(Level::Warning)); $this->assertTrue($test->hasWarningRecords()); $this->assertTrue($test->hasInfoRecords()); $this->assertFalse($test->hasDebugRecords()); @@ -117,11 +117,11 @@ public function testHandleWithCallback() $handler = new FingersCrossedHandler(function ($record, $handler) use ($test) { return $test; }); - $handler->handle($this->getRecord(Logger::DEBUG)); - $handler->handle($this->getRecord(Logger::INFO)); + $handler->handle($this->getRecord(Level::Debug)); + $handler->handle($this->getRecord(Level::Info)); $this->assertFalse($test->hasDebugRecords()); $this->assertFalse($test->hasInfoRecords()); - $handler->handle($this->getRecord(Logger::WARNING)); + $handler->handle($this->getRecord(Level::Warning)); $this->assertTrue($test->hasInfoRecords()); $this->assertCount(3, $test->getRecords()); } @@ -138,7 +138,7 @@ public function testHandleWithBadCallbackThrowsException() $this->expectException(\RuntimeException::class); - $handler->handle($this->getRecord(Logger::WARNING)); + $handler->handle($this->getRecord(Level::Warning)); } /** @@ -147,8 +147,8 @@ public function testHandleWithBadCallbackThrowsException() public function testIsHandlingAlways() { $test = new TestHandler(); - $handler = new FingersCrossedHandler($test, Logger::ERROR); - $this->assertTrue($handler->isHandling($this->getRecord(Logger::DEBUG))); + $handler = new FingersCrossedHandler($test, Level::Error); + $this->assertTrue($handler->isHandling($this->getRecord(Level::Debug))); } /** @@ -159,10 +159,10 @@ public function testIsHandlingAlways() public function testErrorLevelActivationStrategy() { $test = new TestHandler(); - $handler = new FingersCrossedHandler($test, new ErrorLevelActivationStrategy(Logger::WARNING)); - $handler->handle($this->getRecord(Logger::DEBUG)); + $handler = new FingersCrossedHandler($test, new ErrorLevelActivationStrategy(Level::Warning)); + $handler->handle($this->getRecord(Level::Debug)); $this->assertFalse($test->hasDebugRecords()); - $handler->handle($this->getRecord(Logger::WARNING)); + $handler->handle($this->getRecord(Level::Warning)); $this->assertTrue($test->hasDebugRecords()); $this->assertTrue($test->hasWarningRecords()); } @@ -176,9 +176,9 @@ public function testErrorLevelActivationStrategyWithPsrLevel() { $test = new TestHandler(); $handler = new FingersCrossedHandler($test, new ErrorLevelActivationStrategy('warning')); - $handler->handle($this->getRecord(Logger::DEBUG)); + $handler->handle($this->getRecord(Level::Debug)); $this->assertFalse($test->hasDebugRecords()); - $handler->handle($this->getRecord(Logger::WARNING)); + $handler->handle($this->getRecord(Level::Warning)); $this->assertTrue($test->hasDebugRecords()); $this->assertTrue($test->hasWarningRecords()); } @@ -191,11 +191,11 @@ public function testOverrideActivationStrategy() { $test = new TestHandler(); $handler = new FingersCrossedHandler($test, new ErrorLevelActivationStrategy('warning')); - $handler->handle($this->getRecord(Logger::DEBUG)); + $handler->handle($this->getRecord(Level::Debug)); $this->assertFalse($test->hasDebugRecords()); $handler->activate(); $this->assertTrue($test->hasDebugRecords()); - $handler->handle($this->getRecord(Logger::INFO)); + $handler->handle($this->getRecord(Level::Info)); $this->assertTrue($test->hasInfoRecords()); } @@ -206,10 +206,10 @@ public function testOverrideActivationStrategy() public function testChannelLevelActivationStrategy() { $test = new TestHandler(); - $handler = new FingersCrossedHandler($test, new ChannelLevelActivationStrategy(Logger::ERROR, ['othertest' => Logger::DEBUG])); - $handler->handle($this->getRecord(Logger::WARNING)); + $handler = new FingersCrossedHandler($test, new ChannelLevelActivationStrategy(Level::Error, ['othertest' => Level::Debug])); + $handler->handle($this->getRecord(Level::Warning)); $this->assertFalse($test->hasWarningRecords()); - $record = $this->getRecord(Logger::DEBUG, channel: 'othertest'); + $record = $this->getRecord(Level::Debug, channel: 'othertest'); $handler->handle($record); $this->assertTrue($test->hasDebugRecords()); $this->assertTrue($test->hasWarningRecords()); @@ -223,9 +223,9 @@ public function testChannelLevelActivationStrategyWithPsrLevels() { $test = new TestHandler(); $handler = new FingersCrossedHandler($test, new ChannelLevelActivationStrategy('error', ['othertest' => 'debug'])); - $handler->handle($this->getRecord(Logger::WARNING)); + $handler->handle($this->getRecord(Level::Warning)); $this->assertFalse($test->hasWarningRecords()); - $record = $this->getRecord(Logger::DEBUG, channel: 'othertest'); + $record = $this->getRecord(Level::Debug, channel: 'othertest'); $handler->handle($record); $this->assertTrue($test->hasDebugRecords()); $this->assertTrue($test->hasWarningRecords()); @@ -238,13 +238,13 @@ public function testChannelLevelActivationStrategyWithPsrLevels() public function testHandleUsesProcessors() { $test = new TestHandler(); - $handler = new FingersCrossedHandler($test, Logger::INFO); + $handler = new FingersCrossedHandler($test, Level::Info); $handler->pushProcessor(function ($record) { $record->extra['foo'] = true; return $record; }); - $handler->handle($this->getRecord(Logger::WARNING)); + $handler->handle($this->getRecord(Level::Warning)); $this->assertTrue($test->hasWarningRecords()); $records = $test->getRecords(); $this->assertTrue($records[0]['extra']['foo']); @@ -256,9 +256,9 @@ public function testHandleUsesProcessors() public function testPassthruOnClose() { $test = new TestHandler(); - $handler = new FingersCrossedHandler($test, new ErrorLevelActivationStrategy(Logger::WARNING), 0, true, true, Logger::INFO); - $handler->handle($this->getRecord(Logger::DEBUG)); - $handler->handle($this->getRecord(Logger::INFO)); + $handler = new FingersCrossedHandler($test, new ErrorLevelActivationStrategy(Level::Warning), 0, true, true, Level::Info); + $handler->handle($this->getRecord(Level::Debug)); + $handler->handle($this->getRecord(Level::Info)); $handler->close(); $this->assertFalse($test->hasDebugRecords()); $this->assertTrue($test->hasInfoRecords()); @@ -270,9 +270,9 @@ public function testPassthruOnClose() public function testPsrLevelPassthruOnClose() { $test = new TestHandler(); - $handler = new FingersCrossedHandler($test, new ErrorLevelActivationStrategy(Logger::WARNING), 0, true, true, LogLevel::INFO); - $handler->handle($this->getRecord(Logger::DEBUG)); - $handler->handle($this->getRecord(Logger::INFO)); + $handler = new FingersCrossedHandler($test, new ErrorLevelActivationStrategy(Level::Warning), 0, true, true, LogLevel::INFO); + $handler->handle($this->getRecord(Level::Debug)); + $handler->handle($this->getRecord(Level::Info)); $handler->close(); $this->assertFalse($test->hasDebugRecords()); $this->assertTrue($test->hasInfoRecords()); diff --git a/tests/Monolog/Handler/FirePHPHandlerTest.php b/tests/Monolog/Handler/FirePHPHandlerTest.php index cd8fa1bec..fd28b95a8 100644 --- a/tests/Monolog/Handler/FirePHPHandlerTest.php +++ b/tests/Monolog/Handler/FirePHPHandlerTest.php @@ -12,7 +12,7 @@ namespace Monolog\Handler; use Monolog\Test\TestCase; -use Monolog\Logger; +use Monolog\Level; /** * @covers Monolog\Handler\FirePHPHandler @@ -29,8 +29,8 @@ public function testHeaders() { $handler = new TestFirePHPHandler; $handler->setFormatter($this->getIdentityFormatter()); - $handler->handle($this->getRecord(Logger::DEBUG)); - $handler->handle($this->getRecord(Logger::WARNING)); + $handler->handle($this->getRecord(Level::Debug)); + $handler->handle($this->getRecord(Level::Warning)); $expected = [ 'X-Wf-Protocol-1' => 'http://meta.wildfirehq.org/Protocol/JsonStream/0.2', @@ -47,13 +47,13 @@ public function testConcurrentHandlers() { $handler = new TestFirePHPHandler; $handler->setFormatter($this->getIdentityFormatter()); - $handler->handle($this->getRecord(Logger::DEBUG)); - $handler->handle($this->getRecord(Logger::WARNING)); + $handler->handle($this->getRecord(Level::Debug)); + $handler->handle($this->getRecord(Level::Warning)); $handler2 = new TestFirePHPHandler; $handler2->setFormatter($this->getIdentityFormatter()); - $handler2->handle($this->getRecord(Logger::DEBUG)); - $handler2->handle($this->getRecord(Logger::WARNING)); + $handler2->handle($this->getRecord(Level::Debug)); + $handler2->handle($this->getRecord(Level::Warning)); $expected = [ 'X-Wf-Protocol-1' => 'http://meta.wildfirehq.org/Protocol/JsonStream/0.2', diff --git a/tests/Monolog/Handler/FleepHookHandlerTest.php b/tests/Monolog/Handler/FleepHookHandlerTest.php index 029d05081..4f865526a 100644 --- a/tests/Monolog/Handler/FleepHookHandlerTest.php +++ b/tests/Monolog/Handler/FleepHookHandlerTest.php @@ -12,7 +12,7 @@ namespace Monolog\Handler; use Monolog\Formatter\LineFormatter; -use Monolog\Logger; +use Monolog\Level; use Monolog\Test\TestCase; /** @@ -47,7 +47,7 @@ public function setUp(): void */ public function testConstructorSetsExpectedDefaults() { - $this->assertEquals(Logger::DEBUG, $this->handler->getLevel()); + $this->assertEquals(Level::Debug, $this->handler->getLevel()); $this->assertEquals(true, $this->handler->getBubble()); } @@ -56,7 +56,7 @@ public function testConstructorSetsExpectedDefaults() */ public function testHandlerUsesLineFormatterWhichIgnoresEmptyArrays() { - $record = $this->getRecord(Logger::DEBUG, 'msg'); + $record = $this->getRecord(Level::Debug, 'msg'); $expectedFormatter = new LineFormatter(null, null, true, true); $expected = $expectedFormatter->format($record); diff --git a/tests/Monolog/Handler/FlowdockHandlerTest.php b/tests/Monolog/Handler/FlowdockHandlerTest.php index c7612e331..102430988 100644 --- a/tests/Monolog/Handler/FlowdockHandlerTest.php +++ b/tests/Monolog/Handler/FlowdockHandlerTest.php @@ -13,7 +13,7 @@ use Monolog\Formatter\FlowdockFormatter; use Monolog\Test\TestCase; -use Monolog\Logger; +use Monolog\Level; /** * @author Dominik Liebler @@ -41,7 +41,7 @@ public function setUp(): void public function testWriteHeader() { $this->createHandler(); - $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1')); + $this->handler->handle($this->getRecord(Level::Critical, 'test1')); fseek($this->res, 0); $content = fread($this->res, 1024); @@ -61,7 +61,7 @@ public function testWriteContent($content) private function createHandler($token = 'myToken') { - $constructorArgs = [$token, Logger::DEBUG]; + $constructorArgs = [$token, Level::Debug]; $this->res = fopen('php://memory', 'a'); $this->handler = $this->getMockBuilder('Monolog\Handler\FlowdockHandler') ->setConstructorArgs($constructorArgs) diff --git a/tests/Monolog/Handler/GelfHandlerTest.php b/tests/Monolog/Handler/GelfHandlerTest.php index 931171402..918f53248 100644 --- a/tests/Monolog/Handler/GelfHandlerTest.php +++ b/tests/Monolog/Handler/GelfHandlerTest.php @@ -13,7 +13,7 @@ use Gelf\Message; use Monolog\Test\TestCase; -use Monolog\Logger; +use Monolog\Level; use Monolog\Formatter\GelfMessageFormatter; class GelfHandlerTest extends TestCase @@ -51,7 +51,7 @@ protected function getMessagePublisher() public function testDebug() { - $record = $this->getRecord(Logger::DEBUG, "A test debug message"); + $record = $this->getRecord(Level::Debug, "A test debug message"); $expectedMessage = new Message(); $expectedMessage ->setLevel(7) @@ -72,7 +72,7 @@ public function testDebug() public function testWarning() { - $record = $this->getRecord(Logger::WARNING, "A test warning message"); + $record = $this->getRecord(Level::Warning, "A test warning message"); $expectedMessage = new Message(); $expectedMessage ->setLevel(4) @@ -94,7 +94,7 @@ public function testWarning() public function testInjectedGelfMessageFormatter() { $record = $this->getRecord( - Logger::WARNING, + Level::Warning, "A test warning message", extra: ['blarg' => 'yep'], context: ['from' => 'logger'], diff --git a/tests/Monolog/Handler/GroupHandlerTest.php b/tests/Monolog/Handler/GroupHandlerTest.php index 97680db30..0c734dee0 100644 --- a/tests/Monolog/Handler/GroupHandlerTest.php +++ b/tests/Monolog/Handler/GroupHandlerTest.php @@ -12,7 +12,7 @@ namespace Monolog\Handler; use Monolog\Test\TestCase; -use Monolog\Logger; +use Monolog\Level; class GroupHandlerTest extends TestCase { @@ -34,8 +34,8 @@ public function testHandle() { $testHandlers = [new TestHandler(), new TestHandler()]; $handler = new GroupHandler($testHandlers); - $handler->handle($this->getRecord(Logger::DEBUG)); - $handler->handle($this->getRecord(Logger::INFO)); + $handler->handle($this->getRecord(Level::Debug)); + $handler->handle($this->getRecord(Level::Info)); foreach ($testHandlers as $test) { $this->assertTrue($test->hasDebugRecords()); $this->assertTrue($test->hasInfoRecords()); @@ -50,7 +50,7 @@ public function testHandleBatch() { $testHandlers = [new TestHandler(), new TestHandler()]; $handler = new GroupHandler($testHandlers); - $handler->handleBatch([$this->getRecord(Logger::DEBUG), $this->getRecord(Logger::INFO)]); + $handler->handleBatch([$this->getRecord(Level::Debug), $this->getRecord(Level::Info)]); foreach ($testHandlers as $test) { $this->assertTrue($test->hasDebugRecords()); $this->assertTrue($test->hasInfoRecords()); @@ -63,11 +63,11 @@ public function testHandleBatch() */ public function testIsHandling() { - $testHandlers = [new TestHandler(Logger::ERROR), new TestHandler(Logger::WARNING)]; + $testHandlers = [new TestHandler(Level::Error), new TestHandler(Level::Warning)]; $handler = new GroupHandler($testHandlers); - $this->assertTrue($handler->isHandling($this->getRecord(Logger::ERROR))); - $this->assertTrue($handler->isHandling($this->getRecord(Logger::WARNING))); - $this->assertFalse($handler->isHandling($this->getRecord(Logger::DEBUG))); + $this->assertTrue($handler->isHandling($this->getRecord(Level::Error))); + $this->assertTrue($handler->isHandling($this->getRecord(Level::Warning))); + $this->assertFalse($handler->isHandling($this->getRecord(Level::Debug))); } /** @@ -82,7 +82,7 @@ public function testHandleUsesProcessors() return $record; }); - $handler->handle($this->getRecord(Logger::WARNING)); + $handler->handle($this->getRecord(Level::Warning)); $this->assertTrue($test->hasWarningRecords()); $records = $test->getRecords(); $this->assertTrue($records[0]['extra']['foo']); @@ -105,7 +105,7 @@ public function testHandleBatchUsesProcessors() return $record; }); - $handler->handleBatch([$this->getRecord(Logger::DEBUG), $this->getRecord(Logger::INFO)]); + $handler->handleBatch([$this->getRecord(Level::Debug), $this->getRecord(Level::Info)]); foreach ($testHandlers as $test) { $this->assertTrue($test->hasDebugRecords()); $this->assertTrue($test->hasInfoRecords()); diff --git a/tests/Monolog/Handler/InsightOpsHandlerTest.php b/tests/Monolog/Handler/InsightOpsHandlerTest.php index bbb1ff474..8663d7779 100644 --- a/tests/Monolog/Handler/InsightOpsHandlerTest.php +++ b/tests/Monolog/Handler/InsightOpsHandlerTest.php @@ -12,7 +12,7 @@ namespace Monolog\Handler; use Monolog\Test\TestCase; -use Monolog\Logger; +use Monolog\Level; /** * @author Robert Kaufmann III @@ -33,7 +33,7 @@ class InsightOpsHandlerTest extends TestCase public function testWriteContent() { $this->createHandler(); - $this->handler->handle($this->getRecord(Logger::CRITICAL, 'Critical write test')); + $this->handler->handle($this->getRecord(Level::Critical, 'Critical write test')); fseek($this->resource, 0); $content = fread($this->resource, 1024); @@ -55,7 +55,7 @@ public function testWriteBatchContent() private function createHandler() { $useSSL = extension_loaded('openssl'); - $args = array('testToken', 'us', $useSSL, Logger::DEBUG, true); + $args = array('testToken', 'us', $useSSL, Level::Debug, true); $this->resource = fopen('php://memory', 'a'); $this->handler = $this->getMockBuilder(InsightOpsHandler::class) ->onlyMethods(array('fsockopen', 'streamSetTimeout', 'closeSocket')) diff --git a/tests/Monolog/Handler/LogEntriesHandlerTest.php b/tests/Monolog/Handler/LogEntriesHandlerTest.php index 1dcd64529..2f49fa912 100644 --- a/tests/Monolog/Handler/LogEntriesHandlerTest.php +++ b/tests/Monolog/Handler/LogEntriesHandlerTest.php @@ -12,7 +12,7 @@ namespace Monolog\Handler; use Monolog\Test\TestCase; -use Monolog\Logger; +use Monolog\Level; /** * @author Robert Kaufmann III @@ -32,7 +32,7 @@ class LogEntriesHandlerTest extends TestCase public function testWriteContent() { $this->createHandler(); - $this->handler->handle($this->getRecord(Logger::CRITICAL, 'Critical write test')); + $this->handler->handle($this->getRecord(Level::Critical, 'Critical write test')); fseek($this->res, 0); $content = fread($this->res, 1024); @@ -59,7 +59,7 @@ public function testWriteBatchContent() private function createHandler() { $useSSL = extension_loaded('openssl'); - $args = ['testToken', $useSSL, Logger::DEBUG, true]; + $args = ['testToken', $useSSL, Level::Debug, true]; $this->res = fopen('php://memory', 'a'); $this->handler = $this->getMockBuilder('Monolog\Handler\LogEntriesHandler') ->setConstructorArgs($args) diff --git a/tests/Monolog/Handler/LogmaticHandlerTest.php b/tests/Monolog/Handler/LogmaticHandlerTest.php index d6c781343..953ca14b8 100644 --- a/tests/Monolog/Handler/LogmaticHandlerTest.php +++ b/tests/Monolog/Handler/LogmaticHandlerTest.php @@ -12,7 +12,7 @@ namespace Monolog\Handler; use Monolog\Test\TestCase; -use Monolog\Logger; +use Monolog\Level; /** * @author Julien Breux @@ -32,7 +32,7 @@ class LogmaticHandlerTest extends TestCase public function testWriteContent() { $this->createHandler(); - $this->handler->handle($this->getRecord(Logger::CRITICAL, 'Critical write test')); + $this->handler->handle($this->getRecord(Level::Critical, 'Critical write test')); fseek($this->res, 0); $content = fread($this->res, 1024); @@ -59,7 +59,7 @@ public function testWriteBatchContent() private function createHandler() { $useSSL = extension_loaded('openssl'); - $args = ['testToken', 'testHostname', 'testAppname', $useSSL, Logger::DEBUG, true]; + $args = ['testToken', 'testHostname', 'testAppname', $useSSL, Level::Debug, true]; $this->res = fopen('php://memory', 'a'); $this->handler = $this->getMockBuilder('Monolog\Handler\LogmaticHandler') ->setConstructorArgs($args) diff --git a/tests/Monolog/Handler/MailHandlerTest.php b/tests/Monolog/Handler/MailHandlerTest.php index d85a70771..3c4a5805a 100644 --- a/tests/Monolog/Handler/MailHandlerTest.php +++ b/tests/Monolog/Handler/MailHandlerTest.php @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Monolog\Test\TestCase; class MailHandlerTest extends TestCase @@ -42,15 +42,15 @@ public function testHandleBatch() public function testHandleBatchNotSendsMailIfMessagesAreBelowLevel() { $records = [ - $this->getRecord(Logger::DEBUG, 'debug message 1'), - $this->getRecord(Logger::DEBUG, 'debug message 2'), - $this->getRecord(Logger::INFO, 'information'), + $this->getRecord(Level::Debug, 'debug message 1'), + $this->getRecord(Level::Debug, 'debug message 2'), + $this->getRecord(Level::Info, 'information'), ]; $handler = $this->getMockForAbstractClass('Monolog\\Handler\\MailHandler'); $handler->expects($this->never()) ->method('send'); - $handler->setLevel(Logger::ERROR); + $handler->setLevel(Level::Error); $handler->handleBatch($records); } diff --git a/tests/Monolog/Handler/NativeMailerHandlerTest.php b/tests/Monolog/Handler/NativeMailerHandlerTest.php index 62f79b20e..25564e9f1 100644 --- a/tests/Monolog/Handler/NativeMailerHandlerTest.php +++ b/tests/Monolog/Handler/NativeMailerHandlerTest.php @@ -11,8 +11,8 @@ namespace Monolog\Handler; +use Monolog\Level; use Monolog\Test\TestCase; -use Monolog\Logger; function mail($to, $subject, $message, $additional_headers = null, $additional_parameters = null) { @@ -79,7 +79,7 @@ public function testSend() $this->assertEmpty($GLOBALS['mail']); // non-empty batch - $mailer->handle($this->getRecord(Logger::ERROR, "Foo\nBar\r\n\r\nBaz")); + $mailer->handle($this->getRecord(Level::Error, "Foo\nBar\r\n\r\nBaz")); $this->assertNotEmpty($GLOBALS['mail']); $this->assertIsArray($GLOBALS['mail']); $this->assertArrayHasKey('0', $GLOBALS['mail']); @@ -95,7 +95,7 @@ public function testSend() public function testMessageSubjectFormatting() { $mailer = new NativeMailerHandler('to@example.org', 'Alert: %level_name% %message%', 'from@example.org'); - $mailer->handle($this->getRecord(Logger::ERROR, "Foo\nBar\r\n\r\nBaz")); + $mailer->handle($this->getRecord(Level::Error, "Foo\nBar\r\n\r\nBaz")); $this->assertNotEmpty($GLOBALS['mail']); $this->assertIsArray($GLOBALS['mail']); $this->assertArrayHasKey('0', $GLOBALS['mail']); diff --git a/tests/Monolog/Handler/NewRelicHandlerTest.php b/tests/Monolog/Handler/NewRelicHandlerTest.php index b60f0b781..17d7e833d 100644 --- a/tests/Monolog/Handler/NewRelicHandlerTest.php +++ b/tests/Monolog/Handler/NewRelicHandlerTest.php @@ -13,7 +13,7 @@ use Monolog\Formatter\LineFormatter; use Monolog\Test\TestCase; -use Monolog\Logger; +use Monolog\Level; class NewRelicHandlerTest extends TestCase { @@ -34,27 +34,27 @@ public function testThehandlerThrowsAnExceptionIfTheNRExtensionIsNotLoaded() $this->expectException(MissingExtensionException::class); - $handler->handle($this->getRecord(Logger::ERROR)); + $handler->handle($this->getRecord(Level::Error)); } public function testThehandlerCanHandleTheRecord() { $handler = new StubNewRelicHandler(); - $handler->handle($this->getRecord(Logger::ERROR)); + $handler->handle($this->getRecord(Level::Error)); } public function testThehandlerCanAddContextParamsToTheNewRelicTrace() { $handler = new StubNewRelicHandler(); - $handler->handle($this->getRecord(Logger::ERROR, 'log message', ['a' => 'b'])); + $handler->handle($this->getRecord(Level::Error, 'log message', ['a' => 'b'])); $this->assertEquals(['context_a' => 'b'], self::$customParameters); } public function testThehandlerCanAddExplodedContextParamsToTheNewRelicTrace() { - $handler = new StubNewRelicHandler(Logger::ERROR, true, self::$appname, true); + $handler = new StubNewRelicHandler(Level::Error, true, self::$appname, true); $handler->handle($this->getRecord( - Logger::ERROR, + Level::Error, 'log message', ['a' => ['key1' => 'value1', 'key2' => 'value2']] )); @@ -66,7 +66,7 @@ public function testThehandlerCanAddExplodedContextParamsToTheNewRelicTrace() public function testThehandlerCanAddExtraParamsToTheNewRelicTrace() { - $record = $this->getRecord(Logger::ERROR, 'log message'); + $record = $this->getRecord(Level::Error, 'log message'); $record->extra = ['c' => 'd']; $handler = new StubNewRelicHandler(); @@ -77,10 +77,10 @@ public function testThehandlerCanAddExtraParamsToTheNewRelicTrace() public function testThehandlerCanAddExplodedExtraParamsToTheNewRelicTrace() { - $record = $this->getRecord(Logger::ERROR, 'log message'); + $record = $this->getRecord(Level::Error, 'log message'); $record->extra = ['c' => ['key1' => 'value1', 'key2' => 'value2']]; - $handler = new StubNewRelicHandler(Logger::ERROR, true, self::$appname, true); + $handler = new StubNewRelicHandler(Level::Error, true, self::$appname, true); $handler->handle($record); $this->assertEquals( @@ -91,7 +91,7 @@ public function testThehandlerCanAddExplodedExtraParamsToTheNewRelicTrace() public function testThehandlerCanAddExtraContextAndParamsToTheNewRelicTrace() { - $record = $this->getRecord(Logger::ERROR, 'log message', ['a' => 'b']); + $record = $this->getRecord(Level::Error, 'log message', ['a' => 'b']); $record->extra = ['c' => 'd']; $handler = new StubNewRelicHandler(); @@ -109,29 +109,29 @@ public function testThehandlerCanHandleTheRecordsFormattedUsingTheLineFormatter( { $handler = new StubNewRelicHandler(); $handler->setFormatter(new LineFormatter()); - $handler->handle($this->getRecord(Logger::ERROR)); + $handler->handle($this->getRecord(Level::Error)); } public function testTheAppNameIsNullByDefault() { $handler = new StubNewRelicHandler(); - $handler->handle($this->getRecord(Logger::ERROR, 'log message')); + $handler->handle($this->getRecord(Level::Error, 'log message')); $this->assertEquals(null, self::$appname); } public function testTheAppNameCanBeInjectedFromtheConstructor() { - $handler = new StubNewRelicHandler(Logger::DEBUG, false, 'myAppName'); - $handler->handle($this->getRecord(Logger::ERROR, 'log message')); + $handler = new StubNewRelicHandler(Level::Debug, false, 'myAppName'); + $handler->handle($this->getRecord(Level::Error, 'log message')); $this->assertEquals('myAppName', self::$appname); } public function testTheAppNameCanBeOverriddenFromEachLog() { - $handler = new StubNewRelicHandler(Logger::DEBUG, false, 'myAppName'); - $handler->handle($this->getRecord(Logger::ERROR, 'log message', ['appname' => 'logAppName'])); + $handler = new StubNewRelicHandler(Level::Debug, false, 'myAppName'); + $handler->handle($this->getRecord(Level::Error, 'log message', ['appname' => 'logAppName'])); $this->assertEquals('logAppName', self::$appname); } @@ -139,23 +139,23 @@ public function testTheAppNameCanBeOverriddenFromEachLog() public function testTheTransactionNameIsNullByDefault() { $handler = new StubNewRelicHandler(); - $handler->handle($this->getRecord(Logger::ERROR, 'log message')); + $handler->handle($this->getRecord(Level::Error, 'log message')); $this->assertEquals(null, self::$transactionName); } public function testTheTransactionNameCanBeInjectedFromTheConstructor() { - $handler = new StubNewRelicHandler(Logger::DEBUG, false, null, false, 'myTransaction'); - $handler->handle($this->getRecord(Logger::ERROR, 'log message')); + $handler = new StubNewRelicHandler(Level::Debug, false, null, false, 'myTransaction'); + $handler->handle($this->getRecord(Level::Error, 'log message')); $this->assertEquals('myTransaction', self::$transactionName); } public function testTheTransactionNameCanBeOverriddenFromEachLog() { - $handler = new StubNewRelicHandler(Logger::DEBUG, false, null, false, 'myTransaction'); - $handler->handle($this->getRecord(Logger::ERROR, 'log message', ['transaction_name' => 'logTransactName'])); + $handler = new StubNewRelicHandler(Level::Debug, false, null, false, 'myTransaction'); + $handler->handle($this->getRecord(Level::Error, 'log message', ['transaction_name' => 'logTransactName'])); $this->assertEquals('logTransactName', self::$transactionName); } diff --git a/tests/Monolog/Handler/NoopHandlerTest.php b/tests/Monolog/Handler/NoopHandlerTest.php index 768f5e30a..83cb6a2a7 100644 --- a/tests/Monolog/Handler/NoopHandlerTest.php +++ b/tests/Monolog/Handler/NoopHandlerTest.php @@ -11,8 +11,8 @@ namespace Monolog\Handler; +use Monolog\Level; use Monolog\Test\TestCase; -use Monolog\Logger; /** * @covers Monolog\Handler\NoopHandler::handle @@ -22,7 +22,7 @@ class NoopHandlerTest extends TestCase /** * @dataProvider logLevelsProvider */ - public function testIsHandling($level) + public function testIsHandling(Level $level) { $handler = new NoopHandler(); $this->assertTrue($handler->isHandling($this->getRecord($level))); @@ -31,7 +31,7 @@ public function testIsHandling($level) /** * @dataProvider logLevelsProvider */ - public function testHandle($level) + public function testHandle(Level $level) { $handler = new NoopHandler(); $this->assertFalse($handler->handle($this->getRecord($level))); @@ -40,10 +40,8 @@ public function testHandle($level) public function logLevelsProvider() { return array_map( - function ($level) { - return [$level]; - }, - array_values(Logger::getLevels()) + fn ($level) => [$level], + Level::cases() ); } } diff --git a/tests/Monolog/Handler/NullHandlerTest.php b/tests/Monolog/Handler/NullHandlerTest.php index b7e482bac..d6a80074a 100644 --- a/tests/Monolog/Handler/NullHandlerTest.php +++ b/tests/Monolog/Handler/NullHandlerTest.php @@ -12,7 +12,7 @@ namespace Monolog\Handler; use Monolog\Test\TestCase; -use Monolog\Logger; +use Monolog\Level; /** * @covers Monolog\Handler\NullHandler::handle @@ -27,7 +27,7 @@ public function testHandle() public function testHandleLowerLevelRecord() { - $handler = new NullHandler(Logger::WARNING); - $this->assertFalse($handler->handle($this->getRecord(Logger::DEBUG))); + $handler = new NullHandler(Level::Warning); + $this->assertFalse($handler->handle($this->getRecord(Level::Debug))); } } diff --git a/tests/Monolog/Handler/OverflowHandlerTest.php b/tests/Monolog/Handler/OverflowHandlerTest.php index c62f441ae..e50966f9d 100644 --- a/tests/Monolog/Handler/OverflowHandlerTest.php +++ b/tests/Monolog/Handler/OverflowHandlerTest.php @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Monolog\Test\TestCase; /** @@ -23,19 +23,19 @@ class OverflowHandlerTest extends TestCase public function testNotPassingRecordsBeneathLogLevel() { $testHandler = new TestHandler(); - $handler = new OverflowHandler($testHandler, [], Logger::INFO); - $handler->handle($this->getRecord(Logger::DEBUG)); + $handler = new OverflowHandler($testHandler, [], Level::Info); + $handler->handle($this->getRecord(Level::Debug)); $this->assertFalse($testHandler->hasDebugRecords()); } public function testPassThroughWithoutThreshold() { $testHandler = new TestHandler(); - $handler = new OverflowHandler($testHandler, [], Logger::INFO); + $handler = new OverflowHandler($testHandler, [], Level::Info); - $handler->handle($this->getRecord(Logger::INFO, 'Info 1')); - $handler->handle($this->getRecord(Logger::INFO, 'Info 2')); - $handler->handle($this->getRecord(Logger::WARNING, 'Warning 1')); + $handler->handle($this->getRecord(Level::Info, 'Info 1')); + $handler->handle($this->getRecord(Level::Info, 'Info 2')); + $handler->handle($this->getRecord(Level::Warning, 'Warning 1')); $this->assertTrue($testHandler->hasInfoThatContains('Info 1')); $this->assertTrue($testHandler->hasInfoThatContains('Info 2')); @@ -48,20 +48,20 @@ public function testPassThroughWithoutThreshold() public function testHoldingMessagesBeneathThreshold() { $testHandler = new TestHandler(); - $handler = new OverflowHandler($testHandler, [Logger::INFO => 3]); + $handler = new OverflowHandler($testHandler, [Level::Info->value => 3]); - $handler->handle($this->getRecord(Logger::DEBUG, 'debug 1')); - $handler->handle($this->getRecord(Logger::DEBUG, 'debug 2')); + $handler->handle($this->getRecord(Level::Debug, 'debug 1')); + $handler->handle($this->getRecord(Level::Debug, 'debug 2')); foreach (range(1, 3) as $i) { - $handler->handle($this->getRecord(Logger::INFO, 'info ' . $i)); + $handler->handle($this->getRecord(Level::Info, 'info ' . $i)); } $this->assertTrue($testHandler->hasDebugThatContains('debug 1')); $this->assertTrue($testHandler->hasDebugThatContains('debug 2')); $this->assertFalse($testHandler->hasInfoRecords()); - $handler->handle($this->getRecord(Logger::INFO, 'info 4')); + $handler->handle($this->getRecord(Level::Info, 'info 4')); foreach (range(1, 4) as $i) { $this->assertTrue($testHandler->hasInfoThatContains('info ' . $i)); @@ -74,33 +74,33 @@ public function testHoldingMessagesBeneathThreshold() public function testCombinedThresholds() { $testHandler = new TestHandler(); - $handler = new OverflowHandler($testHandler, [Logger::INFO => 5, Logger::WARNING => 10]); + $handler = new OverflowHandler($testHandler, [Level::Info->value => 5, Level::Warning->value => 10]); - $handler->handle($this->getRecord(Logger::DEBUG)); + $handler->handle($this->getRecord(Level::Debug)); foreach (range(1, 5) as $i) { - $handler->handle($this->getRecord(Logger::INFO, 'info ' . $i)); + $handler->handle($this->getRecord(Level::Info, 'info ' . $i)); } foreach (range(1, 10) as $i) { - $handler->handle($this->getRecord(Logger::WARNING, 'warning ' . $i)); + $handler->handle($this->getRecord(Level::Warning, 'warning ' . $i)); } // Only 1 DEBUG records $this->assertCount(1, $testHandler->getRecords()); - $handler->handle($this->getRecord(Logger::INFO, 'info final')); + $handler->handle($this->getRecord(Level::Info, 'info final')); // 1 DEBUG + 5 buffered INFO + 1 new INFO $this->assertCount(7, $testHandler->getRecords()); - $handler->handle($this->getRecord(Logger::WARNING, 'warning final')); + $handler->handle($this->getRecord(Level::Warning, 'warning final')); // 1 DEBUG + 6 INFO + 10 buffered WARNING + 1 new WARNING $this->assertCount(18, $testHandler->getRecords()); - $handler->handle($this->getRecord(Logger::INFO, 'Another info')); - $handler->handle($this->getRecord(Logger::WARNING, 'Anther warning')); + $handler->handle($this->getRecord(Level::Info, 'Another info')); + $handler->handle($this->getRecord(Level::Warning, 'Anther warning')); // 1 DEBUG + 6 INFO + 11 WARNING + 1 new INFO + 1 new WARNING $this->assertCount(20, $testHandler->getRecords()); diff --git a/tests/Monolog/Handler/PHPConsoleHandlerTest.php b/tests/Monolog/Handler/PHPConsoleHandlerTest.php index 98d8a4b2b..84dc911a5 100644 --- a/tests/Monolog/Handler/PHPConsoleHandlerTest.php +++ b/tests/Monolog/Handler/PHPConsoleHandlerTest.php @@ -13,6 +13,7 @@ use Exception; use Monolog\ErrorHandler; +use Monolog\Level; use Monolog\Logger; use Monolog\Test\TestCase; use PhpConsole\Connector; @@ -107,7 +108,7 @@ protected function getHandlerDefaultOption($name) return $options[$name]; } - protected function initLogger($handlerOptions = [], $level = Logger::DEBUG) + protected function initLogger($handlerOptions = [], $level = Level::Debug) { return new Logger('test', [ new PHPConsoleHandler($handlerOptions, $this->connector, $level), diff --git a/tests/Monolog/Handler/ProcessHandlerTest.php b/tests/Monolog/Handler/ProcessHandlerTest.php index 7a71c4d22..daa4ae55b 100644 --- a/tests/Monolog/Handler/ProcessHandlerTest.php +++ b/tests/Monolog/Handler/ProcessHandlerTest.php @@ -12,7 +12,7 @@ namespace Monolog\Handler; use Monolog\Test\TestCase; -use Monolog\Logger; +use Monolog\Level; class ProcessHandlerTest extends TestCase { @@ -51,8 +51,8 @@ public function testWriteOpensProcessAndWritesToStdInOfProcess() ->withConsecutive([$this->stringContains($fixtures[0])], [$this->stringContains($fixtures[1])]); /** @var ProcessHandler $handler */ - $handler->handle($this->getRecord(Logger::WARNING, $fixtures[0])); - $handler->handle($this->getRecord(Logger::ERROR, $fixtures[1])); + $handler->handle($this->getRecord(Level::Warning, $fixtures[0])); + $handler->handle($this->getRecord(Level::Error, $fixtures[1])); } /** @@ -78,7 +78,7 @@ public function invalidCommandProvider() public function testConstructWithInvalidCommandThrowsInvalidArgumentException($invalidCommand, $expectedExcep) { $this->expectException($expectedExcep); - new ProcessHandler($invalidCommand, Logger::DEBUG); + new ProcessHandler($invalidCommand, Level::Debug); } /** @@ -103,7 +103,7 @@ public function invalidCwdProvider() public function testConstructWithInvalidCwdThrowsInvalidArgumentException($invalidCwd, $expectedExcep) { $this->expectException($expectedExcep); - new ProcessHandler(self::DUMMY_COMMAND, Logger::DEBUG, true, $invalidCwd); + new ProcessHandler(self::DUMMY_COMMAND, Level::Debug, true, $invalidCwd); } /** @@ -112,7 +112,7 @@ public function testConstructWithInvalidCwdThrowsInvalidArgumentException($inval */ public function testConstructWithValidCwdWorks() { - $handler = new ProcessHandler(self::DUMMY_COMMAND, Logger::DEBUG, true, sys_get_temp_dir()); + $handler = new ProcessHandler(self::DUMMY_COMMAND, Level::Debug, true, sys_get_temp_dir()); $this->assertInstanceOf( 'Monolog\Handler\ProcessHandler', $handler, @@ -137,7 +137,7 @@ public function testStartupWithFailingToSelectErrorStreamThrowsUnexpectedValueEx $this->expectException(\UnexpectedValueException::class); /** @var ProcessHandler $handler */ - $handler->handle($this->getRecord(Logger::WARNING, 'stream failing, whoops')); + $handler->handle($this->getRecord(Level::Warning, 'stream failing, whoops')); } /** @@ -150,7 +150,7 @@ public function testStartupWithErrorsThrowsUnexpectedValueException() $this->expectException(\UnexpectedValueException::class); - $handler->handle($this->getRecord(Logger::WARNING, 'some warning in the house')); + $handler->handle($this->getRecord(Level::Warning, 'some warning in the house')); } /** @@ -171,7 +171,7 @@ public function testWritingWithErrorsOnStdOutOfProcessThrowsInvalidArgumentExcep $this->expectException(\UnexpectedValueException::class); /** @var ProcessHandler $handler */ - $handler->handle($this->getRecord(Logger::WARNING, 'some test stuff')); + $handler->handle($this->getRecord(Level::Warning, 'some test stuff')); } /** @@ -184,7 +184,7 @@ public function testCloseClosesProcess() $property->setAccessible(true); $handler = new ProcessHandler(self::DUMMY_COMMAND); - $handler->handle($this->getRecord(Logger::WARNING, '21 is only the half truth')); + $handler->handle($this->getRecord(Level::Warning, '21 is only the half truth')); $process = $property->getValue($handler); $this->assertTrue(is_resource($process), 'Process is not running although it should.'); diff --git a/tests/Monolog/Handler/PsrHandlerTest.php b/tests/Monolog/Handler/PsrHandlerTest.php index e3f30bfaa..e06aa20e9 100644 --- a/tests/Monolog/Handler/PsrHandlerTest.php +++ b/tests/Monolog/Handler/PsrHandlerTest.php @@ -11,8 +11,9 @@ namespace Monolog\Handler; +use Monolog\Level; +use Monolog\LevelName; use Monolog\Test\TestCase; -use Monolog\Logger; use Monolog\Formatter\LineFormatter; /** @@ -22,28 +23,24 @@ class PsrHandlerTest extends TestCase { public function logLevelProvider() { - $levels = []; - $monologLogger = new Logger(''); - - foreach ($monologLogger->getLevels() as $levelName => $level) { - $levels[] = [$levelName, $level]; - } - - return $levels; + return array_map( + fn(Level $level) => [$level->toLevelName(), $level], + Level::cases() + ); } /** * @dataProvider logLevelProvider */ - public function testHandlesAllLevels($levelName, $level) + public function testHandlesAllLevels(LevelName $levelName, Level $level) { - $message = 'Hello, world! ' . $level; - $context = ['foo' => 'bar', 'level' => $level]; + $message = 'Hello, world! ' . $level->value; + $context = ['foo' => 'bar', 'level' => $level->value]; $psrLogger = $this->createMock('Psr\Log\NullLogger'); $psrLogger->expects($this->once()) ->method('log') - ->with(strtolower($levelName), $message, $context); + ->with(strtolower($levelName->value), $message, $context); $handler = new PsrHandler($psrLogger); $handler->handle($this->getRecord($level, $message, context: $context)); @@ -53,13 +50,13 @@ public function testFormatter() { $message = 'Hello, world!'; $context = ['foo' => 'bar']; - $level = Logger::ERROR; - $levelName = 'error'; + $level = Level::Error; + $levelName = LevelName::Error; $psrLogger = $this->createMock('Psr\Log\NullLogger'); $psrLogger->expects($this->once()) ->method('log') - ->with(strtolower($levelName), 'dummy', $context); + ->with(strtolower($levelName->value), 'dummy', $context); $handler = new PsrHandler($psrLogger); $handler->setFormatter(new LineFormatter('dummy')); diff --git a/tests/Monolog/Handler/PushoverHandlerTest.php b/tests/Monolog/Handler/PushoverHandlerTest.php index b41ead546..7db7098e9 100644 --- a/tests/Monolog/Handler/PushoverHandlerTest.php +++ b/tests/Monolog/Handler/PushoverHandlerTest.php @@ -12,7 +12,7 @@ namespace Monolog\Handler; use Monolog\Test\TestCase; -use Monolog\Logger; +use Monolog\Level; /** * Almost all examples (expected header, titles, messages) taken from @@ -28,8 +28,8 @@ class PushoverHandlerTest extends TestCase public function testWriteHeader() { $this->createHandler(); - $this->handler->setHighPriorityLevel(Logger::EMERGENCY); // skip priority notifications - $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1')); + $this->handler->setHighPriorityLevel(Level::Emergency); // skip priority notifications + $this->handler->handle($this->getRecord(Level::Critical, 'test1')); fseek($this->res, 0); $content = fread($this->res, 1024); @@ -49,7 +49,7 @@ public function testWriteContent($content) public function testWriteWithComplexTitle() { $this->createHandler('myToken', 'myUser', 'Backup finished - SQL1'); - $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1')); + $this->handler->handle($this->getRecord(Level::Critical, 'test1')); fseek($this->res, 0); $content = fread($this->res, 1024); @@ -59,8 +59,8 @@ public function testWriteWithComplexTitle() public function testWriteWithComplexMessage() { $this->createHandler(); - $this->handler->setHighPriorityLevel(Logger::EMERGENCY); // skip priority notifications - $this->handler->handle($this->getRecord(Logger::CRITICAL, 'Backup of database "example" finished in 16 minutes.')); + $this->handler->setHighPriorityLevel(Level::Emergency); // skip priority notifications + $this->handler->handle($this->getRecord(Level::Critical, 'Backup of database "example" finished in 16 minutes.')); fseek($this->res, 0); $content = fread($this->res, 1024); @@ -71,8 +71,8 @@ public function testWriteWithTooLongMessage() { $message = str_pad('test', 520, 'a'); $this->createHandler(); - $this->handler->setHighPriorityLevel(Logger::EMERGENCY); // skip priority notifications - $this->handler->handle($this->getRecord(Logger::CRITICAL, $message)); + $this->handler->setHighPriorityLevel(Level::Emergency); // skip priority notifications + $this->handler->handle($this->getRecord(Level::Critical, $message)); fseek($this->res, 0); $content = fread($this->res, 1024); @@ -84,7 +84,7 @@ public function testWriteWithTooLongMessage() public function testWriteWithHighPriority() { $this->createHandler(); - $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1')); + $this->handler->handle($this->getRecord(Level::Critical, 'test1')); fseek($this->res, 0); $content = fread($this->res, 1024); @@ -94,7 +94,7 @@ public function testWriteWithHighPriority() public function testWriteWithEmergencyPriority() { $this->createHandler(); - $this->handler->handle($this->getRecord(Logger::EMERGENCY, 'test1')); + $this->handler->handle($this->getRecord(Level::Emergency, 'test1')); fseek($this->res, 0); $content = fread($this->res, 1024); @@ -104,7 +104,7 @@ public function testWriteWithEmergencyPriority() public function testWriteToMultipleUsers() { $this->createHandler('myToken', ['userA', 'userB']); - $this->handler->handle($this->getRecord(Logger::EMERGENCY, 'test1')); + $this->handler->handle($this->getRecord(Level::Emergency, 'test1')); fseek($this->res, 0); $content = fread($this->res, 1024); diff --git a/tests/Monolog/Handler/RedisHandlerTest.php b/tests/Monolog/Handler/RedisHandlerTest.php index 7ee409a16..c65885c71 100644 --- a/tests/Monolog/Handler/RedisHandlerTest.php +++ b/tests/Monolog/Handler/RedisHandlerTest.php @@ -12,7 +12,7 @@ namespace Monolog\Handler; use Monolog\Test\TestCase; -use Monolog\Logger; +use Monolog\Level; use Monolog\Formatter\LineFormatter; class RedisHandlerTest extends TestCase @@ -46,7 +46,7 @@ public function testPredisHandle() $redis->rpush('key', 'test')->shouldBeCalled(); $redis = $redis->reveal(); - $record = $this->getRecord(Logger::WARNING, 'test', ['data' => new \stdClass, 'foo' => 34]); + $record = $this->getRecord(Level::Warning, 'test', ['data' => new \stdClass, 'foo' => 34]); $handler = new RedisHandler($redis, 'key'); $handler->setFormatter(new LineFormatter("%message%")); @@ -66,7 +66,7 @@ public function testRedisHandle() ->method('rPush') ->with('key', 'test'); - $record = $this->getRecord(Logger::WARNING, 'test', ['data' => new \stdClass, 'foo' => 34]); + $record = $this->getRecord(Level::Warning, 'test', ['data' => new \stdClass, 'foo' => 34]); $handler = new RedisHandler($redis, 'key'); $handler->setFormatter(new LineFormatter("%message%")); @@ -98,9 +98,9 @@ public function testRedisHandleCapped() ->method('exec') ->will($this->returnSelf()); - $record = $this->getRecord(Logger::WARNING, 'test', ['data' => new \stdClass, 'foo' => 34]); + $record = $this->getRecord(Level::Warning, 'test', ['data' => new \stdClass, 'foo' => 34]); - $handler = new RedisHandler($redis, 'key', Logger::DEBUG, true, 10); + $handler = new RedisHandler($redis, 'key', Level::Debug, true, 10); $handler->setFormatter(new LineFormatter("%message%")); $handler->handle($record); } @@ -129,9 +129,9 @@ public function testPredisHandleCapped() $cb($redisTransaction); })); - $record = $this->getRecord(Logger::WARNING, 'test', ['data' => new \stdClass, 'foo' => 34]); + $record = $this->getRecord(Level::Warning, 'test', ['data' => new \stdClass, 'foo' => 34]); - $handler = new RedisHandler($redis, 'key', Logger::DEBUG, true, 10); + $handler = new RedisHandler($redis, 'key', Level::Debug, true, 10); $handler->setFormatter(new LineFormatter("%message%")); $handler->handle($record); } diff --git a/tests/Monolog/Handler/RedisPubSubHandlerTest.php b/tests/Monolog/Handler/RedisPubSubHandlerTest.php index 5a37d4100..f3e9f6e69 100644 --- a/tests/Monolog/Handler/RedisPubSubHandlerTest.php +++ b/tests/Monolog/Handler/RedisPubSubHandlerTest.php @@ -14,7 +14,7 @@ namespace Monolog\Handler; use Monolog\Test\TestCase; -use Monolog\Logger; +use Monolog\Level; use Monolog\Formatter\LineFormatter; class RedisPubSubHandlerTest extends TestCase @@ -48,7 +48,7 @@ public function testPredisHandle() $redis->publish('key', 'test')->shouldBeCalled(); $redis = $redis->reveal(); - $record = $this->getRecord(Logger::WARNING, 'test', ['data' => new \stdClass(), 'foo' => 34]); + $record = $this->getRecord(Level::Warning, 'test', ['data' => new \stdClass(), 'foo' => 34]); $handler = new RedisPubSubHandler($redis, 'key'); $handler->setFormatter(new LineFormatter("%message%")); @@ -67,7 +67,7 @@ public function testRedisHandle() ->method('publish') ->with('key', 'test'); - $record = $this->getRecord(Logger::WARNING, 'test', ['data' => new \stdClass(), 'foo' => 34]); + $record = $this->getRecord(Level::Warning, 'test', ['data' => new \stdClass(), 'foo' => 34]); $handler = new RedisPubSubHandler($redis, 'key'); $handler->setFormatter(new LineFormatter("%message%")); diff --git a/tests/Monolog/Handler/RollbarHandlerTest.php b/tests/Monolog/Handler/RollbarHandlerTest.php index 0aa7cbff0..da267a879 100644 --- a/tests/Monolog/Handler/RollbarHandlerTest.php +++ b/tests/Monolog/Handler/RollbarHandlerTest.php @@ -13,7 +13,7 @@ use Exception; use Monolog\Test\TestCase; -use Monolog\Logger; +use Monolog\Level; use PHPUnit\Framework\MockObject\MockObject; use Rollbar\RollbarLogger; @@ -52,7 +52,7 @@ public function testExceptionLogLevel() { $handler = $this->createHandler(); - $handler->handle($this->createExceptionRecord(Logger::DEBUG)); + $handler->handle($this->createExceptionRecord(Level::Debug)); $this->assertEquals('debug', $this->reportedExceptionArguments['payload']['level']); } @@ -79,10 +79,10 @@ private function setupRollbarLoggerMock() private function createHandler(): RollbarHandler { - return new RollbarHandler($this->rollbarLogger, Logger::DEBUG); + return new RollbarHandler($this->rollbarLogger, Level::Debug); } - private function createExceptionRecord($level = Logger::DEBUG, $message = 'test', $exception = null): array + private function createExceptionRecord($level = Level::Debug, $message = 'test', $exception = null): array { return $this->getRecord($level, $message, [ 'exception' => $exception ?: new Exception(), diff --git a/tests/Monolog/Handler/Slack/SlackRecordTest.php b/tests/Monolog/Handler/Slack/SlackRecordTest.php index 563bec728..e6c88fe03 100644 --- a/tests/Monolog/Handler/Slack/SlackRecordTest.php +++ b/tests/Monolog/Handler/Slack/SlackRecordTest.php @@ -11,7 +11,8 @@ namespace Monolog\Handler\Slack; -use Monolog\Logger; +use Monolog\Level; +use Monolog\LevelName; use Monolog\Test\TestCase; /** @@ -22,24 +23,22 @@ class SlackRecordTest extends TestCase public function dataGetAttachmentColor() { return array( - array(Logger::DEBUG, SlackRecord::COLOR_DEFAULT), - array(Logger::INFO, SlackRecord::COLOR_GOOD), - array(Logger::NOTICE, SlackRecord::COLOR_GOOD), - array(Logger::WARNING, SlackRecord::COLOR_WARNING), - array(Logger::ERROR, SlackRecord::COLOR_DANGER), - array(Logger::CRITICAL, SlackRecord::COLOR_DANGER), - array(Logger::ALERT, SlackRecord::COLOR_DANGER), - array(Logger::EMERGENCY, SlackRecord::COLOR_DANGER), + array(Level::Debug, SlackRecord::COLOR_DEFAULT), + array(Level::Info, SlackRecord::COLOR_GOOD), + array(Level::Notice, SlackRecord::COLOR_GOOD), + array(Level::Warning, SlackRecord::COLOR_WARNING), + array(Level::Error, SlackRecord::COLOR_DANGER), + array(Level::Critical, SlackRecord::COLOR_DANGER), + array(Level::Alert, SlackRecord::COLOR_DANGER), + array(Level::Emergency, SlackRecord::COLOR_DANGER), ); } /** * @dataProvider dataGetAttachmentColor - * @param int $logLevel - * @param string $expectedColour RGB hex color or name of Slack color * @covers ::getAttachmentColor */ - public function testGetAttachmentColor($logLevel, $expectedColour) + public function testGetAttachmentColor(Level $logLevel, string $expectedColour) { $slackRecord = new SlackRecord(); $this->assertSame( @@ -155,7 +154,7 @@ public function testTextEqualsMessageIfNoAttachment() { $message = 'Test message'; $record = new SlackRecord(null, null, false); - $data = $record->getSlackData($this->getRecord(Logger::WARNING, $message)); + $data = $record->getSlackData($this->getRecord(Level::Warning, $message)); $this->assertArrayHasKey('text', $data); $this->assertSame($message, $data['text']); @@ -181,13 +180,13 @@ public function testTextEqualsFormatterOutput() $message = 'Test message'; $record = new SlackRecord(null, null, false, null, false, false, array(), $formatter); - $data = $record->getSlackData($this->getRecord(Logger::WARNING, $message)); + $data = $record->getSlackData($this->getRecord(Level::Warning, $message)); $this->assertArrayHasKey('text', $data); $this->assertSame($message . 'test', $data['text']); $record->setFormatter($formatter2); - $data = $record->getSlackData($this->getRecord(Logger::WARNING, $message)); + $data = $record->getSlackData($this->getRecord(Level::Warning, $message)); $this->assertArrayHasKey('text', $data); $this->assertSame($message . 'test1', $data['text']); @@ -197,7 +196,7 @@ public function testAddsFallbackAndTextToAttachment() { $message = 'Test message'; $record = new SlackRecord(null); - $data = $record->getSlackData($this->getRecord(Logger::WARNING, $message)); + $data = $record->getSlackData($this->getRecord(Level::Warning, $message)); $this->assertSame($message, $data['attachments'][0]['text']); $this->assertSame($message, $data['attachments'][0]['fallback']); @@ -206,11 +205,11 @@ public function testAddsFallbackAndTextToAttachment() public function testMapsLevelToColorAttachmentColor() { $record = new SlackRecord(null); - $errorLoggerRecord = $this->getRecord(Logger::ERROR); - $emergencyLoggerRecord = $this->getRecord(Logger::EMERGENCY); - $warningLoggerRecord = $this->getRecord(Logger::WARNING); - $infoLoggerRecord = $this->getRecord(Logger::INFO); - $debugLoggerRecord = $this->getRecord(Logger::DEBUG); + $errorLoggerRecord = $this->getRecord(Level::Error); + $emergencyLoggerRecord = $this->getRecord(Level::Emergency); + $warningLoggerRecord = $this->getRecord(Level::Warning); + $infoLoggerRecord = $this->getRecord(Level::Info); + $debugLoggerRecord = $this->getRecord(Level::Debug); $data = $record->getSlackData($errorLoggerRecord); $this->assertSame(SlackRecord::COLOR_DANGER, $data['attachments'][0]['color']); @@ -230,8 +229,8 @@ public function testMapsLevelToColorAttachmentColor() public function testAddsShortAttachmentWithoutContextAndExtra() { - $level = Logger::ERROR; - $levelName = Logger::getLevelName($level); + $level = Level::Error; + $levelName = LevelName::fromLevel($level)->value; $record = new SlackRecord(null, null, true, null, true); $data = $record->getSlackData($this->getRecord($level, 'test', array('test' => 1))); @@ -244,8 +243,8 @@ public function testAddsShortAttachmentWithoutContextAndExtra() public function testAddsShortAttachmentWithContextAndExtra() { - $level = Logger::ERROR; - $levelName = Logger::getLevelName($level); + $level = Level::Error; + $levelName = LevelName::fromLevel($level)->value; $context = array('test' => 1); $extra = array('tags' => array('web')); $record = new SlackRecord(null, null, true, null, true, true); @@ -277,8 +276,8 @@ public function testAddsShortAttachmentWithContextAndExtra() public function testAddsLongAttachmentWithoutContextAndExtra() { - $level = Logger::ERROR; - $levelName = Logger::getLevelName($level); + $level = Level::Error; + $levelName = LevelName::fromLevel($level)->value; $record = new SlackRecord(null, null, true, null); $data = $record->getSlackData($this->getRecord($level, 'test', array('test' => 1))); @@ -299,8 +298,8 @@ public function testAddsLongAttachmentWithoutContextAndExtra() public function testAddsLongAttachmentWithContextAndExtra() { - $level = Logger::ERROR; - $levelName = Logger::getLevelName($level); + $level = Level::Error; + $levelName = LevelName::fromLevel($level)->value; $context = array('test' => 1); $extra = array('tags' => array('web')); $record = new SlackRecord(null, null, true, null, false, true); @@ -350,7 +349,7 @@ public function testAddsTimestampToAttachment() public function testContextHasException() { - $record = $this->getRecord(Logger::CRITICAL, 'This is a critical message.', array('exception' => new \Exception())); + $record = $this->getRecord(Level::Critical, 'This is a critical message.', array('exception' => new \Exception())); $slackRecord = new SlackRecord(null, null, true, null, false, true); $data = $slackRecord->getSlackData($record); $this->assertIsString($data['attachments'][0]['fields'][1]['value']); @@ -359,7 +358,7 @@ public function testContextHasException() public function testExcludeExtraAndContextFields() { $record = $this->getRecord( - Logger::WARNING, + Level::Warning, 'test', context: array('info' => array('library' => 'monolog', 'author' => 'Jordi')), extra: array('tags' => array('web', 'cli')), diff --git a/tests/Monolog/Handler/SlackHandlerTest.php b/tests/Monolog/Handler/SlackHandlerTest.php index c6252513c..45b439dd9 100644 --- a/tests/Monolog/Handler/SlackHandlerTest.php +++ b/tests/Monolog/Handler/SlackHandlerTest.php @@ -12,7 +12,7 @@ namespace Monolog\Handler; use Monolog\Test\TestCase; -use Monolog\Logger; +use Monolog\Level; use Monolog\Formatter\LineFormatter; use Monolog\Handler\Slack\SlackRecord; @@ -42,7 +42,7 @@ public function setUp(): void public function testWriteHeader() { $this->createHandler(); - $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1')); + $this->handler->handle($this->getRecord(Level::Critical, 'test1')); fseek($this->res, 0); $content = fread($this->res, 1024); @@ -52,7 +52,7 @@ public function testWriteHeader() public function testWriteContent() { $this->createHandler(); - $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1')); + $this->handler->handle($this->getRecord(Level::Critical, 'test1')); fseek($this->res, 0); $content = fread($this->res, 1024); @@ -65,13 +65,13 @@ public function testWriteContent() public function testWriteContentUsesFormatterIfProvided() { $this->createHandler('myToken', 'channel1', 'Monolog', false); - $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1')); + $this->handler->handle($this->getRecord(Level::Critical, 'test1')); fseek($this->res, 0); $content = fread($this->res, 1024); $this->createHandler('myToken', 'channel1', 'Monolog', false); $this->handler->setFormatter(new LineFormatter('foo--%message%')); - $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test2')); + $this->handler->handle($this->getRecord(Level::Critical, 'test2')); fseek($this->res, 0); $content2 = fread($this->res, 1024); @@ -82,7 +82,7 @@ public function testWriteContentUsesFormatterIfProvided() public function testWriteContentWithEmoji() { $this->createHandler('myToken', 'channel1', 'Monolog', true, 'alien'); - $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1')); + $this->handler->handle($this->getRecord(Level::Critical, 'test1')); fseek($this->res, 0); $content = fread($this->res, 1024); @@ -105,7 +105,7 @@ public function testWriteContentWithColors($level, $expectedColor) public function testWriteContentWithPlainTextMessage() { $this->createHandler('myToken', 'channel1', 'Monolog', false); - $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1')); + $this->handler->handle($this->getRecord(Level::Critical, 'test1')); fseek($this->res, 0); $content = fread($this->res, 1024); @@ -115,20 +115,20 @@ public function testWriteContentWithPlainTextMessage() public function provideLevelColors() { return array( - array(Logger::DEBUG, urlencode(SlackRecord::COLOR_DEFAULT)), - array(Logger::INFO, SlackRecord::COLOR_GOOD), - array(Logger::NOTICE, SlackRecord::COLOR_GOOD), - array(Logger::WARNING, SlackRecord::COLOR_WARNING), - array(Logger::ERROR, SlackRecord::COLOR_DANGER), - array(Logger::CRITICAL, SlackRecord::COLOR_DANGER), - array(Logger::ALERT, SlackRecord::COLOR_DANGER), - array(Logger::EMERGENCY,SlackRecord::COLOR_DANGER), + array(Level::Debug, urlencode(SlackRecord::COLOR_DEFAULT)), + array(Level::Info, SlackRecord::COLOR_GOOD), + array(Level::Notice, SlackRecord::COLOR_GOOD), + array(Level::Warning, SlackRecord::COLOR_WARNING), + array(Level::Error, SlackRecord::COLOR_DANGER), + array(Level::Critical, SlackRecord::COLOR_DANGER), + array(Level::Alert, SlackRecord::COLOR_DANGER), + array(Level::Emergency,SlackRecord::COLOR_DANGER), ); } private function createHandler($token = 'myToken', $channel = 'channel1', $username = 'Monolog', $useAttachment = true, $iconEmoji = null, $useShortAttachment = false, $includeExtra = false) { - $constructorArgs = [$token, $channel, $username, $useAttachment, $iconEmoji, Logger::DEBUG, true, $useShortAttachment, $includeExtra]; + $constructorArgs = [$token, $channel, $username, $useAttachment, $iconEmoji, Level::Debug, true, $useShortAttachment, $includeExtra]; $this->res = fopen('php://memory', 'a'); $this->handler = $this->getMockBuilder('Monolog\Handler\SlackHandler') ->setConstructorArgs($constructorArgs) diff --git a/tests/Monolog/Handler/SlackWebhookHandlerTest.php b/tests/Monolog/Handler/SlackWebhookHandlerTest.php index 5ff262254..2dfb5444b 100644 --- a/tests/Monolog/Handler/SlackWebhookHandlerTest.php +++ b/tests/Monolog/Handler/SlackWebhookHandlerTest.php @@ -11,8 +11,9 @@ namespace Monolog\Handler; +use Monolog\LevelName; use Monolog\Test\TestCase; -use Monolog\Logger; +use Monolog\Level; use Monolog\Formatter\LineFormatter; use Monolog\Handler\Slack\SlackRecord; @@ -72,7 +73,7 @@ public function testConstructorFull() ':ghost:', false, false, - Logger::DEBUG, + Level::Debug, false ); @@ -100,7 +101,7 @@ public function testConstructorFullWithAttachment() 'https://www.example.com/example.png', false, false, - Logger::DEBUG, + Level::Debug, false ); @@ -118,7 +119,7 @@ public function testConstructorFullWithAttachment() 'fields' => array( array( 'title' => 'Level', - 'value' => Logger::getLevelName(Logger::WARNING), + 'value' => LevelName::Warning->value, 'short' => false, ), ), diff --git a/tests/Monolog/Handler/SocketHandlerTest.php b/tests/Monolog/Handler/SocketHandlerTest.php index 272dd704a..ddc7597a5 100644 --- a/tests/Monolog/Handler/SocketHandlerTest.php +++ b/tests/Monolog/Handler/SocketHandlerTest.php @@ -12,7 +12,7 @@ namespace Monolog\Handler; use Monolog\Test\TestCase; -use Monolog\Logger; +use Monolog\Level; use PHPUnit\Framework\MockObject\MockObject; /** @@ -285,7 +285,7 @@ private function createHandler($connectionString) private function writeRecord($string) { - $this->handler->handle($this->getRecord(Logger::WARNING, $string)); + $this->handler->handle($this->getRecord(Level::Warning, $string)); } private function setMockHandler(array $methods = []) diff --git a/tests/Monolog/Handler/StreamHandlerTest.php b/tests/Monolog/Handler/StreamHandlerTest.php index 97d56b8cf..c0f4979fa 100644 --- a/tests/Monolog/Handler/StreamHandlerTest.php +++ b/tests/Monolog/Handler/StreamHandlerTest.php @@ -13,7 +13,7 @@ use Monolog\Handler\StreamHandler; use Monolog\Test\TestCase; -use Monolog\Logger; +use Monolog\Level; class StreamHandlerTest extends TestCase { @@ -26,9 +26,9 @@ public function testWrite() $handle = fopen('php://memory', 'a+'); $handler = new StreamHandler($handle); $handler->setFormatter($this->getIdentityFormatter()); - $handler->handle($this->getRecord(Logger::WARNING, 'test')); - $handler->handle($this->getRecord(Logger::WARNING, 'test2')); - $handler->handle($this->getRecord(Logger::WARNING, 'test3')); + $handler->handle($this->getRecord(Level::Warning, 'test')); + $handler->handle($this->getRecord(Level::Warning, 'test2')); + $handler->handle($this->getRecord(Level::Warning, 'test3')); fseek($handle, 0); $this->assertEquals('testtest2test3', fread($handle, 100)); } @@ -51,7 +51,7 @@ public function testCloseKeepsExternalHandlersOpen() public function testClose() { $handler = new StreamHandler('php://memory'); - $handler->handle($this->getRecord(Logger::WARNING, 'test')); + $handler->handle($this->getRecord(Level::Warning, 'test')); $stream = $handler->getStream(); $this->assertTrue(is_resource($stream)); @@ -66,7 +66,7 @@ public function testClose() public function testSerialization() { $handler = new StreamHandler('php://memory'); - $handler->handle($this->getRecord(Logger::WARNING, 'testfoo')); + $handler->handle($this->getRecord(Level::Warning, 'testfoo')); $stream = $handler->getStream(); $this->assertTrue(is_resource($stream)); @@ -76,7 +76,7 @@ public function testSerialization() $this->assertFalse(is_resource($stream)); $handler = unserialize($serialized); - $handler->handle($this->getRecord(Logger::WARNING, 'testbar')); + $handler->handle($this->getRecord(Level::Warning, 'testbar')); $stream = $handler->getStream(); $this->assertTrue(is_resource($stream)); @@ -102,7 +102,7 @@ public function testWriteCreatesTheStreamResource() public function testWriteLocking() { $temp = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'monolog_locked_log'; - $handler = new StreamHandler($temp, Logger::DEBUG, true, null, true); + $handler = new StreamHandler($temp, Level::Debug, true, null, true); $handler->handle($this->getRecord()); } diff --git a/tests/Monolog/Handler/SyslogHandlerTest.php b/tests/Monolog/Handler/SyslogHandlerTest.php index 5479d547a..18fb2bcb8 100644 --- a/tests/Monolog/Handler/SyslogHandlerTest.php +++ b/tests/Monolog/Handler/SyslogHandlerTest.php @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; class SyslogHandlerTest extends \PHPUnit\Framework\TestCase { @@ -29,7 +29,7 @@ public function testConstruct() $handler = new SyslogHandler('test', 'user'); $this->assertInstanceOf('Monolog\Handler\SyslogHandler', $handler); - $handler = new SyslogHandler('test', LOG_USER, Logger::DEBUG, true, LOG_PERROR); + $handler = new SyslogHandler('test', LOG_USER, Level::Debug, true, LOG_PERROR); $this->assertInstanceOf('Monolog\Handler\SyslogHandler', $handler); } diff --git a/tests/Monolog/Handler/SyslogUdpHandlerTest.php b/tests/Monolog/Handler/SyslogUdpHandlerTest.php index 7cb832542..530a9d53c 100644 --- a/tests/Monolog/Handler/SyslogUdpHandlerTest.php +++ b/tests/Monolog/Handler/SyslogUdpHandlerTest.php @@ -11,6 +11,7 @@ namespace Monolog\Handler; +use Monolog\Level; use Monolog\Test\TestCase; /** @@ -98,6 +99,6 @@ public function testRfc() protected function getRecordWithMessage($msg) { - return $this->getRecord(message: $msg, level: \Monolog\Logger::WARNING, channel: 'lol', datetime: new \DateTimeImmutable('2014-01-07 12:34:56')); + return $this->getRecord(message: $msg, level: Level::Warning, channel: 'lol', datetime: new \DateTimeImmutable('2014-01-07 12:34:56')); } } diff --git a/tests/Monolog/Handler/TelegramBotHandlerTest.php b/tests/Monolog/Handler/TelegramBotHandlerTest.php index 6cb3c7d96..754af3335 100644 --- a/tests/Monolog/Handler/TelegramBotHandlerTest.php +++ b/tests/Monolog/Handler/TelegramBotHandlerTest.php @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Monolog\Test\TestCase; /** @@ -42,7 +42,7 @@ private function createHandler( bool $disableWebPagePreview = false, bool $disableNotification = true ): void { - $constructorArgs = [$apiKey, $channel, Logger::DEBUG, true, $parseMode, $disableWebPagePreview, $disableNotification]; + $constructorArgs = [$apiKey, $channel, Level::Debug, true, $parseMode, $disableWebPagePreview, $disableNotification]; $this->handler = $this->getMockBuilder(TelegramBotHandler::class) ->setConstructorArgs($constructorArgs) diff --git a/tests/Monolog/Handler/TestHandlerTest.php b/tests/Monolog/Handler/TestHandlerTest.php index b4609c92c..218d111ce 100644 --- a/tests/Monolog/Handler/TestHandlerTest.php +++ b/tests/Monolog/Handler/TestHandlerTest.php @@ -11,8 +11,8 @@ namespace Monolog\Handler; +use Monolog\Level; use Monolog\Test\TestCase; -use Monolog\Logger; /** * @covers Monolog\Handler\TestHandler @@ -22,7 +22,7 @@ class TestHandlerTest extends TestCase /** * @dataProvider methodProvider */ - public function testHandler($method, $level) + public function testHandler($method, Level $level) { $handler = new TestHandler; $record = $this->getRecord($level, 'test'.$method); @@ -57,7 +57,7 @@ public function testHandler($method, $level) public function testHandlerAssertEmptyContext() { $handler = new TestHandler; - $record = $this->getRecord(Logger::WARNING, 'test', []); + $record = $this->getRecord(Level::Warning, 'test', []); $this->assertFalse($handler->hasWarning([ 'message' => 'test', 'context' => [], @@ -80,7 +80,7 @@ public function testHandlerAssertEmptyContext() public function testHandlerAssertNonEmptyContext() { $handler = new TestHandler; - $record = $this->getRecord(Logger::WARNING, 'test', ['foo' => 'bar']); + $record = $this->getRecord(Level::Warning, 'test', ['foo' => 'bar']); $this->assertFalse($handler->hasWarning([ 'message' => 'test', 'context' => [ @@ -105,14 +105,14 @@ public function testHandlerAssertNonEmptyContext() public function methodProvider() { return [ - ['Emergency', Logger::EMERGENCY], - ['Alert' , Logger::ALERT], - ['Critical' , Logger::CRITICAL], - ['Error' , Logger::ERROR], - ['Warning' , Logger::WARNING], - ['Info' , Logger::INFO], - ['Notice' , Logger::NOTICE], - ['Debug' , Logger::DEBUG], + ['Emergency', Level::Emergency], + ['Alert' , Level::Alert], + ['Critical' , Level::Critical], + ['Error' , Level::Error], + ['Warning' , Level::Warning], + ['Info' , Level::Info], + ['Notice' , Level::Notice], + ['Debug' , Level::Debug], ]; } } diff --git a/tests/Monolog/Handler/WhatFailureGroupHandlerTest.php b/tests/Monolog/Handler/WhatFailureGroupHandlerTest.php index 3d0d3b128..77bc932b7 100644 --- a/tests/Monolog/Handler/WhatFailureGroupHandlerTest.php +++ b/tests/Monolog/Handler/WhatFailureGroupHandlerTest.php @@ -12,7 +12,7 @@ namespace Monolog\Handler; use Monolog\Test\TestCase; -use Monolog\Logger; +use Monolog\Level; class WhatFailureGroupHandlerTest extends TestCase { @@ -34,8 +34,8 @@ public function testHandle() { $testHandlers = [new TestHandler(), new TestHandler()]; $handler = new WhatFailureGroupHandler($testHandlers); - $handler->handle($this->getRecord(Logger::DEBUG)); - $handler->handle($this->getRecord(Logger::INFO)); + $handler->handle($this->getRecord(Level::Debug)); + $handler->handle($this->getRecord(Level::Info)); foreach ($testHandlers as $test) { $this->assertTrue($test->hasDebugRecords()); $this->assertTrue($test->hasInfoRecords()); @@ -50,7 +50,7 @@ public function testHandleBatch() { $testHandlers = [new TestHandler(), new TestHandler()]; $handler = new WhatFailureGroupHandler($testHandlers); - $handler->handleBatch([$this->getRecord(Logger::DEBUG), $this->getRecord(Logger::INFO)]); + $handler->handleBatch([$this->getRecord(Level::Debug), $this->getRecord(Level::Info)]); foreach ($testHandlers as $test) { $this->assertTrue($test->hasDebugRecords()); $this->assertTrue($test->hasInfoRecords()); @@ -63,11 +63,11 @@ public function testHandleBatch() */ public function testIsHandling() { - $testHandlers = [new TestHandler(Logger::ERROR), new TestHandler(Logger::WARNING)]; + $testHandlers = [new TestHandler(Level::Error), new TestHandler(Level::Warning)]; $handler = new WhatFailureGroupHandler($testHandlers); - $this->assertTrue($handler->isHandling($this->getRecord(Logger::ERROR))); - $this->assertTrue($handler->isHandling($this->getRecord(Logger::WARNING))); - $this->assertFalse($handler->isHandling($this->getRecord(Logger::DEBUG))); + $this->assertTrue($handler->isHandling($this->getRecord(Level::Error))); + $this->assertTrue($handler->isHandling($this->getRecord(Level::Warning))); + $this->assertFalse($handler->isHandling($this->getRecord(Level::Debug))); } /** @@ -82,7 +82,7 @@ public function testHandleUsesProcessors() return $record; }); - $handler->handle($this->getRecord(Logger::WARNING)); + $handler->handle($this->getRecord(Level::Warning)); $this->assertTrue($test->hasWarningRecords()); $records = $test->getRecords(); $this->assertTrue($records[0]['extra']['foo']); @@ -105,7 +105,7 @@ public function testHandleBatchUsesProcessors() return $record; }); - $handler->handleBatch(array($this->getRecord(Logger::DEBUG), $this->getRecord(Logger::INFO))); + $handler->handleBatch(array($this->getRecord(Level::Debug), $this->getRecord(Level::Info))); foreach ($testHandlers as $test) { $this->assertTrue($test->hasDebugRecords()); $this->assertTrue($test->hasInfoRecords()); @@ -131,7 +131,7 @@ public function testHandleException() return $record; }); - $handler->handle($this->getRecord(Logger::WARNING)); + $handler->handle($this->getRecord(Level::Warning)); $this->assertTrue($test->hasWarningRecords()); $records = $test->getRecords(); $this->assertTrue($records[0]['extra']['foo']); diff --git a/tests/Monolog/Handler/ZendMonitorHandlerTest.php b/tests/Monolog/Handler/ZendMonitorHandlerTest.php index 42622ffbb..217a6e552 100644 --- a/tests/Monolog/Handler/ZendMonitorHandlerTest.php +++ b/tests/Monolog/Handler/ZendMonitorHandlerTest.php @@ -12,7 +12,7 @@ namespace Monolog\Handler; use Monolog\Test\TestCase; -use Monolog\Logger; +use Monolog\Level; class ZendMonitorHandlerTest extends TestCase { @@ -51,15 +51,13 @@ public function testWrite() ->method('getDefaultFormatter') ->will($this->returnValue($formatterMock)); - $levelMap = $zendMonitor->getLevelMap(); - $zendMonitor->expects($this->once()) ->method('writeZendMonitorCustomEvent') ->with( - Logger::getLevelName($record->level), + $record->levelName->value, $record->message, $formatterResult, - $levelMap[$record->level] + \ZEND_MONITOR_EVENT_SEVERITY_WARNING ); $zendMonitor->handle($record); diff --git a/tests/Monolog/LoggerTest.php b/tests/Monolog/LoggerTest.php index 9ba62f749..70b4a9ff2 100644 --- a/tests/Monolog/LoggerTest.php +++ b/tests/Monolog/LoggerTest.php @@ -18,7 +18,7 @@ class LoggerTest extends TestCase { /** - * @covers Monolog\Logger::getName + * @covers Logger::getName */ public function testGetName() { @@ -27,15 +27,7 @@ public function testGetName() } /** - * @covers Monolog\Logger::getLevelName - */ - public function testGetLevelName() - { - $this->assertEquals('ERROR', Logger::getLevelName(Logger::ERROR)); - } - - /** - * @covers Monolog\Logger::withName + * @covers Logger::withName */ public function testWithName() { @@ -48,32 +40,22 @@ public function testWithName() } /** - * @covers Monolog\Logger::toMonologLevel + * @covers Logger::toMonologLevel */ public function testConvertPSR3ToMonologLevel() { - $this->assertEquals(Logger::toMonologLevel('debug'), 100); - $this->assertEquals(Logger::toMonologLevel('info'), 200); - $this->assertEquals(Logger::toMonologLevel('notice'), 250); - $this->assertEquals(Logger::toMonologLevel('warning'), 300); - $this->assertEquals(Logger::toMonologLevel('error'), 400); - $this->assertEquals(Logger::toMonologLevel('critical'), 500); - $this->assertEquals(Logger::toMonologLevel('alert'), 550); - $this->assertEquals(Logger::toMonologLevel('emergency'), 600); - } - - /** - * @covers Monolog\Logger::getLevelName - */ - public function testGetLevelNameThrows() - { - $this->expectException(\InvalidArgumentException::class); - - Logger::getLevelName(5); + $this->assertEquals(Logger::toMonologLevel('debug'), Level::Debug); + $this->assertEquals(Logger::toMonologLevel('info'), Level::Info); + $this->assertEquals(Logger::toMonologLevel('notice'), Level::Notice); + $this->assertEquals(Logger::toMonologLevel('warning'), Level::Warning); + $this->assertEquals(Logger::toMonologLevel('error'), Level::Error); + $this->assertEquals(Logger::toMonologLevel('critical'), Level::Critical); + $this->assertEquals(Logger::toMonologLevel('alert'), Level::Alert); + $this->assertEquals(Logger::toMonologLevel('emergency'), Level::Emergency); } /** - * @covers Monolog\Logger::__construct + * @covers Logger::__construct */ public function testChannel() { @@ -86,7 +68,7 @@ public function testChannel() } /** - * @covers Monolog\Logger::addRecord + * @covers Logger::addRecord */ public function testLog() { @@ -98,11 +80,11 @@ public function testLog() $logger->pushHandler($handler); - $this->assertTrue($logger->addRecord(Logger::WARNING, 'test')); + $this->assertTrue($logger->addRecord(Level::Warning, 'test')); } /** - * @covers Monolog\Logger::addRecord + * @covers Logger::addRecord */ public function testLogAlwaysHandledIfNoProcessorsArePresent() { @@ -114,11 +96,11 @@ public function testLogAlwaysHandledIfNoProcessorsArePresent() $logger->pushHandler($handler); - $this->assertTrue($logger->addRecord(Logger::WARNING, 'test')); + $this->assertTrue($logger->addRecord(Level::Warning, 'test')); } /** - * @covers Monolog\Logger::addRecord + * @covers Logger::addRecord */ public function testLogNotHandledIfProcessorsArePresent() { @@ -131,7 +113,7 @@ public function testLogNotHandledIfProcessorsArePresent() $logger->pushProcessor(fn (LogRecord $record) => $record); $logger->pushHandler($handler); - $this->assertFalse($logger->addRecord(Logger::WARNING, 'test')); + $this->assertFalse($logger->addRecord(Level::Warning, 'test')); } public function testHandlersInCtor() @@ -155,8 +137,8 @@ public function testProcessorsInCtor() } /** - * @covers Monolog\Logger::pushHandler - * @covers Monolog\Logger::popHandler + * @covers Logger::pushHandler + * @covers Logger::popHandler */ public function testPushPopHandler() { @@ -176,7 +158,7 @@ public function testPushPopHandler() } /** - * @covers Monolog\Logger::setHandlers + * @covers Logger::setHandlers */ public function testSetHandlers() { @@ -200,8 +182,8 @@ public function testSetHandlers() } /** - * @covers Monolog\Logger::pushProcessor - * @covers Monolog\Logger::popProcessor + * @covers Logger::pushProcessor + * @covers Logger::popProcessor */ public function testPushPopProcessor() { @@ -221,7 +203,7 @@ public function testPushPopProcessor() } /** - * @covers Monolog\Logger::addRecord + * @covers Logger::addRecord */ public function testProcessorsAreExecuted() { @@ -239,7 +221,7 @@ public function testProcessorsAreExecuted() } /** - * @covers Monolog\Logger::addRecord + * @covers Logger::addRecord */ public function testProcessorsAreCalledOnlyOnce() { @@ -270,7 +252,7 @@ public function testProcessorsAreCalledOnlyOnce() } /** - * @covers Monolog\Logger::addRecord + * @covers Logger::addRecord */ public function testProcessorsNotCalledWhenNotHandled() { @@ -289,7 +271,7 @@ public function testProcessorsNotCalledWhenNotHandled() } /** - * @covers Monolog\Logger::addRecord + * @covers Logger::addRecord */ public function testHandlersNotCalledBeforeFirstHandlingWhenProcessorsPresent() { @@ -332,7 +314,7 @@ public function testHandlersNotCalledBeforeFirstHandlingWhenProcessorsPresent() } /** - * @covers Monolog\Logger::addRecord + * @covers Logger::addRecord */ public function testHandlersNotCalledBeforeFirstHandlingWhenProcessorsPresentWithAssocArray() { @@ -372,7 +354,7 @@ public function testHandlersNotCalledBeforeFirstHandlingWhenProcessorsPresentWit } /** - * @covers Monolog\Logger::addRecord + * @covers Logger::addRecord */ public function testBubblingWhenTheHandlerReturnsFalse() { @@ -404,7 +386,7 @@ public function testBubblingWhenTheHandlerReturnsFalse() } /** - * @covers Monolog\Logger::addRecord + * @covers Logger::addRecord */ public function testNotBubblingWhenTheHandlerReturnsTrue() { @@ -435,7 +417,7 @@ public function testNotBubblingWhenTheHandlerReturnsTrue() } /** - * @covers Monolog\Logger::isHandling + * @covers Logger::isHandling */ public function testIsHandling() { @@ -448,7 +430,7 @@ public function testIsHandling() ; $logger->pushHandler($handler1); - $this->assertFalse($logger->isHandling(Logger::DEBUG)); + $this->assertFalse($logger->isHandling(Level::Debug)); $handler2 = $this->createMock('Monolog\Handler\HandlerInterface'); $handler2->expects($this->any()) @@ -457,21 +439,21 @@ public function testIsHandling() ; $logger->pushHandler($handler2); - $this->assertTrue($logger->isHandling(Logger::DEBUG)); + $this->assertTrue($logger->isHandling(Level::Debug)); } /** * @dataProvider logMethodProvider - * @covers Monolog\Logger::debug - * @covers Monolog\Logger::info - * @covers Monolog\Logger::notice - * @covers Monolog\Logger::warning - * @covers Monolog\Logger::error - * @covers Monolog\Logger::critical - * @covers Monolog\Logger::alert - * @covers Monolog\Logger::emergency + * @covers Level::Debug + * @covers Level::Info + * @covers Level::Notice + * @covers Level::Warning + * @covers Level::Error + * @covers Level::Critical + * @covers Level::Alert + * @covers Level::Emergency */ - public function testLogMethods($method, $expectedLevel) + public function testLogMethods(string $method, Level $expectedLevel) { $logger = new Logger('foo'); $handler = new TestHandler; @@ -485,20 +467,20 @@ public function logMethodProvider() { return [ // PSR-3 methods - ['debug', Logger::DEBUG], - ['info', Logger::INFO], - ['notice', Logger::NOTICE], - ['warning', Logger::WARNING], - ['error', Logger::ERROR], - ['critical', Logger::CRITICAL], - ['alert', Logger::ALERT], - ['emergency', Logger::EMERGENCY], + ['debug', Level::Debug], + ['info', Level::Info], + ['notice', Level::Notice], + ['warning', Level::Warning], + ['error', Level::Error], + ['critical', Level::Critical], + ['alert', Level::Alert], + ['emergency', Level::Emergency], ]; } /** * @dataProvider setTimezoneProvider - * @covers Monolog\Logger::setTimezone + * @covers Logger::setTimezone */ public function testSetTimezone($tz) { @@ -522,8 +504,8 @@ function ($tz) { } /** - * @covers Monolog\Logger::setTimezone - * @covers Monolog\DateTimeImmutable::__construct + * @covers Logger::setTimezone + * @covers DateTimeImmutable::__construct */ public function testTimezoneIsRespectedInUTC() { @@ -544,8 +526,8 @@ public function testTimezoneIsRespectedInUTC() } /** - * @covers Monolog\Logger::setTimezone - * @covers Monolog\DateTimeImmutable::__construct + * @covers Logger::setTimezone + * @covers DateTimeImmutable::__construct */ public function testTimezoneIsRespectedInOtherTimezone() { @@ -573,8 +555,8 @@ public function tearDown(): void /** * @dataProvider useMicrosecondTimestampsProvider - * @covers Monolog\Logger::useMicrosecondTimestamps - * @covers Monolog\Logger::addRecord + * @covers Logger::useMicrosecondTimestamps + * @covers Logger::addRecord */ public function testUseMicrosecondTimestamps($micro, $assert, $assertFormat) { @@ -603,7 +585,7 @@ public function useMicrosecondTimestampsProvider() } /** - * @covers Monolog\Logger::setExceptionHandler + * @covers Logger::setExceptionHandler */ public function testSetExceptionHandler() { @@ -616,7 +598,7 @@ public function testSetExceptionHandler() } /** - * @covers Monolog\Logger::handleException + * @covers Logger::handleException */ public function testDefaultHandleException() { @@ -638,8 +620,8 @@ public function testDefaultHandleException() } /** - * @covers Monolog\Logger::handleException - * @covers Monolog\Logger::addRecord + * @covers Logger::handleException + * @covers Logger::addRecord */ public function testCustomHandleException() { @@ -689,13 +671,12 @@ public function testReset() return $reflectionProperty->getValue($object); }; - $that = $this; - $assertBufferOfBufferHandlerEmpty = function () use ($getProperty, $bufferHandler, $that) { - $that->assertEmpty($getProperty($bufferHandler, 'buffer')); + $assertBufferOfBufferHandlerEmpty = function () use ($getProperty, $bufferHandler) { + self::assertEmpty($getProperty($bufferHandler, 'buffer')); }; - $assertBuffersEmpty = function () use ($assertBufferOfBufferHandlerEmpty, $getProperty, $fingersCrossedHandler, $that) { + $assertBuffersEmpty = function () use ($assertBufferOfBufferHandlerEmpty, $getProperty, $fingersCrossedHandler) { $assertBufferOfBufferHandlerEmpty(); - $that->assertEmpty($getProperty($fingersCrossedHandler, 'buffer')); + self::assertEmpty($getProperty($fingersCrossedHandler, 'buffer')); }; $logger->debug('debug1'); @@ -710,8 +691,8 @@ public function testReset() $logger->error('error2'); $logger->reset(); $assertBuffersEmpty(); - $this->assertTrue($testHandler->hasRecordThatContains('debug2', Logger::DEBUG)); - $this->assertTrue($testHandler->hasRecordThatContains('error2', Logger::ERROR)); + $this->assertTrue($testHandler->hasRecordThatContains('debug2', Level::Debug)); + $this->assertTrue($testHandler->hasRecordThatContains('error2', Level::Error)); $this->assertNotSame($uid1, $uid1 = $processorUid1->getUid()); $this->assertNotSame($uid2, $uid2 = $processorUid2->getUid()); @@ -731,8 +712,8 @@ public function testReset() $logger->reset(); $assertBuffersEmpty(); $this->assertFalse($testHandler->hasInfoRecords()); - $this->assertTrue($testHandler->hasRecordThatContains('notice4', Logger::NOTICE)); - $this->assertTrue($testHandler->hasRecordThatContains('emergency4', Logger::EMERGENCY)); + $this->assertTrue($testHandler->hasRecordThatContains('notice4', Level::Notice)); + $this->assertTrue($testHandler->hasRecordThatContains('emergency4', Level::Emergency)); $this->assertNotSame($uid1, $processorUid1->getUid()); $this->assertNotSame($uid2, $processorUid2->getUid()); } diff --git a/tests/Monolog/Processor/IntrospectionProcessorTest.php b/tests/Monolog/Processor/IntrospectionProcessorTest.php index ac5b523d0..d18dbd00a 100644 --- a/tests/Monolog/Processor/IntrospectionProcessorTest.php +++ b/tests/Monolog/Processor/IntrospectionProcessorTest.php @@ -26,7 +26,7 @@ function tester($handler, $record) namespace Monolog\Processor; -use Monolog\Logger; +use Monolog\Level; use Monolog\Test\TestCase; use Monolog\Handler\TestHandler; @@ -66,11 +66,11 @@ public function testProcessorFromFunc() public function testLevelTooLow() { - $input = $this->getRecord(Logger::DEBUG); + $input = $this->getRecord(Level::Debug); $expected = $input; - $processor = new IntrospectionProcessor(Logger::CRITICAL); + $processor = new IntrospectionProcessor(Level::Critical); $actual = $processor($input); $this->assertEquals($expected, $actual); @@ -78,7 +78,7 @@ public function testLevelTooLow() public function testLevelEqual() { - $input = $this->getRecord(Logger::CRITICAL); + $input = $this->getRecord(Level::Critical); $expected = $input; $expected['extra'] = [ @@ -89,7 +89,7 @@ public function testLevelEqual() 'callType' => '->', ]; - $processor = new IntrospectionProcessor(Logger::CRITICAL); + $processor = new IntrospectionProcessor(Level::Critical); $actual = $processor($input); $this->assertEquals($expected, $actual); @@ -97,7 +97,7 @@ public function testLevelEqual() public function testLevelHigher() { - $input = $this->getRecord(Logger::EMERGENCY); + $input = $this->getRecord(Level::Emergency); $expected = $input; $expected['extra'] = [ @@ -108,7 +108,7 @@ public function testLevelHigher() 'callType' => '->', ]; - $processor = new IntrospectionProcessor(Logger::CRITICAL); + $processor = new IntrospectionProcessor(Level::Critical); $actual = $processor($input); $this->assertEquals($expected, $actual);