1
0
mirror of https://github.com/Seldaek/monolog.git synced 2025-10-20 16:16:37 +02:00

Convert level/levelName to enums (#1656)

This commit is contained in:
Jordi Boggiano
2022-04-19 21:49:03 +02:00
committed by GitHub
parent 248673e858
commit 2d006a8472
138 changed files with 1297 additions and 1216 deletions

2
.gitignore vendored
View File

@@ -3,6 +3,6 @@ composer.phar
phpunit.xml phpunit.xml
composer.lock composer.lock
.DS_Store .DS_Store
.php_cs.cache .php-cs-fixer.cache
.hg .hg
.phpunit.result.cache .phpunit.result.cache

View File

@@ -17,10 +17,8 @@ $finder = PhpCsFixer\Finder::create()
->in(__DIR__.'/tests') ->in(__DIR__.'/tests')
; ;
return PhpCsFixer\Config::create() $config = new PhpCsFixer\Config();
->setUsingCache(true) return $config->setRules(array(
->setRiskyAllowed(true)
->setRules(array(
'@PSR2' => true, '@PSR2' => true,
// some rules disabled as long as 1.x branch is maintained // some rules disabled as long as 1.x branch is maintained
'binary_operator_spaces' => array( 'binary_operator_spaces' => array(
@@ -30,11 +28,11 @@ return PhpCsFixer\Config::create()
'cast_spaces' => ['space' => 'single'], 'cast_spaces' => ['space' => 'single'],
'header_comment' => ['header' => $header], 'header_comment' => ['header' => $header],
'include' => true, '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_class_opening' => true,
'no_blank_lines_after_phpdoc' => true, 'no_blank_lines_after_phpdoc' => true,
'no_empty_statement' => true, 'no_empty_statement' => true,
'no_extra_consecutive_blank_lines' => true, 'no_extra_blank_lines' => true,
'no_leading_import_slash' => true, 'no_leading_import_slash' => true,
'no_leading_namespace_whitespace' => true, 'no_leading_namespace_whitespace' => true,
'no_trailing_comma_in_singleline_array' => true, 'no_trailing_comma_in_singleline_array' => true,
@@ -49,13 +47,15 @@ return PhpCsFixer\Config::create()
//'phpdoc_scalar' => true, //'phpdoc_scalar' => true,
'phpdoc_trim' => true, 'phpdoc_trim' => true,
//'phpdoc_types' => true, //'phpdoc_types' => true,
'psr0' => true, 'psr_autoloading' => ['dir' => 'src'],
//'array_syntax' => array('syntax' => 'short'), //'array_syntax' => array('syntax' => 'short'),
'declare_strict_types' => true, 'declare_strict_types' => true,
'single_blank_line_before_namespace' => true, 'single_blank_line_before_namespace' => true,
'standardize_not_equals' => true, 'standardize_not_equals' => true,
'ternary_operator_spaces' => true, 'ternary_operator_spaces' => true,
'trailing_comma_in_multiline_array' => true, 'trailing_comma_in_multiline' => true,
)) ))
->setUsingCache(true)
->setRiskyAllowed(true)
->setFinder($finder) ->setFinder($finder)
; ;

View File

@@ -33,7 +33,7 @@ use Monolog\Handler\StreamHandler;
// create a log channel // create a log channel
$log = new Logger('name'); $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 // add records to the log
$log->warning('Foo'); $log->warning('Foo');

View File

@@ -90,7 +90,7 @@ use Monolog\Handler\FirePHPHandler;
// Create the logger // Create the logger
$logger = new Logger('my_logger'); $logger = new Logger('my_logger');
// Now add some handlers // 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()); $logger->pushHandler(new FirePHPHandler());
// You can now use your logger // You can now use your logger
@@ -170,7 +170,7 @@ use Monolog\Handler\StreamHandler;
use Monolog\Handler\FirePHPHandler; use Monolog\Handler\FirePHPHandler;
// Create some handlers // Create some handlers
$stream = new StreamHandler(__DIR__.'/my_app.log', Logger::DEBUG); $stream = new StreamHandler(__DIR__.'/my_app.log', Level::Debug);
$firephp = new FirePHPHandler(); $firephp = new FirePHPHandler();
// Create the main logger of the app // Create the main logger of the app
@@ -229,7 +229,7 @@ $output = "%datetime% > %level_name% > %message% %context% %extra%\n";
$formatter = new LineFormatter($output, $dateFormat); $formatter = new LineFormatter($output, $dateFormat);
// Create a handler // Create a handler
$stream = new StreamHandler(__DIR__.'/my_app.log', Logger::DEBUG); $stream = new StreamHandler(__DIR__.'/my_app.log', Level::Debug);
$stream->setFormatter($formatter); $stream->setFormatter($formatter);
// bind it to a logger object // bind it to a logger object

View File

@@ -30,7 +30,7 @@ class PDOHandler extends AbstractProcessingHandler
private $pdo; private $pdo;
private $statement; 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; $this->pdo = $pdo;
parent::__construct($level, $bubble); parent::__construct($level, $bubble);

View File

@@ -26,7 +26,7 @@ $handler = new SocketHandler('unix:///var/log/httpd_app_log.socket');
$handler->setPersistent(true); $handler->setPersistent(true);
// Now add the handler // Now add the handler
$logger->pushHandler($handler, Logger::DEBUG); $logger->pushHandler($handler, Level::Debug);
// You can now use your logger // You can now use your logger
$logger->info('My logger is now ready'); $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: 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 [] [] cweb1 [2012-02-26 00:12:03] my_logger.INFO: My logger is now ready [] []

View File

@@ -11,6 +11,7 @@
namespace Monolog\Formatter; namespace Monolog\Formatter;
use Monolog\Level;
use Monolog\Logger; use Monolog\Logger;
use Monolog\LogRecord; use Monolog\LogRecord;
@@ -24,18 +25,21 @@ class ChromePHPFormatter implements FormatterInterface
/** /**
* Translates Monolog log levels to Wildfire levels. * Translates Monolog log levels to Wildfire levels.
* *
* @var array<int, 'log'|'info'|'warn'|'error'> * @return 'log'|'info'|'warn'|'error'
*/ */
private $logLevels = [ private function toWildfireLevel(Level $level): string
Logger::DEBUG => 'log', {
Logger::INFO => 'info', return match ($level) {
Logger::NOTICE => 'info', Level::Debug => 'log',
Logger::WARNING => 'warn', Level::Info => 'info',
Logger::ERROR => 'error', Level::Notice => 'info',
Logger::CRITICAL => 'error', Level::Warning => 'warn',
Logger::ALERT => 'error', Level::Error => 'error',
Logger::EMERGENCY => 'error', Level::Critical => 'error',
]; Level::Alert => 'error',
Level::Emergency => 'error',
};
}
/** /**
* {@inheritDoc} * {@inheritDoc}
@@ -64,7 +68,7 @@ class ChromePHPFormatter implements FormatterInterface
$record->channel, $record->channel,
$message, $message,
$backtrace, $backtrace,
$this->logLevels[$record->level], $this->toWildfireLevel($record->level),
]; ];
} }

View File

@@ -45,7 +45,7 @@ class FlowdockFormatter implements FormatterInterface
{ {
$tags = [ $tags = [
'#logs', '#logs',
'#' . strtolower($record->levelName), '#' . strtolower($record->levelName->value),
'#' . $record->channel, '#' . $record->channel,
]; ];
@@ -56,7 +56,7 @@ class FlowdockFormatter implements FormatterInterface
$subject = sprintf( $subject = sprintf(
'in %s: %s - %s', 'in %s: %s - %s',
$this->source, $this->source,
$record->levelName, $record->levelName->value,
$this->getShortMessage($record->message) $this->getShortMessage($record->message)
); );

View File

@@ -60,7 +60,7 @@ class FluentdFormatter implements FormatterInterface
{ {
$tag = $record->channel; $tag = $record->channel;
if ($this->levelTag) { if ($this->levelTag) {
$tag .= '.' . strtolower($record->levelName); $tag .= '.' . strtolower($record->levelName->value);
} }
$message = [ $message = [
@@ -70,8 +70,8 @@ class FluentdFormatter implements FormatterInterface
]; ];
if (!$this->levelTag) { if (!$this->levelTag) {
$message['level'] = $record->level; $message['level'] = $record->level->value;
$message['level_name'] = $record->levelName; $message['level_name'] = $record->levelName->value;
} }
return Utils::jsonEncode([$tag, $record->datetime->getTimestamp(), $message]); return Utils::jsonEncode([$tag, $record->datetime->getTimestamp(), $message]);

View File

@@ -11,6 +11,7 @@
namespace Monolog\Formatter; namespace Monolog\Formatter;
use Monolog\Level;
use Monolog\Logger; use Monolog\Logger;
use Gelf\Message; use Gelf\Message;
use Monolog\Utils; use Monolog\Utils;
@@ -21,8 +22,6 @@ use Monolog\LogRecord;
* @see http://docs.graylog.org/en/latest/pages/gelf.html * @see http://docs.graylog.org/en/latest/pages/gelf.html
* *
* @author Matt Lehner <mlehner@gmail.com> * @author Matt Lehner <mlehner@gmail.com>
*
* @phpstan-import-type Level from \Monolog\Logger
*/ */
class GelfMessageFormatter extends NormalizerFormatter class GelfMessageFormatter extends NormalizerFormatter
{ {
@@ -50,21 +49,20 @@ class GelfMessageFormatter extends NormalizerFormatter
/** /**
* Translates Monolog log levels to Graylog2 log priorities. * Translates Monolog log levels to Graylog2 log priorities.
*
* @var array<int, int>
*
* @phpstan-var array<Level, int>
*/ */
private $logLevels = [ private function getGraylog2Priority(Level $level): int
Logger::DEBUG => 7, {
Logger::INFO => 6, return match ($level) {
Logger::NOTICE => 5, Level::Debug => 7,
Logger::WARNING => 4, Level::Info => 6,
Logger::ERROR => 3, Level::Notice => 5,
Logger::CRITICAL => 2, Level::Warning => 4,
Logger::ALERT => 1, Level::Error => 3,
Logger::EMERGENCY => 0, Level::Critical => 2,
]; Level::Alert => 1,
Level::Emergency => 0,
};
}
public function __construct(?string $systemName = null, ?string $extraPrefix = null, string $contextPrefix = 'ctxt_', ?int $maxLength = null) public function __construct(?string $systemName = null, ?string $extraPrefix = null, string $contextPrefix = 'ctxt_', ?int $maxLength = null)
{ {
@@ -101,7 +99,7 @@ class GelfMessageFormatter extends NormalizerFormatter
->setTimestamp($record->datetime) ->setTimestamp($record->datetime)
->setShortMessage((string) $record->message) ->setShortMessage((string) $record->message)
->setHost($this->systemName) ->setHost($this->systemName)
->setLevel($this->logLevels[$record->level]); ->setLevel($this->getGraylog2Priority($record->level));
// message length + system name length + 200 for padding / metadata // message length + system name length + 200 for padding / metadata
$len = 200 + strlen((string) $record->message) + strlen($this->systemName); $len = 200 + strlen((string) $record->message) + strlen($this->systemName);

View File

@@ -11,6 +11,7 @@
namespace Monolog\Formatter; namespace Monolog\Formatter;
use Monolog\Level;
use Monolog\Logger; use Monolog\Logger;
use Monolog\Utils; use Monolog\Utils;
use Monolog\LogRecord; use Monolog\LogRecord;
@@ -26,19 +27,20 @@ class HtmlFormatter extends NormalizerFormatter
{ {
/** /**
* Translates Monolog log levels to html color priorities. * Translates Monolog log levels to html color priorities.
*
* @var array<int, string>
*/ */
protected $logLevels = [ protected function getLevelColor(Level $level): string
Logger::DEBUG => '#CCCCCC', {
Logger::INFO => '#28A745', return match ($level) {
Logger::NOTICE => '#17A2B8', Level::Debug => '#CCCCCC',
Logger::WARNING => '#FFC107', Level::Info => '#28A745',
Logger::ERROR => '#FD7E14', Level::Notice => '#17A2B8',
Logger::CRITICAL => '#DC3545', Level::Warning => '#FFC107',
Logger::ALERT => '#821722', Level::Error => '#FD7E14',
Logger::EMERGENCY => '#000000', Level::Critical => '#DC3545',
]; Level::Alert => '#821722',
Level::Emergency => '#000000',
};
}
/** /**
* @param string|null $dateFormat The format of the timestamp: one supported by DateTime::format * @param string|null $dateFormat The format of the timestamp: one supported by DateTime::format
@@ -69,14 +71,13 @@ class HtmlFormatter extends NormalizerFormatter
* Create a HTML h1 tag * Create a HTML h1 tag
* *
* @param string $title Text to be in the h1 * @param string $title Text to be in the h1
* @param int $level Error level
* @return string * @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'); $title = htmlspecialchars($title, ENT_NOQUOTES, 'UTF-8');
return '<h1 style="background: '.$this->logLevels[$level].';color: #ffffff;padding: 5px;" class="monolog-output">'.$title.'</h1>'; return '<h1 style="background: '.$this->getLevelColor($level).';color: #ffffff;padding: 5px;" class="monolog-output">'.$title.'</h1>';
} }
/** /**
@@ -86,7 +87,7 @@ class HtmlFormatter extends NormalizerFormatter
*/ */
public function format(LogRecord $record): string public function format(LogRecord $record): string
{ {
$output = $this->addTitle($record->levelName, $record->level); $output = $this->addTitle($record->levelName->value, $record->level);
$output .= '<table cellspacing="1" width="100%" class="monolog-output">'; $output .= '<table cellspacing="1" width="100%" class="monolog-output">';
$output .= $this->addRow('Message', (string) $record->message); $output .= $this->addRow('Message', (string) $record->message);

View File

@@ -11,6 +11,7 @@
namespace Monolog\Formatter; namespace Monolog\Formatter;
use Monolog\Level;
use Monolog\Logger; use Monolog\Logger;
use Monolog\LogRecord; use Monolog\LogRecord;
@@ -20,27 +21,9 @@ use Monolog\LogRecord;
* @author Eric Clemmons (@ericclemmons) <eric@uxdriven.com> * @author Eric Clemmons (@ericclemmons) <eric@uxdriven.com>
* @author Christophe Coevoet <stof@notk.org> * @author Christophe Coevoet <stof@notk.org>
* @author Kirill chEbba Chebunin <iam@chebba.org> * @author Kirill chEbba Chebunin <iam@chebba.org>
*
* @phpstan-import-type Level from \Monolog\Logger
*/ */
class WildfireFormatter extends NormalizerFormatter class WildfireFormatter extends NormalizerFormatter
{ {
/**
* Translates Monolog log levels to Wildfire levels.
*
* @var array<Level, string>
*/
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 * @param string|null $dateFormat The format of the timestamp: one supported by DateTime::format
*/ */
@@ -52,6 +35,25 @@ class WildfireFormatter extends NormalizerFormatter
$this->removeJsonEncodeOption(JSON_UNESCAPED_UNICODE); $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} * {@inheritDoc}
* *
@@ -89,7 +91,7 @@ class WildfireFormatter extends NormalizerFormatter
$label = $record->channel .': '. $record->message; $label = $record->channel .': '. $record->message;
$message = $message['context']['table']; $message = $message['context']['table'];
} else { } else {
$type = $this->logLevels[$record->level]; $type = $this->toWildfireLevel($record->level);
$label = $record->channel; $label = $record->channel;
} }

View File

@@ -11,6 +11,8 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Level;
use Monolog\LevelName;
use Monolog\Logger; use Monolog\Logger;
use Monolog\ResettableInterface; use Monolog\ResettableInterface;
use Psr\Log\LogLevel; use Psr\Log\LogLevel;
@@ -20,27 +22,20 @@ use Monolog\LogRecord;
* Base Handler class providing basic level/bubble support * Base Handler class providing basic level/bubble support
* *
* @author Jordi Boggiano <j.boggiano@seld.be> * @author Jordi Boggiano <j.boggiano@seld.be>
*
* @phpstan-import-type Level from \Monolog\Logger
* @phpstan-import-type LevelName from \Monolog\Logger
*/ */
abstract class AbstractHandler extends Handler implements ResettableInterface abstract class AbstractHandler extends Handler implements ResettableInterface
{ {
/** protected Level $level = Level::Debug;
* @var int
* @phpstan-var Level
*/
protected $level = Logger::DEBUG;
/** @var bool */ /** @var bool */
protected $bubble = true; protected $bubble = true;
/** /**
* @param int|string $level The minimum logging level at which this handler will be triggered * @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 * @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<Level::VALUES>|value-of<LevelName::VALUES>|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->setLevel($level);
$this->bubble = $bubble; $this->bubble = $bubble;
@@ -51,7 +46,7 @@ abstract class AbstractHandler extends Handler implements ResettableInterface
*/ */
public function isHandling(LogRecord $record): bool public function isHandling(LogRecord $record): bool
{ {
return $record->level >= $this->level; return $record->level->value >= $this->level->value;
} }
/** /**
@@ -59,8 +54,10 @@ abstract class AbstractHandler extends Handler implements ResettableInterface
* *
* @param Level|LevelName|LogLevel::* $level Level or level name * @param Level|LevelName|LogLevel::* $level Level or level name
* @return self * @return self
*
* @phpstan-param value-of<Level::VALUES>|value-of<LevelName::VALUES>|Level|LevelName|LogLevel::* $level
*/ */
public function setLevel($level): self public function setLevel(int|string|Level|LevelName $level): self
{ {
$this->level = Logger::toMonologLevel($level); $this->level = Logger::toMonologLevel($level);
@@ -69,12 +66,8 @@ abstract class AbstractHandler extends Handler implements ResettableInterface
/** /**
* Gets minimum logging level at which this handler will be triggered. * 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; return $this->level;
} }

View File

@@ -20,9 +20,6 @@ use Monolog\LogRecord;
* *
* @author Jordi Boggiano <j.boggiano@seld.be> * @author Jordi Boggiano <j.boggiano@seld.be>
* @author Christophe Coevoet <stof@notk.org> * @author Christophe Coevoet <stof@notk.org>
*
* @phpstan-import-type LevelName from \Monolog\Logger
* @phpstan-import-type Level from \Monolog\Logger
*/ */
abstract class AbstractProcessingHandler extends AbstractHandler implements ProcessableHandlerInterface, FormattableHandlerInterface abstract class AbstractProcessingHandler extends AbstractHandler implements ProcessableHandlerInterface, FormattableHandlerInterface
{ {

View File

@@ -11,14 +11,12 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Logger; use Monolog\Level;
use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\FormatterInterface;
use Monolog\Formatter\LineFormatter; use Monolog\Formatter\LineFormatter;
/** /**
* Common syslog functionality * Common syslog functionality
*
* @phpstan-import-type Level from \Monolog\Logger
*/ */
abstract class AbstractSyslogHandler extends AbstractProcessingHandler abstract class AbstractSyslogHandler extends AbstractProcessingHandler
{ {
@@ -27,54 +25,55 @@ abstract class AbstractSyslogHandler extends AbstractProcessingHandler
/** /**
* Translates Monolog log levels to syslog log priorities. * Translates Monolog log levels to syslog log priorities.
* @var array
* @phpstan-var array<Level, int>
*/ */
protected $logLevels = [ protected function toSyslogPriority(Level $level): int
Logger::DEBUG => LOG_DEBUG, {
Logger::INFO => LOG_INFO, return match ($level) {
Logger::NOTICE => LOG_NOTICE, Level::Debug => \LOG_DEBUG,
Logger::WARNING => LOG_WARNING, Level::Info => \LOG_INFO,
Logger::ERROR => LOG_ERR, Level::Notice => \LOG_NOTICE,
Logger::CRITICAL => LOG_CRIT, Level::Warning => \LOG_WARNING,
Logger::ALERT => LOG_ALERT, Level::Error => \LOG_ERR,
Logger::EMERGENCY => LOG_EMERG, Level::Critical => \LOG_CRIT,
]; Level::Alert => \LOG_ALERT,
Level::Emergency => \LOG_EMERG,
};
}
/** /**
* List of valid log facility names. * List of valid log facility names.
* @var array<string, int> * @var array<string, int>
*/ */
protected $facilities = [ protected $facilities = [
'auth' => LOG_AUTH, 'auth' => \LOG_AUTH,
'authpriv' => LOG_AUTHPRIV, 'authpriv' => \LOG_AUTHPRIV,
'cron' => LOG_CRON, 'cron' => \LOG_CRON,
'daemon' => LOG_DAEMON, 'daemon' => \LOG_DAEMON,
'kern' => LOG_KERN, 'kern' => \LOG_KERN,
'lpr' => LOG_LPR, 'lpr' => \LOG_LPR,
'mail' => LOG_MAIL, 'mail' => \LOG_MAIL,
'news' => LOG_NEWS, 'news' => \LOG_NEWS,
'syslog' => LOG_SYSLOG, 'syslog' => \LOG_SYSLOG,
'user' => LOG_USER, 'user' => \LOG_USER,
'uucp' => LOG_UUCP, 'uucp' => \LOG_UUCP,
]; ];
/** /**
* @param string|int $facility Either one of the names of the keys in $this->facilities, or a LOG_* facility constant * @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); parent::__construct($level, $bubble);
if (!defined('PHP_WINDOWS_VERSION_BUILD')) { if (!defined('PHP_WINDOWS_VERSION_BUILD')) {
$this->facilities['local0'] = LOG_LOCAL0; $this->facilities['local0'] = \LOG_LOCAL0;
$this->facilities['local1'] = LOG_LOCAL1; $this->facilities['local1'] = \LOG_LOCAL1;
$this->facilities['local2'] = LOG_LOCAL2; $this->facilities['local2'] = \LOG_LOCAL2;
$this->facilities['local3'] = LOG_LOCAL3; $this->facilities['local3'] = \LOG_LOCAL3;
$this->facilities['local4'] = LOG_LOCAL4; $this->facilities['local4'] = \LOG_LOCAL4;
$this->facilities['local5'] = LOG_LOCAL5; $this->facilities['local5'] = \LOG_LOCAL5;
$this->facilities['local6'] = LOG_LOCAL6; $this->facilities['local6'] = \LOG_LOCAL6;
$this->facilities['local7'] = LOG_LOCAL7; $this->facilities['local7'] = \LOG_LOCAL7;
} else { } else {
$this->facilities['local0'] = 128; // LOG_LOCAL0 $this->facilities['local0'] = 128; // LOG_LOCAL0
$this->facilities['local1'] = 136; // LOG_LOCAL1 $this->facilities['local1'] = 136; // LOG_LOCAL1

View File

@@ -11,7 +11,7 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Logger; use Monolog\Level;
use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\FormatterInterface;
use Monolog\Formatter\JsonFormatter; use Monolog\Formatter\JsonFormatter;
use PhpAmqpLib\Message\AMQPMessage; 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 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 * @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) { if ($exchange instanceof AMQPChannel) {
$this->exchangeName = (string) $exchangeName; $this->exchangeName = (string) $exchangeName;
@@ -110,7 +110,7 @@ class AmqpHandler extends AbstractProcessingHandler
*/ */
protected function getRoutingKey(LogRecord $record): string 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); return strtolower($routingKey);
} }

View File

@@ -11,7 +11,8 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Logger; use Monolog\Level;
use Monolog\LevelName;
use Monolog\ResettableInterface; use Monolog\ResettableInterface;
use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\FormatterInterface;
use Monolog\LogRecord; 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 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 * @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); parent::__construct($level, $bubble);
$this->handler = $handler; $this->handler = $handler;
@@ -59,7 +60,7 @@ class BufferHandler extends AbstractHandler implements ProcessableHandlerInterfa
*/ */
public function handle(LogRecord $record): bool public function handle(LogRecord $record): bool
{ {
if ($record->level < $this->level) { if ($record->level->isLowerThan($this->level)) {
return false; return false;
} }

View File

@@ -13,7 +13,7 @@ namespace Monolog\Handler;
use Monolog\Formatter\ChromePHPFormatter; use Monolog\Formatter\ChromePHPFormatter;
use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\FormatterInterface;
use Monolog\Logger; use Monolog\Level;
use Monolog\Utils; use Monolog\Utils;
use Monolog\LogRecord; use Monolog\LogRecord;
use Monolog\DateTimeImmutable; use Monolog\DateTimeImmutable;
@@ -66,7 +66,7 @@ class ChromePHPHandler extends AbstractProcessingHandler
/** @var bool */ /** @var bool */
protected static $sendHeaders = true; 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); parent::__construct($level, $bubble);
if (!function_exists('json_encode')) { if (!function_exists('json_encode')) {
@@ -155,7 +155,7 @@ class ChromePHPHandler extends AbstractProcessingHandler
$record = new LogRecord( $record = new LogRecord(
message: 'Incomplete logs, chrome header size limit reached', message: 'Incomplete logs, chrome header size limit reached',
level: Logger::WARNING, level: Level::Warning,
channel: 'monolog', channel: 'monolog',
datetime: new DateTimeImmutable(true), datetime: new DateTimeImmutable(true),
); );

View File

@@ -13,7 +13,7 @@ namespace Monolog\Handler;
use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\FormatterInterface;
use Monolog\Formatter\JsonFormatter; use Monolog\Formatter\JsonFormatter;
use Monolog\Logger; use Monolog\Level;
use Monolog\LogRecord; use Monolog\LogRecord;
/** /**
@@ -29,7 +29,7 @@ class CouchDBHandler extends AbstractProcessingHandler
/** /**
* @param mixed[] $options * @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([ $this->options = array_merge([
'host' => 'localhost', 'host' => 'localhost',

View File

@@ -11,7 +11,7 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Logger; use Monolog\Level;
use Monolog\Utils; use Monolog\Utils;
use Monolog\LogRecord; use Monolog\LogRecord;
@@ -43,7 +43,7 @@ class CubeHandler extends AbstractProcessingHandler
* A valid url must consist of three parts : protocol://host:port * A valid url must consist of three parts : protocol://host:port
* Only valid protocols used by Cube are http and udp * 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); $urlInfo = parse_url($url);

View File

@@ -11,6 +11,8 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Level;
use Monolog\LevelName;
use Monolog\Logger; use Monolog\Logger;
use Psr\Log\LogLevel; use Psr\Log\LogLevel;
use Monolog\LogRecord; use Monolog\LogRecord;
@@ -34,8 +36,6 @@ use Monolog\LogRecord;
* same way. * same way.
* *
* @author Jordi Boggiano <j.boggiano@seld.be> * @author Jordi Boggiano <j.boggiano@seld.be>
* @phpstan-import-type LevelName from \Monolog\Logger
* @phpstan-import-type Level from \Monolog\Logger
*/ */
class DeduplicationHandler extends BufferHandler class DeduplicationHandler extends BufferHandler
{ {
@@ -62,15 +62,15 @@ class DeduplicationHandler extends BufferHandler
/** /**
* @param HandlerInterface $handler Handler. * @param HandlerInterface $handler Handler.
* @param string $deduplicationStore The file/path where the deduplication log should be kept * @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 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 * @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<Level::VALUES>|value-of<LevelName::VALUES>|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->deduplicationStore = $deduplicationStore === null ? sys_get_temp_dir() . '/monolog-dedup-' . substr(md5(__FILE__), 0, 20) .'.log' : $deduplicationStore;
$this->deduplicationLevel = Logger::toMonologLevel($deduplicationLevel); $this->deduplicationLevel = Logger::toMonologLevel($deduplicationLevel);
@@ -86,7 +86,7 @@ class DeduplicationHandler extends BufferHandler
$passthru = null; $passthru = null;
foreach ($this->buffer as $record) { foreach ($this->buffer as $record) {
if ($record->level >= $this->deduplicationLevel) { if ($record->level->value >= $this->deduplicationLevel->value) {
$passthru = $passthru || !$this->isDuplicate($record); $passthru = $passthru || !$this->isDuplicate($record);
if ($passthru) { if ($passthru) {
$this->appendRecord($record); $this->appendRecord($record);
@@ -124,7 +124,7 @@ class DeduplicationHandler extends BufferHandler
for ($i = count($store) - 1; $i >= 0; $i--) { for ($i = count($store) - 1; $i >= 0; $i--) {
list($timestamp, $level, $message) = explode(':', $store[$i], 3); 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; return true;
} }
@@ -174,6 +174,6 @@ class DeduplicationHandler extends BufferHandler
private function appendRecord(LogRecord $record): 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);
} }
} }

View File

@@ -11,7 +11,7 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Logger; use Monolog\Level;
use Monolog\Formatter\NormalizerFormatter; use Monolog\Formatter\NormalizerFormatter;
use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\FormatterInterface;
use Doctrine\CouchDB\CouchDBClient; use Doctrine\CouchDB\CouchDBClient;
@@ -27,7 +27,7 @@ class DoctrineCouchDBHandler extends AbstractProcessingHandler
/** @var CouchDBClient */ /** @var CouchDBClient */
private $client; 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; $this->client = $client;
parent::__construct($level, $bubble); parent::__construct($level, $bubble);

View File

@@ -16,7 +16,7 @@ use Aws\DynamoDb\DynamoDbClient;
use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\FormatterInterface;
use Aws\DynamoDb\Marshaler; use Aws\DynamoDb\Marshaler;
use Monolog\Formatter\ScalarFormatter; use Monolog\Formatter\ScalarFormatter;
use Monolog\Logger; use Monolog\Level;
use Monolog\LogRecord; use Monolog\LogRecord;
/** /**
@@ -44,7 +44,7 @@ class DynamoDbHandler extends AbstractProcessingHandler
*/ */
protected $marshaler; 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; $this->marshaler = new Marshaler;

View File

@@ -14,7 +14,7 @@ namespace Monolog\Handler;
use Elastica\Document; use Elastica\Document;
use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\FormatterInterface;
use Monolog\Formatter\ElasticaFormatter; use Monolog\Formatter\ElasticaFormatter;
use Monolog\Logger; use Monolog\Level;
use Elastica\Client; use Elastica\Client;
use Elastica\Exception\ExceptionInterface; use Elastica\Exception\ExceptionInterface;
use Monolog\LogRecord; use Monolog\LogRecord;
@@ -51,7 +51,7 @@ class ElasticaHandler extends AbstractProcessingHandler
* @param Client $client Elastica Client object * @param Client $client Elastica Client object
* @param mixed[] $options Handler configuration * @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); parent::__construct($level, $bubble);
$this->client = $client; $this->client = $client;

View File

@@ -13,7 +13,7 @@ namespace Monolog\Handler;
use Throwable; use Throwable;
use RuntimeException; use RuntimeException;
use Monolog\Logger; use Monolog\Level;
use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\FormatterInterface;
use Monolog\Formatter\ElasticsearchFormatter; use Monolog\Formatter\ElasticsearchFormatter;
use InvalidArgumentException; use InvalidArgumentException;
@@ -58,7 +58,7 @@ class ElasticsearchHandler extends AbstractProcessingHandler
* @param Client $client Elasticsearch Client object * @param Client $client Elasticsearch Client object
* @param mixed[] $options Handler configuration * @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); parent::__construct($level, $bubble);
$this->client = $client; $this->client = $client;

View File

@@ -13,7 +13,7 @@ namespace Monolog\Handler;
use Monolog\Formatter\LineFormatter; use Monolog\Formatter\LineFormatter;
use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\FormatterInterface;
use Monolog\Logger; use Monolog\Level;
use Monolog\Utils; use Monolog\Utils;
use Monolog\LogRecord; use Monolog\LogRecord;
@@ -36,7 +36,7 @@ class ErrorLogHandler extends AbstractProcessingHandler
* @param int $messageType Says where the error should go. * @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 * @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); parent::__construct($level, $bubble);

View File

@@ -11,6 +11,8 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Level;
use Monolog\LevelName;
use Monolog\Logger; use Monolog\Logger;
use Monolog\ResettableInterface; use Monolog\ResettableInterface;
use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\FormatterInterface;
@@ -24,8 +26,6 @@ use Monolog\LogRecord;
* *
* @author Hennadiy Verkh * @author Hennadiy Verkh
* @author Jordi Boggiano <j.boggiano@seld.be> * @author Jordi Boggiano <j.boggiano@seld.be>
* @phpstan-import-type Level from \Monolog\Logger
* @phpstan-import-type LevelName from \Monolog\Logger
*/ */
class FilterHandler extends Handler implements ProcessableHandlerInterface, ResettableInterface, FormattableHandlerInterface 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 * Minimum level for logs that are passed to handler
* *
* @var int[] * @var bool[] Map of Level value => true
* @phpstan-var array<Level, int> * @phpstan-var array<value-of<Level::VALUES>, true>
*/ */
protected $acceptedLevels; protected array $acceptedLevels;
/** /**
* Whether the messages that are handled can bubble up the stack or not * 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 * @phpstan-param (callable(LogRecord|null, HandlerInterface): HandlerInterface)|HandlerInterface $handler
* *
* @param callable|HandlerInterface $handler Handler or factory callable($record|null, $filterHandler). * @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|Level|LevelName|array<int|string|Level|LevelName|LogLevel::*> $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|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 * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
* *
* @phpstan-param Level|LevelName|LogLevel::*|array<Level|LevelName|LogLevel::*> $minLevelOrList * @phpstan-param value-of<Level::VALUES>|value-of<LevelName::VALUES>|Level|LevelName|LogLevel::*|array<value-of<Level::VALUES>|value-of<LevelName::VALUES>|Level|LevelName|LogLevel::*> $minLevelOrList
* @phpstan-param Level|LevelName|LogLevel::* $maxLevel * @phpstan-param value-of<Level::VALUES>|value-of<LevelName::VALUES>|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->handler = $handler;
$this->bubble = $bubble; $this->bubble = $bubble;
@@ -77,32 +77,33 @@ class FilterHandler extends Handler implements ProcessableHandlerInterface, Rese
} }
/** /**
* @phpstan-return array<int, Level> * @phpstan-return list<Level> List of levels
*/ */
public function getAcceptedLevels(): array 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|Level|LevelName|LogLevel::*|array<int|string|Level|LevelName|LogLevel::*> $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::* $maxLevel Maximum level or level name to accept, only used if $minLevelOrList is not an array
* *
* @phpstan-param Level|LevelName|LogLevel::*|array<Level|LevelName|LogLevel::*> $minLevelOrList * @phpstan-param value-of<Level::VALUES>|value-of<LevelName::VALUES>|Level|LevelName|LogLevel::*|array<value-of<Level::VALUES>|value-of<LevelName::VALUES>|Level|LevelName|LogLevel::*> $minLevelOrList
* @phpstan-param Level|LevelName|LogLevel::* $maxLevel * @phpstan-param value-of<Level::VALUES>|value-of<LevelName::VALUES>|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)) { if (is_array($minLevelOrList)) {
$acceptedLevels = array_map('Monolog\Logger::toMonologLevel', $minLevelOrList); $acceptedLevels = array_map(Logger::toMonologLevel(...), $minLevelOrList);
} else { } else {
$minLevelOrList = Logger::toMonologLevel($minLevelOrList); $minLevelOrList = Logger::toMonologLevel($minLevelOrList);
$maxLevel = Logger::toMonologLevel($maxLevel); $maxLevel = Logger::toMonologLevel($maxLevel);
$acceptedLevels = array_values(array_filter(Logger::getLevels(), function ($level) use ($minLevelOrList, $maxLevel) { $acceptedLevels = array_values(array_filter(Level::cases(), fn (Level $level) => $level->value >= $minLevelOrList->value && $level->value <= $maxLevel->value));
return $level >= $minLevelOrList && $level <= $maxLevel; }
})); $this->acceptedLevels = [];
foreach ($acceptedLevels as $level) {
$this->acceptedLevels[$level->value] = true;
} }
$this->acceptedLevels = array_flip($acceptedLevels);
return $this; return $this;
} }
@@ -112,7 +113,7 @@ class FilterHandler extends Handler implements ProcessableHandlerInterface, Rese
*/ */
public function isHandling(LogRecord $record): bool public function isHandling(LogRecord $record): bool
{ {
return isset($this->acceptedLevels[$record->level]); return isset($this->acceptedLevels[$record->level->value]);
} }
/** /**

View File

@@ -11,6 +11,8 @@
namespace Monolog\Handler\FingersCrossed; namespace Monolog\Handler\FingersCrossed;
use Monolog\Level;
use Monolog\LevelName;
use Monolog\Logger; use Monolog\Logger;
use Psr\Log\LogLevel; use Psr\Log\LogLevel;
use Monolog\LogRecord; use Monolog\LogRecord;
@@ -24,50 +26,45 @@ use Monolog\LogRecord;
* *
* <code> * <code>
* $activationStrategy = new ChannelLevelActivationStrategy( * $activationStrategy = new ChannelLevelActivationStrategy(
* Logger::CRITICAL, * Level::Critical,
* array( * array(
* 'request' => Logger::ALERT, * 'request' => Level::Alert,
* 'sensitive' => Logger::ERROR, * 'sensitive' => Level::Error,
* ) * )
* ); * );
* $handler = new FingersCrossedHandler(new StreamHandler('php://stderr'), $activationStrategy); * $handler = new FingersCrossedHandler(new StreamHandler('php://stderr'), $activationStrategy);
* </code> * </code>
* *
* @author Mike Meessen <netmikey@gmail.com> * @author Mike Meessen <netmikey@gmail.com>
* @phpstan-import-type Level from \Monolog\Logger
* @phpstan-import-type LevelName from \Monolog\Logger
*/ */
class ChannelLevelActivationStrategy implements ActivationStrategyInterface class ChannelLevelActivationStrategy implements ActivationStrategyInterface
{ {
/** private Level $defaultActionLevel;
* @var Level
*/
private $defaultActionLevel;
/** /**
* @var array<string, Level> * @var array<string, Level>
*/ */
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 int|string|Level|LevelName|LogLevel::* $defaultActionLevel The default action level to be used if the record's category doesn't match any
* @param array<string, int> $channelToActionLevel An array that maps channel names to action levels. * @param array<string, int|string|Level|LevelName|LogLevel::*> $channelToActionLevel An array that maps channel names to action levels.
* *
* @phpstan-param array<string, Level> $channelToActionLevel * @phpstan-param value-of<Level::VALUES>|value-of<LevelName::VALUES>|Level|LevelName|LogLevel::* $defaultActionLevel
* @phpstan-param Level|LevelName|LogLevel::* $defaultActionLevel * @phpstan-param array<string, value-of<Level::VALUES>|value-of<LevelName::VALUES>|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->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 public function isHandlerActivated(LogRecord $record): bool
{ {
if (isset($this->channelToActionLevel[$record->channel])) { 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;
} }
} }

View File

@@ -11,37 +11,33 @@
namespace Monolog\Handler\FingersCrossed; namespace Monolog\Handler\FingersCrossed;
use Monolog\Level;
use Monolog\LevelName;
use Monolog\LogRecord;
use Monolog\Logger; use Monolog\Logger;
use Psr\Log\LogLevel; use Psr\Log\LogLevel;
use Monolog\LogRecord;
/** /**
* Error level based activation strategy. * Error level based activation strategy.
* *
* @author Johannes M. Schmitt <schmittjoh@gmail.com> * @author Johannes M. Schmitt <schmittjoh@gmail.com>
*
* @phpstan-import-type Level from \Monolog\Logger
* @phpstan-import-type LevelName from \Monolog\Logger
*/ */
class ErrorLevelActivationStrategy implements ActivationStrategyInterface class ErrorLevelActivationStrategy implements ActivationStrategyInterface
{ {
/** private Level $actionLevel;
* @var Level
*/
private $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<Level::VALUES>|value-of<LevelName::VALUES>|Level|LevelName|LogLevel::* $actionLevel
*/ */
public function __construct($actionLevel) public function __construct(int|string|Level|LevelName $actionLevel)
{ {
$this->actionLevel = Logger::toMonologLevel($actionLevel); $this->actionLevel = Logger::toMonologLevel($actionLevel);
} }
public function isHandlerActivated(LogRecord $record): bool public function isHandlerActivated(LogRecord $record): bool
{ {
return $record->level >= $this->actionLevel; return $record->level->value >= $this->actionLevel->value;
} }
} }

View File

@@ -13,6 +13,8 @@ namespace Monolog\Handler;
use Monolog\Handler\FingersCrossed\ErrorLevelActivationStrategy; use Monolog\Handler\FingersCrossed\ErrorLevelActivationStrategy;
use Monolog\Handler\FingersCrossed\ActivationStrategyInterface; use Monolog\Handler\FingersCrossed\ActivationStrategyInterface;
use Monolog\Level;
use Monolog\LevelName;
use Monolog\Logger; use Monolog\Logger;
use Monolog\ResettableInterface; use Monolog\ResettableInterface;
use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\FormatterInterface;
@@ -34,8 +36,6 @@ use Monolog\LogRecord;
* Monolog\Handler\FingersCrossed\ namespace. * Monolog\Handler\FingersCrossed\ namespace.
* *
* @author Jordi Boggiano <j.boggiano@seld.be> * @author Jordi Boggiano <j.boggiano@seld.be>
* @phpstan-import-type Level from \Monolog\Logger
* @phpstan-import-type LevelName from \Monolog\Logger
*/ */
class FingersCrossedHandler extends Handler implements ProcessableHandlerInterface, ResettableInterface, FormattableHandlerInterface class FingersCrossedHandler extends Handler implements ProcessableHandlerInterface, ResettableInterface, FormattableHandlerInterface
{ {
@@ -56,11 +56,7 @@ class FingersCrossedHandler extends Handler implements ProcessableHandlerInterfa
protected $buffer = []; protected $buffer = [];
/** @var bool */ /** @var bool */
protected $stopBuffering; protected $stopBuffering;
/** protected Level|null $passthruLevel = null;
* @var ?int
* @phpstan-var ?Level
*/
protected $passthruLevel;
/** @var bool */ /** @var bool */
protected $bubble; protected $bubble;
@@ -68,19 +64,19 @@ class FingersCrossedHandler extends Handler implements ProcessableHandlerInterfa
* @phpstan-param (callable(LogRecord|null, HandlerInterface): HandlerInterface)|HandlerInterface $handler * @phpstan-param (callable(LogRecord|null, HandlerInterface): HandlerInterface)|HandlerInterface $handler
* *
* @param callable|HandlerInterface $handler Handler or factory callable($record|null, $fingersCrossedHandler). * @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 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 $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 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 value-of<Level::VALUES>|value-of<LevelName::VALUES>|Level|LevelName|LogLevel::*|ActivationStrategyInterface $activationStrategy
* @phpstan-param Level|LevelName|LogLevel::*|ActivationStrategyInterface $activationStrategy * @phpstan-param value-of<Level::VALUES>|value-of<LevelName::VALUES>|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) { if (null === $activationStrategy) {
$activationStrategy = new ErrorLevelActivationStrategy(Logger::WARNING); $activationStrategy = new ErrorLevelActivationStrategy(Level::Warning);
} }
// convert simple int activationStrategy to an object // convert simple int activationStrategy to an object

View File

@@ -13,7 +13,7 @@ namespace Monolog\Handler;
use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\FormatterInterface;
use Monolog\Formatter\LineFormatter; use Monolog\Formatter\LineFormatter;
use Monolog\Logger; use Monolog\Level;
use Monolog\LogRecord; use Monolog\LogRecord;
/** /**
@@ -46,7 +46,7 @@ class FleepHookHandler extends SocketHandler
*/ */
public function __construct( public function __construct(
string $token, string $token,
$level = Logger::DEBUG, $level = Level::Debug,
bool $bubble = true, bool $bubble = true,
bool $persistent = false, bool $persistent = false,
float $timeout = 0.0, float $timeout = 0.0,

View File

@@ -11,7 +11,7 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Logger; use Monolog\Level;
use Monolog\Utils; use Monolog\Utils;
use Monolog\Formatter\FlowdockFormatter; use Monolog\Formatter\FlowdockFormatter;
use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\FormatterInterface;
@@ -40,7 +40,7 @@ class FlowdockHandler extends SocketHandler
*/ */
public function __construct( public function __construct(
string $apiToken, string $apiToken,
$level = Logger::DEBUG, $level = Level::Debug,
bool $bubble = true, bool $bubble = true,
bool $persistent = false, bool $persistent = false,
float $timeout = 0.0, float $timeout = 0.0,

View File

@@ -12,7 +12,7 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Gelf\PublisherInterface; use Gelf\PublisherInterface;
use Monolog\Logger; use Monolog\Level;
use Monolog\Formatter\GelfMessageFormatter; use Monolog\Formatter\GelfMessageFormatter;
use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\FormatterInterface;
use Monolog\LogRecord; use Monolog\LogRecord;
@@ -33,7 +33,7 @@ class GelfHandler extends AbstractProcessingHandler
/** /**
* @param PublisherInterface $publisher a gelf publisher object * @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); parent::__construct($level, $bubble);

View File

@@ -17,8 +17,6 @@ use Monolog\LogRecord;
* Interface that all Monolog Handlers must implement * Interface that all Monolog Handlers must implement
* *
* @author Jordi Boggiano <j.boggiano@seld.be> * @author Jordi Boggiano <j.boggiano@seld.be>
*
* @phpstan-import-type Level from \Monolog\Logger
*/ */
interface HandlerInterface interface HandlerInterface
{ {

View File

@@ -11,7 +11,7 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Logger; use Monolog\Level;
use Monolog\Utils; use Monolog\Utils;
use Monolog\LogRecord; 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 $eventName The name of the IFTTT Maker event that should be triggered
* @param string $secretKey A valid IFTTT secret key * @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')) { if (!extension_loaded('curl')) {
throw new MissingExtensionException('The curl extension is needed to use the IFTTTHandler'); throw new MissingExtensionException('The curl extension is needed to use the IFTTTHandler');

View File

@@ -11,7 +11,7 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Logger; use Monolog\Level;
use Monolog\LogRecord; use Monolog\LogRecord;
/** /**
@@ -38,7 +38,7 @@ class InsightOpsHandler extends SocketHandler
string $token, string $token,
string $region = 'us', string $region = 'us',
bool $useSSL = true, bool $useSSL = true,
$level = Logger::DEBUG, $level = Level::Debug,
bool $bubble = true, bool $bubble = true,
bool $persistent = false, bool $persistent = false,
float $timeout = 0.0, float $timeout = 0.0,

View File

@@ -11,7 +11,7 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Logger; use Monolog\Level;
use Monolog\LogRecord; use Monolog\LogRecord;
/** /**
@@ -34,7 +34,7 @@ class LogEntriesHandler extends SocketHandler
public function __construct( public function __construct(
string $token, string $token,
bool $useSSL = true, bool $useSSL = true,
$level = Logger::DEBUG, $level = Level::Debug,
bool $bubble = true, bool $bubble = true,
string $host = 'data.logentries.com', string $host = 'data.logentries.com',
bool $persistent = false, bool $persistent = false,

View File

@@ -11,7 +11,7 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Logger; use Monolog\Level;
use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\FormatterInterface;
use Monolog\Formatter\LogglyFormatter; use Monolog\Formatter\LogglyFormatter;
use function array_key_exists; use function array_key_exists;
@@ -49,7 +49,7 @@ class LogglyHandler extends AbstractProcessingHandler
* *
* @throws MissingExtensionException If the curl extension is missing * @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')) { if (!extension_loaded('curl')) {
throw new MissingExtensionException('The curl extension is needed to use the LogglyHandler'); throw new MissingExtensionException('The curl extension is needed to use the LogglyHandler');

View File

@@ -11,7 +11,7 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Logger; use Monolog\Level;
use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\FormatterInterface;
use Monolog\Formatter\LogmaticFormatter; use Monolog\Formatter\LogmaticFormatter;
use Monolog\LogRecord; use Monolog\LogRecord;
@@ -49,7 +49,7 @@ class LogmaticHandler extends SocketHandler
string $hostname = '', string $hostname = '',
string $appname = '', string $appname = '',
bool $useSSL = true, bool $useSSL = true,
$level = Logger::DEBUG, $level = Level::Debug,
bool $bubble = true, bool $bubble = true,
bool $persistent = false, bool $persistent = false,
float $timeout = 0.0, float $timeout = 0.0,

View File

@@ -30,7 +30,7 @@ abstract class MailHandler extends AbstractProcessingHandler
$messages = []; $messages = [];
foreach ($records as $record) { foreach ($records as $record) {
if ($record->level < $this->level) { if ($record->level->isLowerThan($this->level)) {
continue; continue;
} }
@@ -68,7 +68,7 @@ abstract class MailHandler extends AbstractProcessingHandler
{ {
$highestRecord = null; $highestRecord = null;
foreach ($records as $record) { foreach ($records as $record) {
if ($highestRecord === null || $highestRecord['level'] < $record->level) { if ($highestRecord === null || $record->level->isHigherThan($highestRecord->level)) {
$highestRecord = $record; $highestRecord = $record;
} }
} }

View File

@@ -11,7 +11,7 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Logger; use Monolog\Level;
use Swift; use Swift;
use Swift_Message; use Swift_Message;
@@ -33,7 +33,7 @@ class MandrillHandler extends MailHandler
* @param string $apiKey A valid Mandrill API key * @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 * @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); parent::__construct($level, $bubble);

View File

@@ -14,7 +14,7 @@ namespace Monolog\Handler;
use MongoDB\Driver\BulkWrite; use MongoDB\Driver\BulkWrite;
use MongoDB\Driver\Manager; use MongoDB\Driver\Manager;
use MongoDB\Client; use MongoDB\Client;
use Monolog\Logger; use Monolog\Level;
use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\FormatterInterface;
use Monolog\Formatter\MongoDBFormatter; use Monolog\Formatter\MongoDBFormatter;
use Monolog\LogRecord; use Monolog\LogRecord;
@@ -47,7 +47,7 @@ class MongoDBHandler extends AbstractProcessingHandler
* @param string $database Database name * @param string $database Database name
* @param string $collection Collection 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)) { if (!($mongodb instanceof Client || $mongodb instanceof Manager)) {
throw new \InvalidArgumentException('MongoDB\Client or MongoDB\Driver\Manager instance required'); throw new \InvalidArgumentException('MongoDB\Client or MongoDB\Driver\Manager instance required');

View File

@@ -11,7 +11,7 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Logger; use Monolog\Level;
use Monolog\Formatter\LineFormatter; use Monolog\Formatter\LineFormatter;
/** /**
@@ -70,7 +70,7 @@ class NativeMailerHandler extends MailHandler
* @param string $from The sender of the mail * @param string $from The sender of the mail
* @param int $maxColumnWidth The maximum column width that the message lines will have * @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); parent::__construct($level, $bubble);
$this->to = (array) $to; $this->to = (array) $to;

View File

@@ -11,7 +11,7 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Logger; use Monolog\Level;
use Monolog\Utils; use Monolog\Utils;
use Monolog\Formatter\NormalizerFormatter; use Monolog\Formatter\NormalizerFormatter;
use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\FormatterInterface;
@@ -58,7 +58,7 @@ class NewRelicHandler extends AbstractProcessingHandler
* @param string|null $transactionName * @param string|null $transactionName
*/ */
public function __construct( public function __construct(
$level = Logger::ERROR, $level = Level::Error,
bool $bubble = true, bool $bubble = true,
?string $appName = null, ?string $appName = null,
bool $explodeArrays = false, bool $explodeArrays = false,

View File

@@ -11,8 +11,10 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Logger; use Monolog\Level;
use Monolog\LevelName;
use Psr\Log\LogLevel; use Psr\Log\LogLevel;
use Monolog\Logger;
use Monolog\LogRecord; use Monolog\LogRecord;
/** /**
@@ -22,23 +24,17 @@ use Monolog\LogRecord;
* to put on top of an existing stack to override it temporarily. * to put on top of an existing stack to override it temporarily.
* *
* @author Jordi Boggiano <j.boggiano@seld.be> * @author Jordi Boggiano <j.boggiano@seld.be>
*
* @phpstan-import-type Level from \Monolog\Logger
* @phpstan-import-type LevelName from \Monolog\Logger
*/ */
class NullHandler extends Handler class NullHandler extends Handler
{ {
/** private Level $level;
* @var int
*/
private $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<Level::VALUES>|value-of<LevelName::VALUES>|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); $this->level = Logger::toMonologLevel($level);
} }
@@ -48,7 +44,7 @@ class NullHandler extends Handler
*/ */
public function isHandling(LogRecord $record): bool public function isHandling(LogRecord $record): bool
{ {
return $record->level >= $this->level; return $record->level->value >= $this->level->value;
} }
/** /**
@@ -56,6 +52,6 @@ class NullHandler extends Handler
*/ */
public function handle(LogRecord $record): bool public function handle(LogRecord $record): bool
{ {
return $record->level >= $this->level; return $record->level->value >= $this->level->value;
} }
} }

View File

@@ -11,7 +11,7 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Logger; use Monolog\Level;
use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\FormatterInterface;
use Monolog\LogRecord; use Monolog\LogRecord;
@@ -28,7 +28,7 @@ use Monolog\LogRecord;
* $handler = new SomeHandler(...) * $handler = new SomeHandler(...)
* *
* // Pass all warnings to the handler when more than 10 & all error messages when more then 5 * // 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); * $log->pushHandler($overflow);
*``` *```
@@ -40,17 +40,8 @@ class OverflowHandler extends AbstractHandler implements FormattableHandlerInter
/** @var HandlerInterface */ /** @var HandlerInterface */
private $handler; private $handler;
/** @var int[] */ /** @var array<int, int> */
private $thresholdMap = [ 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,
];
/** /**
* Buffer of all messages passed to the handler before the threshold was reached * 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 HandlerInterface $handler
* @param int[] $thresholdMap Dictionary of logger level => threshold * @param array<int, int> $thresholdMap Dictionary of log level value => threshold
*/ */
public function __construct( public function __construct(
HandlerInterface $handler, HandlerInterface $handler,
array $thresholdMap = [], array $thresholdMap = [],
$level = Logger::DEBUG, $level = Level::Debug,
bool $bubble = true bool $bubble = true
) { ) {
$this->handler = $handler; $this->handler = $handler;
@@ -90,11 +81,11 @@ class OverflowHandler extends AbstractHandler implements FormattableHandlerInter
*/ */
public function handle(LogRecord $record): bool public function handle(LogRecord $record): bool
{ {
if ($record->level < $this->level) { if ($record->level->isLowerThan($this->level)) {
return false; return false;
} }
$level = $record->level; $level = $record->level->value;
if (!isset($this->thresholdMap[$level])) { if (!isset($this->thresholdMap[$level])) {
$this->thresholdMap[$level] = 0; $this->thresholdMap[$level] = 0;

View File

@@ -13,7 +13,7 @@ namespace Monolog\Handler;
use Monolog\Formatter\LineFormatter; use Monolog\Formatter\LineFormatter;
use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\FormatterInterface;
use Monolog\Logger; use Monolog\Level;
use Monolog\Utils; use Monolog\Utils;
use PhpConsole\Connector; use PhpConsole\Connector;
use PhpConsole\Handler as VendorPhpConsoleHandler; use PhpConsole\Handler as VendorPhpConsoleHandler;
@@ -73,7 +73,7 @@ class PHPConsoleHandler extends AbstractProcessingHandler
* @param Connector|null $connector Instance of \PhpConsole\Connector class (optional) * @param Connector|null $connector Instance of \PhpConsole\Connector class (optional)
* @throws \RuntimeException * @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')) { if (!class_exists('PhpConsole\Connector')) {
throw new \RuntimeException('PHP Console library not found. See https://github.com/barbushin/php-console#installation'); throw new \RuntimeException('PHP Console library not found. See https://github.com/barbushin/php-console#installation');
@@ -180,7 +180,7 @@ class PHPConsoleHandler extends AbstractProcessingHandler
*/ */
protected function write(LogRecord $record): void protected function write(LogRecord $record): void
{ {
if ($record->level < Logger::NOTICE) { if ($record->level->isLowerThan(Level::Notice)) {
$this->handleDebugRecord($record); $this->handleDebugRecord($record);
} elseif (isset($record->context['exception']) && $record->context['exception'] instanceof \Throwable) { } elseif (isset($record->context['exception']) && $record->context['exception'] instanceof \Throwable) {
$this->handleExceptionRecord($record); $this->handleExceptionRecord($record);
@@ -239,7 +239,7 @@ class PHPConsoleHandler extends AbstractProcessingHandler
} }
} }
return [$tags ?: strtolower($record->levelName), $filteredContext]; return [$tags ?: strtolower($record->levelName->value), $filteredContext];
} }
/** /**

View File

@@ -11,7 +11,7 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Logger; use Monolog\Level;
use Monolog\LogRecord; 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. * @param string|null $cwd "Current working directory" (CWD) for the process to be executed in.
* @throws \InvalidArgumentException * @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 === '') { if ($command === '') {
throw new \InvalidArgumentException('The command argument must be a non-empty string.'); throw new \InvalidArgumentException('The command argument must be a non-empty string.');

View File

@@ -11,7 +11,7 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Logger; use Monolog\Level;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\FormatterInterface;
use Monolog\LogRecord; 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 * @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); parent::__construct($level, $bubble);
@@ -60,9 +60,9 @@ class PsrHandler extends AbstractHandler implements FormattableHandlerInterface
if ($this->formatter) { if ($this->formatter) {
$formatted = $this->formatter->format($record); $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 { } 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; return false === $this->bubble;

View File

@@ -11,6 +11,8 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Level;
use Monolog\LevelName;
use Monolog\Logger; use Monolog\Logger;
use Monolog\Utils; use Monolog\Utils;
use Psr\Log\LogLevel; use Psr\Log\LogLevel;
@@ -21,9 +23,6 @@ use Monolog\LogRecord;
* *
* @author Sebastian Göttschkes <sebastian.goettschkes@googlemail.com> * @author Sebastian Göttschkes <sebastian.goettschkes@googlemail.com>
* @see https://www.pushover.net/api * @see https://www.pushover.net/api
*
* @phpstan-import-type Level from \Monolog\Logger
* @phpstan-import-type LevelName from \Monolog\Logger
*/ */
class PushoverHandler extends SocketHandler class PushoverHandler extends SocketHandler
{ {
@@ -40,10 +39,8 @@ class PushoverHandler extends SocketHandler
/** @var int */ /** @var int */
private $expire; private $expire;
/** @var int */ private Level $highPriorityLevel;
private $highPriorityLevel; private Level $emergencyLevel;
/** @var int */
private $emergencyLevel;
/** @var bool */ /** @var bool */
private $useFormattedMessage = false; private $useFormattedMessage = false;
@@ -85,28 +82,30 @@ class PushoverHandler extends SocketHandler
* @param string|null $title Title sent to the Pushover API * @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 * @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. * 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 * @param int $retry The retry parameter specifies how often (in seconds) the Pushover servers will
* send the same notification to the user. * send the same notification to the user.
* @param int $expire The expire parameter specifies how many seconds your notification will continue * @param int $expire The expire parameter specifies how many seconds your notification will continue
* to be retried for (every retry seconds). * 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<int|string> $users * @phpstan-param string|array<int|string> $users
* @phpstan-param Level|LevelName|LogLevel::* $highPriorityLevel * @phpstan-param value-of<Level::VALUES>|value-of<LevelName::VALUES>|Level|LevelName|LogLevel::* $highPriorityLevel
* @phpstan-param Level|LevelName|LogLevel::* $emergencyLevel * @phpstan-param value-of<Level::VALUES>|value-of<LevelName::VALUES>|Level|LevelName|LogLevel::* $emergencyLevel
*/ */
public function __construct( public function __construct(
string $token, string $token,
$users, $users,
?string $title = null, ?string $title = null,
$level = Logger::CRITICAL, int|string|Level|LevelName $level = Level::Critical,
bool $bubble = true, bool $bubble = true,
bool $useSSL = true, bool $useSSL = true,
$highPriorityLevel = Logger::CRITICAL, int|string|Level|LevelName $highPriorityLevel = Level::Critical,
$emergencyLevel = Logger::EMERGENCY, int|string|Level|LevelName $emergencyLevel = Level::Emergency,
int $retry = 30, int $retry = 30,
int $expire = 25200, int $expire = 25200,
bool $persistent = false, bool $persistent = false,
@@ -161,11 +160,11 @@ class PushoverHandler extends SocketHandler
'timestamp' => $timestamp, 'timestamp' => $timestamp,
]; ];
if (isset($record->level) && $record->level >= $this->emergencyLevel) { if ($record->level->value >= $this->emergencyLevel->value) {
$dataArray['priority'] = 2; $dataArray['priority'] = 2;
$dataArray['retry'] = $this->retry; $dataArray['retry'] = $this->retry;
$dataArray['expire'] = $this->expire; $dataArray['expire'] = $this->expire;
} elseif (isset($record->level) && $record->level >= $this->highPriorityLevel) { } elseif ($record->level->value >= $this->highPriorityLevel->value) {
$dataArray['priority'] = 1; $dataArray['priority'] = 1;
} }
@@ -208,25 +207,25 @@ class PushoverHandler extends SocketHandler
} }
/** /**
* @param int|string $value * @param int|string|Level|LevelName|LogLevel::* $level
* *
* @phpstan-param Level|LevelName|LogLevel::* $value * @phpstan-param value-of<Level::VALUES>|value-of<LevelName::VALUES>|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; return $this;
} }
/** /**
* @param int|string $value * @param int|string|Level|LevelName|LogLevel::* $level
* *
* @phpstan-param Level|LevelName|LogLevel::* $value * @phpstan-param value-of<Level::VALUES>|value-of<LevelName::VALUES>|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; return $this;
} }
@@ -234,9 +233,9 @@ class PushoverHandler extends SocketHandler
/** /**
* Use the formatted message? * Use the formatted message?
*/ */
public function useFormattedMessage(bool $value): self public function useFormattedMessage(bool $useFormattedMessage): self
{ {
$this->useFormattedMessage = $value; $this->useFormattedMessage = $useFormattedMessage;
return $this; return $this;
} }

View File

@@ -13,7 +13,7 @@ namespace Monolog\Handler;
use Monolog\Formatter\LineFormatter; use Monolog\Formatter\LineFormatter;
use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\FormatterInterface;
use Monolog\Logger; use Monolog\Level;
use Monolog\LogRecord; use Monolog\LogRecord;
/** /**
@@ -41,7 +41,7 @@ class RedisHandler extends AbstractProcessingHandler
* @param string $key The key name to push records to * @param string $key The key name to push records to
* @param int $capSize Number of entries to limit list size to, 0 = unlimited * @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))) { if (!(($redis instanceof \Predis\Client) || ($redis instanceof \Redis))) {
throw new \InvalidArgumentException('Predis\Client or Redis instance required'); throw new \InvalidArgumentException('Predis\Client or Redis instance required');

View File

@@ -13,7 +13,7 @@ namespace Monolog\Handler;
use Monolog\Formatter\LineFormatter; use Monolog\Formatter\LineFormatter;
use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\FormatterInterface;
use Monolog\Logger; use Monolog\Level;
use Monolog\LogRecord; use Monolog\LogRecord;
/** /**
@@ -22,7 +22,7 @@ use Monolog\LogRecord;
* usage example: * usage example:
* *
* $log = new Logger('application'); * $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); * $log->pushHandler($redis);
* *
* @author Gaëtan Faugère <gaetan@fauge.re> * @author Gaëtan Faugère <gaetan@fauge.re>
@@ -38,7 +38,7 @@ class RedisPubSubHandler extends AbstractProcessingHandler
* @param \Predis\Client<\Predis\Client>|\Redis $redis The redis instance * @param \Predis\Client<\Predis\Client>|\Redis $redis The redis instance
* @param string $key The channel key to publish records to * @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))) { if (!(($redis instanceof \Predis\Client) || ($redis instanceof \Redis))) {
throw new \InvalidArgumentException('Predis\Client or Redis instance required'); throw new \InvalidArgumentException('Predis\Client or Redis instance required');

View File

@@ -11,9 +11,10 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Level;
use Monolog\LevelName;
use Rollbar\RollbarLogger; use Rollbar\RollbarLogger;
use Throwable; use Throwable;
use Monolog\Logger;
use Monolog\LogRecord; use Monolog\LogRecord;
/** /**
@@ -39,18 +40,6 @@ class RollbarHandler extends AbstractProcessingHandler
*/ */
protected $rollbarLogger; 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 * 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 * @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; $this->rollbarLogger = $rollbarLogger;
parent::__construct($level, $bubble); 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} * {@inheritDoc}
*/ */
@@ -84,7 +92,7 @@ class RollbarHandler extends AbstractProcessingHandler
$context = $record->context; $context = $record->context;
$context = array_merge($context, $record->extra, [ $context = array_merge($context, $record->extra, [
'level' => $this->levelMap[$record->level], 'level' => $this->toRollbarLevel($record->level),
'monolog_level' => $record->levelName, 'monolog_level' => $record->levelName,
'channel' => $record->channel, 'channel' => $record->channel,
'datetime' => $record->datetime->format('U'), 'datetime' => $record->datetime->format('U'),

View File

@@ -12,7 +12,7 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use InvalidArgumentException; use InvalidArgumentException;
use Monolog\Logger; use Monolog\Level;
use Monolog\Utils; use Monolog\Utils;
use Monolog\LogRecord; 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 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 * @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->filename = Utils::canonicalizePath($filename);
$this->maxFiles = $maxFiles; $this->maxFiles = $maxFiles;

View File

@@ -27,7 +27,6 @@ use Monolog\LogRecord;
* *
* @author Bryan Davis <bd808@wikimedia.org> * @author Bryan Davis <bd808@wikimedia.org>
* @author Kunal Mehta <legoktm@gmail.com> * @author Kunal Mehta <legoktm@gmail.com>
* @phpstan-import-type Level from \Monolog\Logger
*/ */
class SamplingHandler extends AbstractHandler implements ProcessableHandlerInterface, FormattableHandlerInterface class SamplingHandler extends AbstractHandler implements ProcessableHandlerInterface, FormattableHandlerInterface
{ {

View File

@@ -11,7 +11,7 @@
namespace Monolog\Handler; 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 * 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|string[] $to The recipients of the email
* @param string $subject The subject of the mail * @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')) { if (!extension_loaded('curl')) {
throw new MissingExtensionException('The curl extension is needed to use the SendGridHandler'); throw new MissingExtensionException('The curl extension is needed to use the SendGridHandler');

View File

@@ -11,7 +11,7 @@
namespace Monolog\Handler\Slack; namespace Monolog\Handler\Slack;
use Monolog\Logger; use Monolog\Level;
use Monolog\Utils; use Monolog\Utils;
use Monolog\Formatter\NormalizerFormatter; use Monolog\Formatter\NormalizerFormatter;
use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\FormatterInterface;
@@ -145,7 +145,7 @@ class SlackRecord
$attachment = array( $attachment = array(
'fallback' => $message, 'fallback' => $message,
'text' => $message, 'text' => $message,
'color' => $this->getAttachmentColor($recordData['level']), 'color' => $this->getAttachmentColor($record->level),
'fields' => array(), 'fields' => array(),
'mrkdwn_in' => array('fields'), 'mrkdwn_in' => array('fields'),
'ts' => $recordData['datetime']->getTimestamp(), 'ts' => $recordData['datetime']->getTimestamp(),
@@ -201,18 +201,14 @@ class SlackRecord
* Returns a Slack message attachment color associated with * Returns a Slack message attachment color associated with
* provided level. * provided level.
*/ */
public function getAttachmentColor(int $level): string public function getAttachmentColor(Level $level): string
{ {
switch (true) { return match ($level) {
case $level >= Logger::ERROR: Level::Error, Level::Critical, Level::Alert, Level::Emergency => static::COLOR_DANGER,
return static::COLOR_DANGER; Level::Warning => static::COLOR_WARNING,
case $level >= Logger::WARNING: Level::Info, Level::Notice => static::COLOR_GOOD,
return static::COLOR_WARNING; Level::Debug => static::COLOR_DEFAULT
case $level >= Logger::INFO: };
return static::COLOR_GOOD;
default:
return static::COLOR_DEFAULT;
}
} }
/** /**

View File

@@ -12,7 +12,7 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\FormatterInterface;
use Monolog\Logger; use Monolog\Level;
use Monolog\Utils; use Monolog\Utils;
use Monolog\Handler\Slack\SlackRecord; use Monolog\Handler\Slack\SlackRecord;
use Monolog\LogRecord; use Monolog\LogRecord;
@@ -54,7 +54,7 @@ class SlackHandler extends SocketHandler
?string $username = null, ?string $username = null,
bool $useAttachment = true, bool $useAttachment = true,
?string $iconEmoji = null, ?string $iconEmoji = null,
$level = Logger::CRITICAL, $level = Level::Critical,
bool $bubble = true, bool $bubble = true,
bool $useShortAttachment = false, bool $useShortAttachment = false,
bool $includeContextAndExtra = false, bool $includeContextAndExtra = false,

View File

@@ -12,7 +12,7 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\FormatterInterface;
use Monolog\Logger; use Monolog\Level;
use Monolog\Utils; use Monolog\Utils;
use Monolog\Handler\Slack\SlackRecord; use Monolog\Handler\Slack\SlackRecord;
use Monolog\LogRecord; use Monolog\LogRecord;
@@ -55,7 +55,7 @@ class SlackWebhookHandler extends AbstractProcessingHandler
?string $iconEmoji = null, ?string $iconEmoji = null,
bool $useShortAttachment = false, bool $useShortAttachment = false,
bool $includeContextAndExtra = false, bool $includeContextAndExtra = false,
$level = Logger::CRITICAL, $level = Level::Critical,
bool $bubble = true, bool $bubble = true,
array $excludeFields = array() array $excludeFields = array()
) { ) {

View File

@@ -11,7 +11,7 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Logger; use Monolog\Level;
use Monolog\LogRecord; use Monolog\LogRecord;
/** /**
@@ -58,7 +58,7 @@ class SocketHandler extends AbstractProcessingHandler
*/ */
public function __construct( public function __construct(
string $connectionString, string $connectionString,
$level = Logger::DEBUG, $level = Level::Debug,
bool $bubble = true, bool $bubble = true,
bool $persistent = false, bool $persistent = false,
float $timeout = 0.0, float $timeout = 0.0,

View File

@@ -12,7 +12,7 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Aws\Sqs\SqsClient; use Aws\Sqs\SqsClient;
use Monolog\Logger; use Monolog\Level;
use Monolog\Utils; use Monolog\Utils;
use Monolog\LogRecord; use Monolog\LogRecord;
@@ -33,7 +33,7 @@ class SqsHandler extends AbstractProcessingHandler
/** @var string */ /** @var string */
private $queueUrl; 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); parent::__construct($level, $bubble);

View File

@@ -11,7 +11,7 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Logger; use Monolog\Level;
use Monolog\Utils; use Monolog\Utils;
use Monolog\LogRecord; use Monolog\LogRecord;
@@ -50,7 +50,7 @@ class StreamHandler extends AbstractProcessingHandler
* *
* @throws \InvalidArgumentException If stream is not a resource or string * @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); parent::__construct($level, $bubble);

View File

@@ -11,7 +11,7 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Logger; use Monolog\Level;
use Monolog\Utils; use Monolog\Utils;
use Monolog\LogRecord; 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 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 * @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); parent::__construct($facility, $level, $bubble);
@@ -64,6 +64,6 @@ class SyslogHandler extends AbstractSyslogHandler
if (!openlog($this->ident, $this->logopts, $this->facility)) { 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)); 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);
} }
} }

View File

@@ -12,7 +12,7 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use DateTimeInterface; use DateTimeInterface;
use Monolog\Logger; use Monolog\Level;
use Monolog\Handler\SyslogUdp\UdpSocket; use Monolog\Handler\SyslogUdp\UdpSocket;
use Monolog\Utils; use Monolog\Utils;
use Monolog\LogRecord; use Monolog\LogRecord;
@@ -54,7 +54,7 @@ class SyslogUdpHandler extends AbstractSyslogHandler
* *
* @phpstan-param self::RFC* $rfc * @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')) { if (!extension_loaded('sockets')) {
throw new MissingExtensionException('The sockets extension is required to use the SyslogUdpHandler'); throw new MissingExtensionException('The sockets extension is required to use the SyslogUdpHandler');
@@ -72,7 +72,7 @@ class SyslogUdpHandler extends AbstractSyslogHandler
{ {
$lines = $this->splitMessageIntoLines($record->formatted); $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) { foreach ($lines as $line) {
$this->socket->write($line, $header); $this->socket->write($line, $header);

View File

@@ -12,7 +12,7 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use RuntimeException; use RuntimeException;
use Monolog\Logger; use Monolog\Level;
use Monolog\Utils; use Monolog\Utils;
use Monolog\LogRecord; use Monolog\LogRecord;
@@ -105,7 +105,7 @@ class TelegramBotHandler extends AbstractProcessingHandler
public function __construct( public function __construct(
string $apiKey, string $apiKey,
string $channel, string $channel,
$level = Logger::DEBUG, $level = Level::Debug,
bool $bubble = true, bool $bubble = true,
string $parseMode = null, string $parseMode = null,
bool $disableWebPagePreview = null, bool $disableWebPagePreview = null,

View File

@@ -11,10 +11,11 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Level;
use Monolog\LevelName;
use Monolog\Logger; use Monolog\Logger;
use Psr\Log\LogLevel; use Psr\Log\LogLevel;
use Monolog\LogRecord; use Monolog\LogRecord;
use Monolog\DateTimeImmutable;
/** /**
* Used for testing purposes. * Used for testing purposes.
@@ -67,16 +68,13 @@ use Monolog\DateTimeImmutable;
* @method bool hasNoticeThatPasses($message) * @method bool hasNoticeThatPasses($message)
* @method bool hasInfoThatPasses($message) * @method bool hasInfoThatPasses($message)
* @method bool hasDebugThatPasses($message) * @method bool hasDebugThatPasses($message)
*
* @phpstan-import-type Level from \Monolog\Logger
* @phpstan-import-type LevelName from \Monolog\Logger
*/ */
class TestHandler extends AbstractProcessingHandler class TestHandler extends AbstractProcessingHandler
{ {
/** @var LogRecord[] */ /** @var LogRecord[] */
protected $records = []; protected $records = [];
/** @var array<Level, LogRecord[]> */ /** @phpstan-var array<value-of<Level::VALUES>, LogRecord[]> */
protected $recordsByLevel = []; protected array $recordsByLevel = [];
/** @var bool */ /** @var bool */
private $skipReset = false; private $skipReset = false;
@@ -116,23 +114,21 @@ class TestHandler extends AbstractProcessingHandler
} }
/** /**
* @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<Level::VALUES>|value-of<LevelName::VALUES>|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|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 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)) { if (is_string($recordAssertions)) {
$recordAssertions = ['message' => $recordAssertions]; $recordAssertions = ['message' => $recordAssertions];
@@ -150,42 +146,28 @@ class TestHandler extends AbstractProcessingHandler
}, $level); }, $level);
} }
/** public function hasRecordThatContains(string $message, Level $level): bool
* @param string|int $level Logging level value or name
*
* @phpstan-param Level|LevelName|LogLevel::* $level
*/
public function hasRecordThatContains(string $message, $level): bool
{ {
return $this->hasRecordThatPasses(fn (LogRecord $rec) => str_contains($rec->message, $message), $level); return $this->hasRecordThatPasses(fn (LogRecord $rec) => str_contains($rec->message, $message), $level);
} }
/** public function hasRecordThatMatches(string $regex, Level $level): bool
* @param string|int $level Logging level value or name
*
* @phpstan-param Level|LevelName|LogLevel::* $level
*/
public function hasRecordThatMatches(string $regex, $level): bool
{ {
return $this->hasRecordThatPasses(fn (LogRecord $rec) => preg_match($regex, $rec->message) > 0, $level); 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 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); $level = Logger::toMonologLevel($level);
if (!isset($this->recordsByLevel[$level])) { if (!isset($this->recordsByLevel[$level->value])) {
return false; return false;
} }
foreach ($this->recordsByLevel[$level] as $i => $rec) { foreach ($this->recordsByLevel[$level->value] as $i => $rec) {
if ($predicate($rec, $i)) { if ($predicate($rec, $i)) {
return true; return true;
} }
@@ -199,7 +181,7 @@ class TestHandler extends AbstractProcessingHandler
*/ */
protected function write(LogRecord $record): void protected function write(LogRecord $record): void
{ {
$this->recordsByLevel[$record->level][] = $record; $this->recordsByLevel[$record->level->value][] = $record;
$this->records[] = $record; $this->records[] = $record;
} }
@@ -212,11 +194,10 @@ class TestHandler extends AbstractProcessingHandler
{ {
if (preg_match('/(.*)(Debug|Info|Notice|Warning|Error|Critical|Alert|Emergency)(.*)/', $method, $matches) > 0) { if (preg_match('/(.*)(Debug|Info|Notice|Warning|Error|Critical|Alert|Emergency)(.*)/', $method, $matches) > 0) {
$genericMethod = $matches[1] . ('Records' !== $matches[3] ? 'Record' : '') . $matches[3]; $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]; $callback = [$this, $genericMethod];
if (is_callable($callback)) { if (is_callable($callback)) {
$args[] = $level; $args[] = $level;
return call_user_func_array($callback, $args); return call_user_func_array($callback, $args);
} }
} }

View File

@@ -13,7 +13,7 @@ namespace Monolog\Handler;
use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\FormatterInterface;
use Monolog\Formatter\NormalizerFormatter; use Monolog\Formatter\NormalizerFormatter;
use Monolog\Logger; use Monolog\Level;
use Monolog\LogRecord; use Monolog\LogRecord;
/** /**
@@ -24,47 +24,48 @@ use Monolog\LogRecord;
*/ */
class ZendMonitorHandler extends AbstractProcessingHandler class ZendMonitorHandler extends AbstractProcessingHandler
{ {
/**
* Monolog level / ZendMonitor Custom Event priority map
*
* @var array<int, int>
*/
protected $levelMap = [];
/** /**
* @throws MissingExtensionException * @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')) { if (!function_exists('zend_monitor_custom_event')) {
throw new MissingExtensionException( throw new MissingExtensionException(
'You must have Zend Server installed with Zend Monitor enabled in order to use this handler' '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); 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} * {@inheritDoc}
*/ */
protected function write(LogRecord $record): void protected function write(LogRecord $record): void
{ {
$this->writeZendMonitorCustomEvent( $this->writeZendMonitorCustomEvent(
Logger::getLevelName($record->level), $record->level->toLevelName()->value,
$record->message, $record->message,
$record->formatted, $record->formatted,
$this->levelMap[$record->level] $this->toZendMonitorLevel($record->level)
); );
} }
@@ -87,12 +88,4 @@ class ZendMonitorHandler extends AbstractProcessingHandler
{ {
return new NormalizerFormatter(); return new NormalizerFormatter();
} }
/**
* @return array<int, int>
*/
public function getLevelMap(): array
{
return $this->levelMap;
}
} }

127
src/Monolog/Level.php Normal file
View File

@@ -0,0 +1,127 @@
<?php
namespace Monolog;
use Psr\Log\LogLevel;
/**
* @see LevelName
*/
enum Level: int
{
/**
* Detailed debug information
*/
case Debug = 100;
/**
* Interesting events
*
* Examples: User logs in, SQL logs.
*/
case Info = 200;
/**
* Uncommon events
*/
case Notice = 250;
/**
* Exceptional occurrences that are not errors
*
* Examples: Use of deprecated APIs, poor use of an API,
* undesirable things that are not necessarily wrong.
*/
case Warning = 300;
/**
* Runtime errors
*/
case Error = 400;
/**
* Critical conditions
*
* Example: Application component unavailable, unexpected exception.
*/
case Critical = 500;
/**
* Action must be taken immediately
*
* Example: Entire website down, database unavailable, etc.
* This should trigger the SMS alerts and wake you up.
*/
case Alert = 550;
/**
* Urgent alert.
*/
case Emergency = 600;
public static function fromLevelName(LevelName $name): self
{
return match ($name) {
LevelName::Debug => 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,
];
}

53
src/Monolog/LevelName.php Normal file
View File

@@ -0,0 +1,53 @@
<?php
namespace Monolog;
/**
* @see Level
*/
enum LevelName: string
{
case Debug = 'DEBUG';
case Info = 'INFO';
case Notice = 'NOTICE';
case Warning = 'WARNING';
case Error = 'ERROR';
case Critical = 'CRITICAL';
case Alert = 'ALERT';
case Emergency = 'EMERGENCY';
public static function fromLevel(Level $level): self
{
return match ($level) {
Level::Debug => 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;
}
}

View File

@@ -17,25 +17,21 @@ use ArrayAccess;
* Monolog log record * Monolog log record
* *
* @author Jordi Boggiano <j.boggiano@seld.be> * @author Jordi Boggiano <j.boggiano@seld.be>
* @template-implements \ArrayAccess<'message'|'level'|'context'|'level_name'|'channel'|'datetime'|'extra', int|string|\DateTimeImmutable|array<mixed>> * @template-implements ArrayAccess<'message'|'level'|'context'|'level_name'|'channel'|'datetime'|'extra', int|string|\DateTimeImmutable|array<mixed>>
* @phpstan-import-type Level from Logger
* @phpstan-import-type LevelName from Logger
*/ */
class LogRecord implements \ArrayAccess class LogRecord implements ArrayAccess
{ {
private const MODIFIABLE_FIELDS = [ private const MODIFIABLE_FIELDS = [
'extra' => true, 'extra' => true,
'formatted' => true, 'formatted' => true,
]; ];
/** @var 'DEBUG'|'INFO'|'NOTICE'|'WARNING'|'ERROR'|'CRITICAL'|'ALERT'|'EMERGENCY' */ public readonly LevelName $levelName;
public readonly string $levelName; // TODO enum?
public function __construct( public function __construct(
public readonly \DateTimeImmutable $datetime, public readonly \DateTimeImmutable $datetime,
public readonly string $channel, public readonly string $channel,
/** @var Logger::DEBUG|Logger::INFO|Logger::NOTICE|Logger::WARNING|Logger::ERROR|Logger::CRITICAL|Logger::ALERT|Logger::EMERGENCY */ public readonly Level $level,
public readonly int $level, // TODO enum?
public readonly string $message, public readonly string $message,
/** @var array<mixed> */ /** @var array<mixed> */
public readonly array $context = [], public readonly array $context = [],
@@ -43,7 +39,7 @@ class LogRecord implements \ArrayAccess
public array $extra = [], public array $extra = [],
public mixed $formatted = null, public mixed $formatted = null,
) { ) {
$this->levelName = Logger::getLevelName($level); $this->levelName = LevelName::fromLevel($level);
} }
public function offsetSet(mixed $offset, mixed $value): void public function offsetSet(mixed $offset, mixed $value): void
@@ -81,8 +77,15 @@ class LogRecord implements \ArrayAccess
public function &offsetGet(mixed $offset): mixed public function &offsetGet(mixed $offset): mixed
{ {
if ($offset === 'level_name') { if ($offset === 'level_name' || $offset === 'level') {
$offset = 'levelName'; 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])) { if (isset(self::MODIFIABLE_FIELDS[$offset])) {
@@ -96,15 +99,15 @@ class LogRecord implements \ArrayAccess
} }
/** /**
* @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::VALUES>, level_name: value-of<LevelName::VALUES>, channel: string, datetime: \DateTimeImmutable, extra: mixed[]}
*/ */
public function toArray(): array public function toArray(): array
{ {
return [ return [
'message' => $this->message, 'message' => $this->message,
'context' => $this->context, 'context' => $this->context,
'level' => $this->level, 'level' => $this->level->value,
'level_name' => $this->levelName, 'level_name' => $this->levelName->value,
'channel' => $this->channel, 'channel' => $this->channel,
'datetime' => $this->datetime, 'datetime' => $this->datetime,
'extra' => $this->extra, 'extra' => $this->extra,

View File

@@ -27,14 +27,13 @@ use Stringable;
* and uses them to store records that are added to it. * and uses them to store records that are added to it.
* *
* @author Jordi Boggiano <j.boggiano@seld.be> * @author Jordi Boggiano <j.boggiano@seld.be>
*
* @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 class Logger implements LoggerInterface, ResettableInterface
{ {
/** /**
* Detailed debug information * Detailed debug information
*
* @deprecated Use \Monolog\Level::Debug
*/ */
public const DEBUG = 100; public const DEBUG = 100;
@@ -42,11 +41,15 @@ class Logger implements LoggerInterface, ResettableInterface
* Interesting events * Interesting events
* *
* Examples: User logs in, SQL logs. * Examples: User logs in, SQL logs.
*
* @deprecated Use \Monolog\Level::Info
*/ */
public const INFO = 200; public const INFO = 200;
/** /**
* Uncommon events * Uncommon events
*
* @deprecated Use \Monolog\Level::Notice
*/ */
public const NOTICE = 250; public const NOTICE = 250;
@@ -55,11 +58,15 @@ class Logger implements LoggerInterface, ResettableInterface
* *
* Examples: Use of deprecated APIs, poor use of an API, * Examples: Use of deprecated APIs, poor use of an API,
* undesirable things that are not necessarily wrong. * undesirable things that are not necessarily wrong.
*
* @deprecated Use \Monolog\Level::Warning
*/ */
public const WARNING = 300; public const WARNING = 300;
/** /**
* Runtime errors * Runtime errors
*
* @deprecated Use \Monolog\Level::Error
*/ */
public const ERROR = 400; public const ERROR = 400;
@@ -67,6 +74,8 @@ class Logger implements LoggerInterface, ResettableInterface
* Critical conditions * Critical conditions
* *
* Example: Application component unavailable, unexpected exception. * Example: Application component unavailable, unexpected exception.
*
* @deprecated Use \Monolog\Level::Critical
*/ */
public const CRITICAL = 500; public const CRITICAL = 500;
@@ -75,11 +84,15 @@ class Logger implements LoggerInterface, ResettableInterface
* *
* Example: Entire website down, database unavailable, etc. * Example: Entire website down, database unavailable, etc.
* This should trigger the SMS alerts and wake you up. * This should trigger the SMS alerts and wake you up.
*
* @deprecated Use \Monolog\Level::Alert
*/ */
public const ALERT = 550; public const ALERT = 550;
/** /**
* Urgent alert. * Urgent alert.
*
* @deprecated Use \Monolog\Level::Emergency
*/ */
public const EMERGENCY = 600; public const EMERGENCY = 600;
@@ -91,25 +104,7 @@ class Logger implements LoggerInterface, ResettableInterface
* *
* @var int * @var int
*/ */
public const API = 2; public const API = 3;
/**
* This is a static variable and not a constant to serve as an extension point for custom levels
*
* @var array<int, string> $levels Logging levels with the levels as key
*
* @phpstan-var array<Level, LevelName> $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',
];
/** /**
* @var string * @var string
@@ -287,16 +282,16 @@ class Logger implements LoggerInterface, ResettableInterface
* @param mixed[] $context The log context * @param mixed[] $context The log context
* @return bool Whether the record has been processed * @return bool Whether the record has been processed
* *
* @phpstan-param Level $level * @phpstan-param value-of<Level::VALUES>|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; $recordInitialized = count($this->processors) === 0;
$record = new LogRecord( $record = new LogRecord(
message: $message, message: $message,
context: $context, context: $context,
level: $level, level: self::toMonologLevel($level),
channel: $this->name, channel: $this->name,
datetime: new DateTimeImmutable($this->microsecondTimestamps, $this->timezone), datetime: new DateTimeImmutable($this->microsecondTimestamps, $this->timezone),
extra: [], extra: [],
@@ -380,79 +375,64 @@ class Logger implements LoggerInterface, ResettableInterface
} }
} }
/**
* Gets all supported logging levels.
*
* @return array<string, int> Assoc array with human-readable level names => level codes.
* @phpstan-return array<LevelName, Level>
*/
public static function getLevels(): array
{
return array_flip(static::$levels);
}
/**
* Gets the name of the logging level.
*
* @throws \Psr\Log\InvalidArgumentException If level is not defined
*
* @phpstan-param Level $level
* @phpstan-return LevelName
*/
public static function getLevelName(int $level): string
{
if (!isset(static::$levels[$level])) {
throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', array_keys(static::$levels)));
}
return static::$levels[$level];
}
/** /**
* Converts PSR-3 levels to Monolog ones if necessary * Converts PSR-3 levels to Monolog ones if necessary
* *
* @param string|int $level Level number (monolog) or name (PSR-3) * @param int|string|Level|LevelName|LogLevel::* $level Level number (monolog) or name (PSR-3)
* @throws \Psr\Log\InvalidArgumentException If level is not defined * @throws \Psr\Log\InvalidArgumentException If level is not defined
* *
* @phpstan-param Level|LevelName|LogLevel::* $level * @phpstan-param value-of<Level::VALUES>|value-of<LevelName::VALUES>|Level|LevelName|LogLevel::* $level
* @phpstan-return Level
*/ */
public static function toMonologLevel($level): int public static function toMonologLevel(string|int|Level|LevelName $level): Level
{ {
if (is_string($level)) { if ($level instanceof Level) {
if (is_numeric($level)) { return $level;
return intval($level); }
if ($level instanceof LevelName) {
return $level->toLevel();
}
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) // strange results depending on locale (for example, "i" will become "İ" in Turkish locale)
$upper = strtr($level, 'abcdefgilmnortuwy', 'ABCDEFGILMNORTUWY'); $upper = strtr(substr($level, 0, 1), 'dinweca', 'DINWECA') . strtolower(substr($level, 1));
if (defined(__CLASS__.'::'.$upper)) { if (defined(Level::class.'::'.$upper)) {
return constant(__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)) { $levelEnum = Level::tryFrom($level);
throw new InvalidArgumentException('Level "'.var_export($level, true).'" is not defined, use one of: '.implode(', ', array_keys(static::$levels) + static::$levels)); 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 * Checks whether the Logger has a handler that listens on the given level
* *
* @phpstan-param Level $level * @phpstan-param value-of<Level::VALUES>|value-of<LevelName::VALUES>|Level|LevelName|LogLevel::* $level
*/ */
public function isHandling(int $level): bool public function isHandling(int|string|LevelName|Level $level): bool
{ {
$record = new LogRecord( $record = new LogRecord(
datetime: new DateTimeImmutable($this->microsecondTimestamps, $this->timezone), datetime: new DateTimeImmutable($this->microsecondTimestamps, $this->timezone),
channel: $this->name, channel: $this->name,
message: '', message: '',
level: $level, level: self::toMonologLevel($level),
); );
foreach ($this->handlers as $handler) { foreach ($this->handlers as $handler) {
@@ -494,8 +474,8 @@ class Logger implements LoggerInterface, ResettableInterface
*/ */
public function log($level, string|\Stringable $message, array $context = []): void public function log($level, string|\Stringable $message, array $context = []): void
{ {
if (!is_int($level) && !is_string($level)) { if (!is_string($level) && !is_int($level) && !$level instanceof Level) {
throw new \InvalidArgumentException('$level is expected to be a string or int'); throw new \InvalidArgumentException('$level is expected to be a string, int or '.Level::class.' instance');
} }
$level = static::toMonologLevel($level); $level = static::toMonologLevel($level);

View File

@@ -11,6 +11,8 @@
namespace Monolog\Processor; namespace Monolog\Processor;
use Monolog\Level;
use Monolog\LevelName;
use Monolog\Logger; use Monolog\Logger;
use Psr\Log\LogLevel; use Psr\Log\LogLevel;
use Monolog\LogRecord; use Monolog\LogRecord;
@@ -20,23 +22,19 @@ use Monolog\LogRecord;
* *
* @author Nick Otter * @author Nick Otter
* @author Jordi Boggiano <j.boggiano@seld.be> * @author Jordi Boggiano <j.boggiano@seld.be>
*
* @phpstan-import-type Level from \Monolog\Logger
* @phpstan-import-type LevelName from \Monolog\Logger
*/ */
class GitProcessor implements ProcessorInterface class GitProcessor implements ProcessorInterface
{ {
/** @var int */ private Level $level;
private $level;
/** @var array{branch: string, commit: string}|array<never>|null */ /** @var array{branch: string, commit: string}|array<never>|null */
private static $cache = 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<Level::VALUES>|value-of<LevelName::VALUES>|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); $this->level = Logger::toMonologLevel($level);
} }

View File

@@ -11,6 +11,8 @@
namespace Monolog\Processor; namespace Monolog\Processor;
use Monolog\Level;
use Monolog\LevelName;
use Monolog\Logger; use Monolog\Logger;
use Psr\Log\LogLevel; use Psr\Log\LogLevel;
use Monolog\LogRecord; use Monolog\LogRecord;
@@ -25,13 +27,10 @@ use Monolog\LogRecord;
* triggered the FingersCrossedHandler. * triggered the FingersCrossedHandler.
* *
* @author Jordi Boggiano <j.boggiano@seld.be> * @author Jordi Boggiano <j.boggiano@seld.be>
*
* @phpstan-import-type Level from \Monolog\Logger
* @phpstan-import-type LevelName from \Monolog\Logger
*/ */
class IntrospectionProcessor implements ProcessorInterface class IntrospectionProcessor implements ProcessorInterface
{ {
private int $level; private Level $level;
/** @var string[] */ /** @var string[] */
private array $skipClassesPartials; 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 * @param string[] $skipClassesPartials
* *
* @phpstan-param Level|LevelName|LogLevel::* $level * @phpstan-param value-of<Level::VALUES>|value-of<LevelName::VALUES>|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->level = Logger::toMonologLevel($level);
$this->skipClassesPartials = array_merge(['Monolog\\'], $skipClassesPartials); $this->skipClassesPartials = array_merge(['Monolog\\'], $skipClassesPartials);
@@ -62,7 +61,7 @@ class IntrospectionProcessor implements ProcessorInterface
public function __invoke(LogRecord $record): LogRecord public function __invoke(LogRecord $record): LogRecord
{ {
// return if the level is not high enough // return if the level is not high enough
if ($record->level < $this->level) { if ($record->level->isLowerThan($this->level)) {
return $record; return $record;
} }

View File

@@ -11,6 +11,8 @@
namespace Monolog\Processor; namespace Monolog\Processor;
use Monolog\Level;
use Monolog\LevelName;
use Monolog\Logger; use Monolog\Logger;
use Psr\Log\LogLevel; use Psr\Log\LogLevel;
use Monolog\LogRecord; use Monolog\LogRecord;
@@ -19,23 +21,19 @@ use Monolog\LogRecord;
* Injects Hg branch and Hg revision number in all records * Injects Hg branch and Hg revision number in all records
* *
* @author Jonathan A. Schweder <jonathanschweder@gmail.com> * @author Jonathan A. Schweder <jonathanschweder@gmail.com>
*
* @phpstan-import-type LevelName from \Monolog\Logger
* @phpstan-import-type Level from \Monolog\Logger
*/ */
class MercurialProcessor implements ProcessorInterface class MercurialProcessor implements ProcessorInterface
{ {
/** @var Level */ private Level $level;
private $level;
/** @var array{branch: string, revision: string}|array<never>|null */ /** @var array{branch: string, revision: string}|array<never>|null */
private static $cache = 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<Level::VALUES>|value-of<LevelName::VALUES>|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); $this->level = Logger::toMonologLevel($level);
} }
@@ -46,7 +44,7 @@ class MercurialProcessor implements ProcessorInterface
public function __invoke(LogRecord $record): LogRecord public function __invoke(LogRecord $record): LogRecord
{ {
// return if the level is not high enough // return if the level is not high enough
if ($record->level < $this->level) { if ($record->level->isLowerThan($this->level)) {
return $record; return $record;
} }

View File

@@ -19,9 +19,6 @@ use ReflectionExtension;
* Monolog POSIX signal handler * Monolog POSIX signal handler
* *
* @author Robert Gust-Bardon <robert@gust-bardon.org> * @author Robert Gust-Bardon <robert@gust-bardon.org>
*
* @phpstan-import-type Level from \Monolog\Logger
* @phpstan-import-type LevelName from \Monolog\Logger
*/ */
class SignalHandler class SignalHandler
{ {
@@ -30,7 +27,7 @@ class SignalHandler
/** @var array<int, callable|string|int> SIG_DFL, SIG_IGN or previous callable */ /** @var array<int, callable|string|int> SIG_DFL, SIG_IGN or previous callable */
private $previousSignalHandler = []; private $previousSignalHandler = [];
/** @var array<int, int> */ /** @var array<int, \Psr\Log\LogLevel::*> */
private $signalLevelMap = []; private $signalLevelMap = [];
/** @var array<int, bool> */ /** @var array<int, bool> */
private $signalRestartSyscalls = []; private $signalRestartSyscalls = [];
@@ -41,21 +38,21 @@ class SignalHandler
} }
/** /**
* @param int|string $level Level or level name * @param int|string|Level|LevelName $level Level or level name
* @param bool $callPrevious * @param bool $callPrevious
* @param bool $restartSyscalls * @param bool $restartSyscalls
* @param bool|null $async * @param bool|null $async
* @return $this * @return $this
* *
* @phpstan-param Level|LevelName|LogLevel::* $level * @phpstan-param value-of<Level::VALUES>|value-of<LevelName::VALUES>|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')) { if (!extension_loaded('pcntl') || !function_exists('pcntl_signal')) {
return $this; return $this;
} }
$level = Logger::toMonologLevel($level); $level = Logger::toMonologLevel($level)->toPsrLogLevel();
if ($callPrevious) { if ($callPrevious) {
$handler = pcntl_signal_get_handler($signo); $handler = pcntl_signal_get_handler($signo);

View File

@@ -11,17 +11,18 @@
namespace Monolog\Test; namespace Monolog\Test;
use Monolog\Level;
use Monolog\LevelName;
use Monolog\Logger; use Monolog\Logger;
use Monolog\LogRecord; use Monolog\LogRecord;
use Monolog\DateTimeImmutable; use Monolog\DateTimeImmutable;
use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\FormatterInterface;
use Psr\Log\LogLevel;
/** /**
* Lets you easily generate log records and a dummy formatter for testing purposes * Lets you easily generate log records and a dummy formatter for testing purposes
* *
* @author Jordi Boggiano <j.boggiano@seld.be> * @author Jordi Boggiano <j.boggiano@seld.be>
*
* @phpstan-import-type Level from \Monolog\Logger
*/ */
class TestCase extends \PHPUnit\Framework\TestCase class TestCase extends \PHPUnit\Framework\TestCase
{ {
@@ -29,14 +30,14 @@ class TestCase extends \PHPUnit\Framework\TestCase
* @param array<mixed> $context * @param array<mixed> $context
* @param array<mixed> $extra * @param array<mixed> $extra
* *
* @phpstan-param Level $level * @phpstan-param value-of<Level::VALUES>|value-of<LevelName::VALUES>|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( return new LogRecord(
message: (string) $message, message: (string) $message,
context: $context, context: $context,
level: $level, level: Logger::toMonologLevel($level),
channel: $channel, channel: $channel,
datetime: $datetime, datetime: $datetime,
extra: $extra, extra: $extra,
@@ -49,11 +50,11 @@ class TestCase extends \PHPUnit\Framework\TestCase
protected function getMultipleRecords(): array protected function getMultipleRecords(): array
{ {
return [ return [
$this->getRecord(Logger::DEBUG, 'debug message 1'), $this->getRecord(Level::Debug, 'debug message 1'),
$this->getRecord(Logger::DEBUG, 'debug message 2'), $this->getRecord(Level::Debug, 'debug message 2'),
$this->getRecord(Logger::INFO, 'information'), $this->getRecord(Level::Info, 'information'),
$this->getRecord(Logger::WARNING, 'warning'), $this->getRecord(Level::Warning, 'warning'),
$this->getRecord(Logger::ERROR, 'error'), $this->getRecord(Level::Error, 'error'),
]; ];
} }

View File

@@ -37,7 +37,7 @@ class ErrorHandlerTest extends \PHPUnit\Framework\TestCase
$this->assertTrue(is_callable($prop)); $this->assertTrue(is_callable($prop));
$this->assertSame($prevHandler, $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); $this->assertSame($errHandler, $resHandler);
trigger_error('Foo', E_USER_ERROR); trigger_error('Foo', E_USER_ERROR);
$this->assertCount(1, $handler->getRecords()); $this->assertCount(1, $handler->getRecords());

View File

@@ -11,7 +11,7 @@
namespace Monolog\Formatter; namespace Monolog\Formatter;
use Monolog\Logger; use Monolog\Level;
use Monolog\Test\TestCase; use Monolog\Test\TestCase;
class ChromePHPFormatterTest extends TestCase class ChromePHPFormatterTest extends TestCase
@@ -23,7 +23,7 @@ class ChromePHPFormatterTest extends TestCase
{ {
$formatter = new ChromePHPFormatter(); $formatter = new ChromePHPFormatter();
$record = $this->getRecord( $record = $this->getRecord(
Logger::ERROR, Level::Error,
'log', 'log',
channel: 'meh', channel: 'meh',
context: ['from' => 'logger'], context: ['from' => 'logger'],
@@ -55,7 +55,7 @@ class ChromePHPFormatterTest extends TestCase
{ {
$formatter = new ChromePHPFormatter(); $formatter = new ChromePHPFormatter();
$record = $this->getRecord( $record = $this->getRecord(
Logger::CRITICAL, Level::Critical,
'log', 'log',
channel: 'meh', channel: 'meh',
context: ['from' => 'logger'], context: ['from' => 'logger'],
@@ -87,7 +87,7 @@ class ChromePHPFormatterTest extends TestCase
{ {
$formatter = new ChromePHPFormatter(); $formatter = new ChromePHPFormatter();
$record = $this->getRecord( $record = $this->getRecord(
Logger::DEBUG, Level::Debug,
'log', 'log',
channel: 'meh', channel: 'meh',
datetime: new \DateTimeImmutable("@0"), datetime: new \DateTimeImmutable("@0"),
@@ -114,13 +114,13 @@ class ChromePHPFormatterTest extends TestCase
$formatter = new ChromePHPFormatter(); $formatter = new ChromePHPFormatter();
$records = [ $records = [
$this->getRecord( $this->getRecord(
Logger::INFO, Level::Info,
'log', 'log',
channel: 'meh', channel: 'meh',
datetime: new \DateTimeImmutable("@0"), datetime: new \DateTimeImmutable("@0"),
), ),
$this->getRecord( $this->getRecord(
Logger::WARNING, Level::Warning,
'log2', 'log2',
channel: 'foo', channel: 'foo',
datetime: new \DateTimeImmutable("@0"), datetime: new \DateTimeImmutable("@0"),

View File

@@ -11,7 +11,7 @@
namespace Monolog\Formatter; namespace Monolog\Formatter;
use Monolog\Logger; use Monolog\Level;
use Monolog\LogRecord; use Monolog\LogRecord;
use Monolog\Test\TestCase; use Monolog\Test\TestCase;
@@ -33,7 +33,7 @@ class ElasticaFormatterTest extends TestCase
{ {
// test log message // test log message
$msg = $this->getRecord( $msg = $this->getRecord(
Logger::ERROR, Level::Error,
'log', 'log',
channel: 'meh', channel: 'meh',
context: ['foo' => 7, 'bar', 'class' => new \stdClass], context: ['foo' => 7, 'bar', 'class' => new \stdClass],

View File

@@ -11,7 +11,7 @@
namespace Monolog\Formatter; namespace Monolog\Formatter;
use Monolog\Logger; use Monolog\Level;
use Monolog\Test\TestCase; use Monolog\Test\TestCase;
class ElasticsearchFormatterTest extends TestCase class ElasticsearchFormatterTest extends TestCase
@@ -25,7 +25,7 @@ class ElasticsearchFormatterTest extends TestCase
{ {
// Test log message // Test log message
$msg = $this->getRecord( $msg = $this->getRecord(
Logger::ERROR, Level::Error,
'log', 'log',
channel: 'meh', channel: 'meh',
context: ['foo' => 7, 'bar', 'class' => new \stdClass], context: ['foo' => 7, 'bar', 'class' => new \stdClass],

View File

@@ -11,7 +11,7 @@
namespace Monolog\Formatter; namespace Monolog\Formatter;
use Monolog\Logger; use Monolog\Level;
use Monolog\Test\TestCase; use Monolog\Test\TestCase;
class FlowdockFormatterTest extends TestCase class FlowdockFormatterTest extends TestCase
@@ -44,8 +44,8 @@ class FlowdockFormatterTest extends TestCase
{ {
$formatter = new FlowdockFormatter('test_source', 'source@test.com'); $formatter = new FlowdockFormatter('test_source', 'source@test.com');
$records = [ $records = [
$this->getRecord(Logger::WARNING), $this->getRecord(Level::Warning),
$this->getRecord(Logger::DEBUG), $this->getRecord(Level::Debug),
]; ];
$formatted = $formatter->formatBatch($records); $formatted = $formatter->formatBatch($records);

View File

@@ -11,7 +11,7 @@
namespace Monolog\Formatter; namespace Monolog\Formatter;
use Monolog\Logger; use Monolog\Level;
use Monolog\Test\TestCase; use Monolog\Test\TestCase;
class FluentdFormatterTest extends TestCase class FluentdFormatterTest extends TestCase
@@ -35,7 +35,7 @@ class FluentdFormatterTest extends TestCase
*/ */
public function testFormat() public function testFormat()
{ {
$record = $this->getRecord(Logger::WARNING, datetime: new \DateTimeImmutable("@0")); $record = $this->getRecord(Level::Warning, datetime: new \DateTimeImmutable("@0"));
$formatter = new FluentdFormatter(); $formatter = new FluentdFormatter();
$this->assertEquals( $this->assertEquals(
@@ -49,7 +49,7 @@ class FluentdFormatterTest extends TestCase
*/ */
public function testFormatWithTag() 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); $formatter = new FluentdFormatter(true);
$this->assertEquals( $this->assertEquals(

View File

@@ -11,7 +11,7 @@
namespace Monolog\Formatter; namespace Monolog\Formatter;
use Monolog\Logger; use Monolog\Level;
use Monolog\Test\TestCase; use Monolog\Test\TestCase;
class GelfMessageFormatterTest extends TestCase class GelfMessageFormatterTest extends TestCase
@@ -30,7 +30,7 @@ class GelfMessageFormatterTest extends TestCase
{ {
$formatter = new GelfMessageFormatter(); $formatter = new GelfMessageFormatter();
$record = $this->getRecord( $record = $this->getRecord(
Logger::ERROR, Level::Error,
'log', 'log',
channel: 'meh', channel: 'meh',
datetime: new \DateTimeImmutable("@0"), datetime: new \DateTimeImmutable("@0"),
@@ -62,7 +62,7 @@ class GelfMessageFormatterTest extends TestCase
{ {
$formatter = new GelfMessageFormatter(); $formatter = new GelfMessageFormatter();
$record = $this->getRecord( $record = $this->getRecord(
Logger::ERROR, Level::Error,
'log', 'log',
channel: 'meh', channel: 'meh',
context: ['from' => 'logger'], context: ['from' => 'logger'],
@@ -84,7 +84,7 @@ class GelfMessageFormatterTest extends TestCase
{ {
$formatter = new GelfMessageFormatter(); $formatter = new GelfMessageFormatter();
$record = $this->getRecord( $record = $this->getRecord(
Logger::ERROR, Level::Error,
'log', 'log',
channel: 'meh', channel: 'meh',
context: ['from' => 'logger'], context: ['from' => 'logger'],
@@ -120,7 +120,7 @@ class GelfMessageFormatterTest extends TestCase
{ {
$formatter = new GelfMessageFormatter(); $formatter = new GelfMessageFormatter();
$record = $this->getRecord( $record = $this->getRecord(
Logger::ERROR, Level::Error,
'log', 'log',
channel: 'meh', channel: 'meh',
context: ['from' => 'logger', 'exception' => [ context: ['from' => 'logger', 'exception' => [
@@ -146,7 +146,7 @@ class GelfMessageFormatterTest extends TestCase
{ {
$formatter = new GelfMessageFormatter(); $formatter = new GelfMessageFormatter();
$record = $this->getRecord( $record = $this->getRecord(
Logger::ERROR, Level::Error,
'log', 'log',
channel: 'meh', channel: 'meh',
context: ['from' => 'logger'], context: ['from' => 'logger'],
@@ -179,7 +179,7 @@ class GelfMessageFormatterTest extends TestCase
{ {
$formatter = new GelfMessageFormatter(); $formatter = new GelfMessageFormatter();
$record = $this->getRecord( $record = $this->getRecord(
Logger::ERROR, Level::Error,
'log', 'log',
channel: 'meh', channel: 'meh',
context: ['exception' => str_repeat(' ', 32767)], context: ['exception' => str_repeat(' ', 32767)],
@@ -205,7 +205,7 @@ class GelfMessageFormatterTest extends TestCase
{ {
$formatter = new GelfMessageFormatter('LONG_SYSTEM_NAME', null, 'ctxt_', PHP_INT_MAX); $formatter = new GelfMessageFormatter('LONG_SYSTEM_NAME', null, 'ctxt_', PHP_INT_MAX);
$record = $this->getRecord( $record = $this->getRecord(
Logger::ERROR, Level::Error,
'log', 'log',
channel: 'meh', channel: 'meh',
context: ['exception' => str_repeat(' ', 32767 * 2)], context: ['exception' => str_repeat(' ', 32767 * 2)],
@@ -231,7 +231,7 @@ class GelfMessageFormatterTest extends TestCase
{ {
$formatter = new GelfMessageFormatter(); $formatter = new GelfMessageFormatter();
$record = $this->getRecord( $record = $this->getRecord(
Logger::ERROR, Level::Error,
str_repeat('в', 32767), str_repeat('в', 32767),
channel: 'meh', channel: 'meh',
context: ['exception' => str_repeat('а', 32767)], context: ['exception' => str_repeat('а', 32767)],

View File

@@ -11,7 +11,7 @@
namespace Monolog\Formatter; namespace Monolog\Formatter;
use Monolog\Logger; use Monolog\Level;
use Monolog\LogRecord; use Monolog\LogRecord;
use Monolog\Test\TestCase; use Monolog\Test\TestCase;
@@ -85,8 +85,8 @@ class JsonFormatterTest extends TestCase
{ {
$formatter = new JsonFormatter(); $formatter = new JsonFormatter();
$records = [ $records = [
$this->getRecord(Logger::WARNING), $this->getRecord(Level::Warning),
$this->getRecord(Logger::DEBUG), $this->getRecord(Level::Debug),
]; ];
$this->assertEquals(json_encode($records), $formatter->formatBatch($records)); $this->assertEquals(json_encode($records), $formatter->formatBatch($records));
} }
@@ -99,8 +99,8 @@ class JsonFormatterTest extends TestCase
{ {
$formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_NEWLINES); $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_NEWLINES);
$records = [ $records = [
$this->getRecord(Logger::WARNING), $this->getRecord(Level::Warning),
$this->getRecord(Logger::DEBUG), $this->getRecord(Level::Debug),
]; ];
$expected = array_map(fn (LogRecord $record) => json_encode($record->toArray(), JSON_FORCE_OBJECT), $records); $expected = array_map(fn (LogRecord $record) => json_encode($record->toArray(), JSON_FORCE_OBJECT), $records);
$this->assertEquals(implode("\n", $expected), $formatter->formatBatch($records)); $this->assertEquals(implode("\n", $expected), $formatter->formatBatch($records));
@@ -213,7 +213,7 @@ class JsonFormatterTest extends TestCase
private function formatRecordWithExceptionInContext(JsonFormatter $formatter, \Throwable $exception) private function formatRecordWithExceptionInContext(JsonFormatter $formatter, \Throwable $exception)
{ {
$message = $formatter->format($this->getRecord( $message = $formatter->format($this->getRecord(
Logger::CRITICAL, Level::Critical,
'foobar', 'foobar',
channel: 'core', channel: 'core',
context: ['exception' => $exception], context: ['exception' => $exception],
@@ -262,7 +262,7 @@ class JsonFormatterTest extends TestCase
$largeArray = range(1, 1000); $largeArray = range(1, 1000);
$res = $formatter->format($this->getRecord( $res = $formatter->format($this->getRecord(
Logger::CRITICAL, Level::Critical,
'bar', 'bar',
channel: 'test', channel: 'test',
context: array($largeArray), context: array($largeArray),
@@ -278,7 +278,7 @@ class JsonFormatterTest extends TestCase
$largeArray = range(1, 2000); $largeArray = range(1, 2000);
$res = $formatter->format($this->getRecord( $res = $formatter->format($this->getRecord(
Logger::CRITICAL, Level::Critical,
'bar', 'bar',
channel: 'test', channel: 'test',
context: array($largeArray), context: array($largeArray),
@@ -293,7 +293,7 @@ class JsonFormatterTest extends TestCase
$formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, true, true); $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, true, true);
$record = $formatter->format($this->getRecord( $record = $formatter->format($this->getRecord(
Logger::DEBUG, Level::Debug,
'Testing', 'Testing',
channel: 'test', channel: 'test',
datetime: new \DateTimeImmutable('2022-02-22 00:00:00'), datetime: new \DateTimeImmutable('2022-02-22 00:00:00'),

View File

@@ -12,7 +12,7 @@
namespace Monolog\Formatter; namespace Monolog\Formatter;
use Monolog\Test\TestCase; use Monolog\Test\TestCase;
use Monolog\Logger; use Monolog\Level;
/** /**
* @covers Monolog\Formatter\LineFormatter * @covers Monolog\Formatter\LineFormatter
@@ -23,7 +23,7 @@ class LineFormatterTest extends TestCase
{ {
$formatter = new LineFormatter(null, 'Y-m-d'); $formatter = new LineFormatter(null, 'Y-m-d');
$message = $formatter->format($this->getRecord( $message = $formatter->format($this->getRecord(
Logger::WARNING, Level::Warning,
'foo', 'foo',
channel: 'log', channel: 'log',
)); ));
@@ -34,7 +34,7 @@ class LineFormatterTest extends TestCase
{ {
$formatter = new LineFormatter(null, 'Y-m-d'); $formatter = new LineFormatter(null, 'Y-m-d');
$message = $formatter->format($this->getRecord( $message = $formatter->format($this->getRecord(
Logger::ERROR, Level::Error,
'foo', 'foo',
channel: 'meh', channel: 'meh',
context: [ context: [
@@ -51,7 +51,7 @@ class LineFormatterTest extends TestCase
{ {
$formatter = new LineFormatter(null, 'Y-m-d'); $formatter = new LineFormatter(null, 'Y-m-d');
$message = $formatter->format($this->getRecord( $message = $formatter->format($this->getRecord(
Logger::ERROR, Level::Error,
'log', 'log',
channel: 'meh', channel: 'meh',
extra: ['ip' => '127.0.0.1'], extra: ['ip' => '127.0.0.1'],
@@ -63,7 +63,7 @@ class LineFormatterTest extends TestCase
{ {
$formatter = new LineFormatter("[%datetime%] %channel%.%level_name%: %message% %context% %extra.file% %extra%\n", 'Y-m-d'); $formatter = new LineFormatter("[%datetime%] %channel%.%level_name%: %message% %context% %extra.file% %extra%\n", 'Y-m-d');
$message = $formatter->format($this->getRecord( $message = $formatter->format($this->getRecord(
Logger::ERROR, Level::Error,
'log', 'log',
channel: 'meh', channel: 'meh',
extra: ['ip' => '127.0.0.1', 'file' => 'test'], extra: ['ip' => '127.0.0.1', 'file' => 'test'],
@@ -75,7 +75,7 @@ class LineFormatterTest extends TestCase
{ {
$formatter = new LineFormatter(null, 'Y-m-d', false, true); $formatter = new LineFormatter(null, 'Y-m-d', false, true);
$message = $formatter->format($this->getRecord( $message = $formatter->format($this->getRecord(
Logger::ERROR, Level::Error,
'log', 'log',
channel: 'meh', channel: 'meh',
)); ));
@@ -86,7 +86,7 @@ class LineFormatterTest extends TestCase
{ {
$formatter = new LineFormatter('%context.foo% => %extra.foo%'); $formatter = new LineFormatter('%context.foo% => %extra.foo%');
$message = $formatter->format($this->getRecord( $message = $formatter->format($this->getRecord(
Logger::ERROR, Level::Error,
'log', 'log',
channel: 'meh', channel: 'meh',
context: ['foo' => 'bar'], context: ['foo' => 'bar'],
@@ -100,7 +100,7 @@ class LineFormatterTest extends TestCase
{ {
$formatter = new LineFormatter(null, 'Y-m-d'); $formatter = new LineFormatter(null, 'Y-m-d');
$message = $formatter->format($this->getRecord( $message = $formatter->format($this->getRecord(
Logger::ERROR, Level::Error,
'foobar', 'foobar',
channel: 'meh', channel: 'meh',
context: [], context: [],
@@ -114,7 +114,7 @@ class LineFormatterTest extends TestCase
{ {
$formatter = new LineFormatter(null, 'Y-m-d'); $formatter = new LineFormatter(null, 'Y-m-d');
$message = $formatter->format($this->getRecord( $message = $formatter->format($this->getRecord(
Logger::CRITICAL, Level::Critical,
'foobar', 'foobar',
channel: 'core', channel: 'core',
context: ['exception' => new \RuntimeException('Foo')], context: ['exception' => new \RuntimeException('Foo')],
@@ -130,7 +130,7 @@ class LineFormatterTest extends TestCase
$formatter = new LineFormatter(null, 'Y-m-d'); $formatter = new LineFormatter(null, 'Y-m-d');
$formatter->includeStacktraces(); $formatter->includeStacktraces();
$message = $formatter->format($this->getRecord( $message = $formatter->format($this->getRecord(
Logger::CRITICAL, Level::Critical,
'foobar', 'foobar',
channel: 'core', channel: 'core',
context: ['exception' => new \RuntimeException('Foo')], context: ['exception' => new \RuntimeException('Foo')],
@@ -146,7 +146,7 @@ class LineFormatterTest extends TestCase
$formatter = new LineFormatter(null, 'Y-m-d'); $formatter = new LineFormatter(null, 'Y-m-d');
$previous = new \LogicException('Wut?'); $previous = new \LogicException('Wut?');
$message = $formatter->format($this->getRecord( $message = $formatter->format($this->getRecord(
Logger::CRITICAL, Level::Critical,
'foobar', 'foobar',
channel: 'core', channel: 'core',
context: ['exception' => new \RuntimeException('Foo', 0, $previous)], context: ['exception' => new \RuntimeException('Foo', 0, $previous)],
@@ -165,7 +165,7 @@ class LineFormatterTest extends TestCase
$formatter = new LineFormatter(null, 'Y-m-d'); $formatter = new LineFormatter(null, 'Y-m-d');
$message = $formatter->format($this->getRecord( $message = $formatter->format($this->getRecord(
Logger::CRITICAL, Level::Critical,
'foobar', 'foobar',
channel: 'core', channel: 'core',
context: ['exception' => new \SoapFault('foo', 'bar', 'hello', 'world')], context: ['exception' => new \SoapFault('foo', 'bar', 'hello', 'world')],
@@ -176,7 +176,7 @@ class LineFormatterTest extends TestCase
$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); $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( $message = $formatter->format($this->getRecord(
Logger::CRITICAL, Level::Critical,
'foobar', 'foobar',
channel: 'core', channel: 'core',
context: ['exception' => new \SoapFault('foo', 'bar', 'hello', (object) ['bar' => (object) ['biz' => 'baz'], 'foo' => 'world'])], context: ['exception' => new \SoapFault('foo', 'bar', 'hello', (object) ['bar' => (object) ['biz' => 'baz'], 'foo' => 'world'])],
@@ -192,12 +192,12 @@ class LineFormatterTest extends TestCase
$formatter = new LineFormatter(null, 'Y-m-d'); $formatter = new LineFormatter(null, 'Y-m-d');
$message = $formatter->formatBatch([ $message = $formatter->formatBatch([
$this->getRecord( $this->getRecord(
Logger::CRITICAL, Level::Critical,
'bar', 'bar',
channel: 'test', channel: 'test',
), ),
$this->getRecord( $this->getRecord(
Logger::WARNING, Level::Warning,
'foo', 'foo',
channel: 'log', channel: 'log',
), ),

View File

@@ -11,7 +11,8 @@
namespace Monolog\Formatter; namespace Monolog\Formatter;
use Monolog\Logger; use Monolog\Level;
use Monolog\LevelName;
use Monolog\Test\TestCase; use Monolog\Test\TestCase;
class LogstashFormatterTest extends TestCase class LogstashFormatterTest extends TestCase
@@ -23,7 +24,7 @@ class LogstashFormatterTest extends TestCase
{ {
$formatter = new LogstashFormatter('test', 'hostname'); $formatter = new LogstashFormatter('test', 'hostname');
$record = $this->getRecord( $record = $this->getRecord(
Logger::ERROR, Level::Error,
'log', 'log',
channel: 'meh', channel: 'meh',
datetime: new \DateTimeImmutable("@0"), datetime: new \DateTimeImmutable("@0"),
@@ -35,8 +36,8 @@ class LogstashFormatterTest extends TestCase
$this->assertEquals("1", $message['@version']); $this->assertEquals("1", $message['@version']);
$this->assertEquals('log', $message['message']); $this->assertEquals('log', $message['message']);
$this->assertEquals('meh', $message['channel']); $this->assertEquals('meh', $message['channel']);
$this->assertEquals('ERROR', $message['level']); $this->assertEquals(LevelName::Error->value, $message['level']);
$this->assertEquals(Logger::ERROR, $message['monolog_level']); $this->assertEquals(Level::Error->value, $message['monolog_level']);
$this->assertEquals('test', $message['type']); $this->assertEquals('test', $message['type']);
$this->assertEquals('hostname', $message['host']); $this->assertEquals('hostname', $message['host']);
@@ -54,7 +55,7 @@ class LogstashFormatterTest extends TestCase
{ {
$formatter = new LogstashFormatter('test'); $formatter = new LogstashFormatter('test');
$record = $this->getRecord( $record = $this->getRecord(
Logger::ERROR, Level::Error,
'log', 'log',
channel: 'meh', channel: 'meh',
context: ['from' => 'logger'], context: ['from' => 'logger'],
@@ -75,7 +76,7 @@ class LogstashFormatterTest extends TestCase
{ {
$formatter = new LogstashFormatter('test'); $formatter = new LogstashFormatter('test');
$record = $this->getRecord( $record = $this->getRecord(
Logger::ERROR, Level::Error,
'log', 'log',
channel: 'meh', channel: 'meh',
context: ['from' => 'logger'], context: ['from' => 'logger'],
@@ -105,7 +106,7 @@ class LogstashFormatterTest extends TestCase
{ {
$formatter = new LogstashFormatter('test'); $formatter = new LogstashFormatter('test');
$record = $this->getRecord( $record = $this->getRecord(
Logger::ERROR, Level::Error,
'log', 'log',
channel: 'meh', channel: 'meh',
context: ['from' => 'logger'], context: ['from' => 'logger'],
@@ -132,7 +133,7 @@ class LogstashFormatterTest extends TestCase
{ {
$formatter = new LogstashFormatter('app', 'test'); $formatter = new LogstashFormatter('app', 'test');
$record = $this->getRecord( $record = $this->getRecord(
Logger::ERROR, Level::Error,
'log', 'log',
channel: 'meh', channel: 'meh',
context: ['from' => 'logger'], context: ['from' => 'logger'],
@@ -150,7 +151,7 @@ class LogstashFormatterTest extends TestCase
{ {
$formatter = new LogstashFormatter('test', 'hostname'); $formatter = new LogstashFormatter('test', 'hostname');
$record = $this->getRecord( $record = $this->getRecord(
Logger::ERROR, Level::Error,
'log', 'log',
channel: '¯\_(ツ)_/¯', channel: '¯\_(ツ)_/¯',
datetime: new \DateTimeImmutable("@0"), datetime: new \DateTimeImmutable("@0"),

View File

@@ -14,7 +14,8 @@ namespace Monolog\Formatter;
use MongoDB\BSON\ObjectId; use MongoDB\BSON\ObjectId;
use MongoDB\BSON\Regex; use MongoDB\BSON\Regex;
use MongoDB\BSON\UTCDateTime; use MongoDB\BSON\UTCDateTime;
use Monolog\Logger; use Monolog\Level;
use Monolog\LevelName;
use Monolog\Test\TestCase; use Monolog\Test\TestCase;
/** /**
@@ -62,7 +63,7 @@ class MongoDBFormatterTest extends TestCase
{ {
$record = $this->getRecord( $record = $this->getRecord(
message: 'some log message', message: 'some log message',
level: Logger::WARNING, level: Level::Warning,
channel: 'test', channel: 'test',
datetime: new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'), datetime: new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'),
); );
@@ -73,8 +74,8 @@ class MongoDBFormatterTest extends TestCase
$this->assertCount(7, $formattedRecord); $this->assertCount(7, $formattedRecord);
$this->assertEquals('some log message', $formattedRecord['message']); $this->assertEquals('some log message', $formattedRecord['message']);
$this->assertEquals([], $formattedRecord['context']); $this->assertEquals([], $formattedRecord['context']);
$this->assertEquals(Logger::WARNING, $formattedRecord['level']); $this->assertEquals(Level::Warning->value, $formattedRecord['level']);
$this->assertEquals(Logger::getLevelName(Logger::WARNING), $formattedRecord['level_name']); $this->assertEquals(LevelName::Warning->value, $formattedRecord['level_name']);
$this->assertEquals('test', $formattedRecord['channel']); $this->assertEquals('test', $formattedRecord['channel']);
$this->assertInstanceOf('MongoDB\BSON\UTCDateTime', $formattedRecord['datetime']); $this->assertInstanceOf('MongoDB\BSON\UTCDateTime', $formattedRecord['datetime']);
$this->assertEquals('1453410690123', $formattedRecord['datetime']->__toString()); $this->assertEquals('1453410690123', $formattedRecord['datetime']->__toString());
@@ -96,7 +97,7 @@ class MongoDBFormatterTest extends TestCase
'context_int' => 123456, 'context_int' => 123456,
'except' => new \Exception('exception message', 987), 'except' => new \Exception('exception message', 987),
], ],
level: Logger::WARNING, level: Level::Warning,
channel: 'test', channel: 'test',
datetime: new \DateTimeImmutable('2016-01-21T21:11:30.213000+00:00'), datetime: new \DateTimeImmutable('2016-01-21T21:11:30.213000+00:00'),
); );
@@ -140,7 +141,7 @@ class MongoDBFormatterTest extends TestCase
], ],
], ],
], ],
level: Logger::WARNING, level: Level::Warning,
channel: 'test', channel: 'test',
datetime: new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'), datetime: new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'),
); );
@@ -174,7 +175,7 @@ class MongoDBFormatterTest extends TestCase
], ],
], ],
], ],
level: Logger::WARNING, level: Level::Warning,
channel: 'test', channel: 'test',
datetime: new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'), datetime: new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'),
); );
@@ -211,7 +212,7 @@ class MongoDBFormatterTest extends TestCase
context: [ context: [
'nest2' => $someObject, 'nest2' => $someObject,
], ],
level: Logger::WARNING, level: Level::Warning,
channel: 'test', channel: 'test',
datetime: new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'), datetime: new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'),
); );
@@ -238,7 +239,7 @@ class MongoDBFormatterTest extends TestCase
context: [ context: [
'nest2' => new \Exception('exception message', 987), 'nest2' => new \Exception('exception message', 987),
], ],
level: Logger::WARNING, level: Level::Warning,
channel: 'test', channel: 'test',
datetime: new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'), datetime: new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'),
); );
@@ -262,7 +263,7 @@ class MongoDBFormatterTest extends TestCase
'regex' => new Regex('pattern'), 'regex' => new Regex('pattern'),
], ],
], ],
level: Logger::WARNING, level: Level::Warning,
channel: 'test', channel: 'test',
datetime: new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'), datetime: new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'),
); );

View File

@@ -11,8 +11,9 @@
namespace Monolog\Formatter; namespace Monolog\Formatter;
use Monolog\LevelName;
use Monolog\Test\TestCase; use Monolog\Test\TestCase;
use Monolog\Logger; use Monolog\Level;
/** /**
* @covers Monolog\Formatter\NormalizerFormatter * @covers Monolog\Formatter\NormalizerFormatter
@@ -23,7 +24,7 @@ class NormalizerFormatterTest extends TestCase
{ {
$formatter = new NormalizerFormatter('Y-m-d'); $formatter = new NormalizerFormatter('Y-m-d');
$formatted = $formatter->format($this->getRecord( $formatted = $formatter->format($this->getRecord(
Logger::ERROR, Level::Error,
'foo', 'foo',
channel: 'meh', channel: 'meh',
extra: ['foo' => new TestFooNorm, 'bar' => new TestBarNorm, 'baz' => [], 'res' => fopen('php://memory', 'rb')], extra: ['foo' => new TestFooNorm, 'bar' => new TestBarNorm, 'baz' => [], 'res' => fopen('php://memory', 'rb')],
@@ -37,8 +38,8 @@ class NormalizerFormatterTest extends TestCase
)); ));
$this->assertEquals([ $this->assertEquals([
'level_name' => 'ERROR', 'level_name' => LevelName::Error->value,
'level' => Logger::ERROR, 'level' => Level::Error->value,
'channel' => 'meh', 'channel' => 'meh',
'message' => 'foo', 'message' => 'foo',
'datetime' => date('Y-m-d'), 'datetime' => date('Y-m-d'),
@@ -142,13 +143,13 @@ class NormalizerFormatterTest extends TestCase
{ {
$formatter = new NormalizerFormatter('Y-m-d'); $formatter = new NormalizerFormatter('Y-m-d');
$formatted = $formatter->formatBatch([ $formatted = $formatter->formatBatch([
$this->getRecord(Logger::CRITICAL, 'bar', channel: 'test'), $this->getRecord(Level::Critical, 'bar', channel: 'test'),
$this->getRecord(Logger::WARNING, 'foo', channel: 'log'), $this->getRecord(Level::Warning, 'foo', channel: 'log'),
]); ]);
$this->assertEquals([ $this->assertEquals([
[ [
'level_name' => 'CRITICAL', 'level_name' => LevelName::Critical->value,
'level' => Logger::CRITICAL, 'level' => Level::Critical->value,
'channel' => 'test', 'channel' => 'test',
'message' => 'bar', 'message' => 'bar',
'context' => [], 'context' => [],
@@ -156,8 +157,8 @@ class NormalizerFormatterTest extends TestCase
'extra' => [], 'extra' => [],
], ],
[ [
'level_name' => 'WARNING', 'level_name' => LevelName::Warning->value,
'level' => Logger::WARNING, 'level' => Level::Warning->value,
'channel' => 'log', 'channel' => 'log',
'message' => 'foo', 'message' => 'foo',
'context' => [], 'context' => [],
@@ -241,7 +242,7 @@ class NormalizerFormatterTest extends TestCase
$largeArray = range(1, 1000); $largeArray = range(1, 1000);
$res = $formatter->format($this->getRecord( $res = $formatter->format($this->getRecord(
Logger::CRITICAL, Level::Critical,
'bar', 'bar',
channel: 'test', channel: 'test',
context: [$largeArray], context: [$largeArray],
@@ -257,7 +258,7 @@ class NormalizerFormatterTest extends TestCase
$largeArray = range(1, 2000); $largeArray = range(1, 2000);
$res = $formatter->format($this->getRecord( $res = $formatter->format($this->getRecord(
Logger::CRITICAL, Level::Critical,
'bar', 'bar',
channel: 'test', channel: 'test',
context: [$largeArray], context: [$largeArray],
@@ -379,7 +380,7 @@ class NormalizerFormatterTest extends TestCase
private function formatRecordWithExceptionInContext(NormalizerFormatter $formatter, \Throwable $exception) private function formatRecordWithExceptionInContext(NormalizerFormatter $formatter, \Throwable $exception)
{ {
$message = $formatter->format($this->getRecord( $message = $formatter->format($this->getRecord(
Logger::CRITICAL, Level::Critical,
'foobar', 'foobar',
channel: 'core', channel: 'core',
context: ['exception' => $exception], context: ['exception' => $exception],

View File

@@ -11,7 +11,7 @@
namespace Monolog\Formatter; namespace Monolog\Formatter;
use Monolog\Logger; use Monolog\Level;
use Monolog\Test\TestCase; use Monolog\Test\TestCase;
class WildfireFormatterTest extends TestCase class WildfireFormatterTest extends TestCase
@@ -23,7 +23,7 @@ class WildfireFormatterTest extends TestCase
{ {
$wildfire = new WildfireFormatter(); $wildfire = new WildfireFormatter();
$record = $this->getRecord( $record = $this->getRecord(
Logger::ERROR, Level::Error,
'log', 'log',
channel: 'meh', channel: 'meh',
context: ['from' => 'logger'], context: ['from' => 'logger'],
@@ -46,7 +46,7 @@ class WildfireFormatterTest extends TestCase
{ {
$wildfire = new WildfireFormatter(); $wildfire = new WildfireFormatter();
$record = $this->getRecord( $record = $this->getRecord(
Logger::ERROR, Level::Error,
'log', 'log',
channel: 'meh', channel: 'meh',
context: ['from' => 'logger'], context: ['from' => 'logger'],
@@ -69,7 +69,7 @@ class WildfireFormatterTest extends TestCase
{ {
$wildfire = new WildfireFormatter(); $wildfire = new WildfireFormatter();
$record = $this->getRecord( $record = $this->getRecord(
Logger::ERROR, Level::Error,
'log', 'log',
channel: 'meh', channel: 'meh',
); );
@@ -91,7 +91,7 @@ class WildfireFormatterTest extends TestCase
$wildfire = new WildfireFormatter(); $wildfire = new WildfireFormatter();
$record = $this->getRecord( $record = $this->getRecord(
Logger::ERROR, Level::Error,
'log', 'log',
channel: 'meh', channel: 'meh',
); );
@@ -106,7 +106,7 @@ class WildfireFormatterTest extends TestCase
{ {
$wildfire = new WildfireFormatter(); $wildfire = new WildfireFormatter();
$record = $this->getRecord( $record = $this->getRecord(
Logger::ERROR, Level::Error,
'table-message', 'table-message',
channel: 'table-channel', channel: 'table-channel',
context: [ context: [

View File

@@ -11,8 +11,8 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Level;
use Monolog\Test\TestCase; use Monolog\Test\TestCase;
use Monolog\Logger;
class AbstractHandlerTest extends TestCase class AbstractHandlerTest extends TestCase
{ {
@@ -25,13 +25,13 @@ class AbstractHandlerTest extends TestCase
*/ */
public function testConstructAndGetSet() public function testConstructAndGetSet()
{ {
$handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler', [Logger::WARNING, false]); $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler', [Level::Warning, false]);
$this->assertEquals(Logger::WARNING, $handler->getLevel()); $this->assertEquals(Level::Warning, $handler->getLevel());
$this->assertEquals(false, $handler->getBubble()); $this->assertEquals(false, $handler->getBubble());
$handler->setLevel(Logger::ERROR); $handler->setLevel(Level::Error);
$handler->setBubble(true); $handler->setBubble(true);
$this->assertEquals(Logger::ERROR, $handler->getLevel()); $this->assertEquals(Level::Error, $handler->getLevel());
$this->assertEquals(true, $handler->getBubble()); $this->assertEquals(true, $handler->getBubble());
} }
@@ -51,9 +51,9 @@ class AbstractHandlerTest extends TestCase
*/ */
public function testIsHandling() 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->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 @@ class AbstractHandlerTest extends TestCase
public function testHandlesPsrStyleLevels() public function testHandlesPsrStyleLevels()
{ {
$handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler', ['warning', false]); $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'); $handler->setLevel('debug');
$this->assertTrue($handler->isHandling($this->getRecord(Logger::DEBUG))); $this->assertTrue($handler->isHandling($this->getRecord(Level::Debug)));
} }
} }

View File

@@ -12,7 +12,7 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Test\TestCase; use Monolog\Test\TestCase;
use Monolog\Logger; use Monolog\Level;
use Monolog\Processor\WebProcessor; use Monolog\Processor\WebProcessor;
use Monolog\Formatter\LineFormatter; use Monolog\Formatter\LineFormatter;
@@ -24,7 +24,7 @@ class AbstractProcessingHandlerTest extends TestCase
*/ */
public function testConstructAndGetSet() 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); $handler->setFormatter($formatter = new LineFormatter);
$this->assertSame($formatter, $handler->getFormatter()); $this->assertSame($formatter, $handler->getFormatter());
} }
@@ -34,8 +34,8 @@ class AbstractProcessingHandlerTest extends TestCase
*/ */
public function testHandleLowerLevelMessage() public function testHandleLowerLevelMessage()
{ {
$handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', [Logger::WARNING, true]); $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', [Level::Warning, true]);
$this->assertFalse($handler->handle($this->getRecord(Logger::DEBUG))); $this->assertFalse($handler->handle($this->getRecord(Level::Debug)));
} }
/** /**
@@ -43,7 +43,7 @@ class AbstractProcessingHandlerTest extends TestCase
*/ */
public function testHandleBubbling() 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())); $this->assertFalse($handler->handle($this->getRecord()));
} }
@@ -52,7 +52,7 @@ class AbstractProcessingHandlerTest extends TestCase
*/ */
public function testHandleNotBubbling() 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())); $this->assertTrue($handler->handle($this->getRecord()));
} }
@@ -61,9 +61,9 @@ class AbstractProcessingHandlerTest extends TestCase
*/ */
public function testHandleIsFalseWhenNotHandled() 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->assertTrue($handler->handle($this->getRecord()));
$this->assertFalse($handler->handle($this->getRecord(Logger::DEBUG))); $this->assertFalse($handler->handle($this->getRecord(Level::Debug)));
} }
/** /**

View File

@@ -12,7 +12,7 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Test\TestCase; use Monolog\Test\TestCase;
use Monolog\Logger; use Monolog\Level;
use PhpAmqpLib\Message\AMQPMessage; use PhpAmqpLib\Message\AMQPMessage;
/** /**
@@ -46,7 +46,7 @@ class AmqpHandlerTest extends TestCase
$handler = new AmqpHandler($exchange); $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 = [ $expected = [
[ [
@@ -103,7 +103,7 @@ class AmqpHandlerTest extends TestCase
$handler = new AmqpHandler($exchange, 'log'); $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 = [ $expected = [
[ [

View File

@@ -12,7 +12,7 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Test\TestCase; use Monolog\Test\TestCase;
use Monolog\Logger; use Monolog\Level;
/** /**
* @covers Monolog\Handler\BrowserConsoleHandlerTest * @covers Monolog\Handler\BrowserConsoleHandlerTest
@@ -37,7 +37,7 @@ class BrowserConsoleHandlerTest extends TestCase
$handler = new BrowserConsoleHandler(); $handler = new BrowserConsoleHandler();
$handler->setFormatter($this->getIdentityFormatter()); $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 = <<<EOF $expected = <<<EOF
(function (c) {if (c && c.groupCollapsed) { (function (c) {if (c && c.groupCollapsed) {
@@ -53,7 +53,7 @@ EOF;
$handler = new BrowserConsoleHandler(); $handler = new BrowserConsoleHandler();
$handler->setFormatter($this->getIdentityFormatter()); $handler->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 = <<<EOF $expected = <<<EOF
(function (c) {if (c && c.groupCollapsed) { (function (c) {if (c && c.groupCollapsed) {
@@ -69,7 +69,7 @@ EOF;
$handler = new BrowserConsoleHandler(); $handler = new BrowserConsoleHandler();
$handler->setFormatter($this->getIdentityFormatter()); $handler->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 = <<<EOF $expected = <<<EOF
(function (c) {if (c && c.groupCollapsed) { (function (c) {if (c && c.groupCollapsed) {
@@ -85,9 +85,9 @@ EOF;
$handler = new BrowserConsoleHandler(); $handler = new BrowserConsoleHandler();
$handler->setFormatter($this->getIdentityFormatter()); $handler->setFormatter($this->getIdentityFormatter());
$handler->handle($this->getRecord(Logger::DEBUG, '[[foo]]{macro: autolabel}')); $handler->handle($this->getRecord(Level::Debug, '[[foo]]{macro: autolabel}'));
$handler->handle($this->getRecord(Logger::DEBUG, '[[bar]]{macro: autolabel}')); $handler->handle($this->getRecord(Level::Debug, '[[bar]]{macro: autolabel}'));
$handler->handle($this->getRecord(Logger::DEBUG, '[[foo]]{macro: autolabel}')); $handler->handle($this->getRecord(Level::Debug, '[[foo]]{macro: autolabel}'));
$expected = <<<EOF $expected = <<<EOF
(function (c) {if (c && c.groupCollapsed) { (function (c) {if (c && c.groupCollapsed) {
@@ -105,7 +105,7 @@ EOF;
$handler = new BrowserConsoleHandler(); $handler = new BrowserConsoleHandler();
$handler->setFormatter($this->getIdentityFormatter()); $handler->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 = <<<EOF $expected = <<<EOF
(function (c) {if (c && c.groupCollapsed) { (function (c) {if (c && c.groupCollapsed) {
@@ -128,10 +128,10 @@ EOF;
$handler2 = new BrowserConsoleHandler(); $handler2 = new BrowserConsoleHandler();
$handler2->setFormatter($this->getIdentityFormatter()); $handler2->setFormatter($this->getIdentityFormatter());
$handler1->handle($this->getRecord(Logger::DEBUG, 'test1')); $handler1->handle($this->getRecord(Level::Debug, 'test1'));
$handler2->handle($this->getRecord(Logger::DEBUG, 'test2')); $handler2->handle($this->getRecord(Level::Debug, 'test2'));
$handler1->handle($this->getRecord(Logger::DEBUG, 'test3')); $handler1->handle($this->getRecord(Level::Debug, 'test3'));
$handler2->handle($this->getRecord(Logger::DEBUG, 'test4')); $handler2->handle($this->getRecord(Level::Debug, 'test4'));
$expected = <<<EOF $expected = <<<EOF
(function (c) {if (c && c.groupCollapsed) { (function (c) {if (c && c.groupCollapsed) {

View File

@@ -12,7 +12,7 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Test\TestCase; use Monolog\Test\TestCase;
use Monolog\Logger; use Monolog\Level;
class BufferHandlerTest extends TestCase class BufferHandlerTest extends TestCase
{ {
@@ -27,8 +27,8 @@ class BufferHandlerTest extends TestCase
{ {
$test = new TestHandler(); $test = new TestHandler();
$handler = new BufferHandler($test); $handler = new BufferHandler($test);
$handler->handle($this->getRecord(Logger::DEBUG)); $handler->handle($this->getRecord(Level::Debug));
$handler->handle($this->getRecord(Logger::INFO)); $handler->handle($this->getRecord(Level::Info));
$this->assertFalse($test->hasDebugRecords()); $this->assertFalse($test->hasDebugRecords());
$this->assertFalse($test->hasInfoRecords()); $this->assertFalse($test->hasInfoRecords());
$handler->close(); $handler->close();
@@ -44,8 +44,8 @@ class BufferHandlerTest extends TestCase
{ {
$test = new TestHandler(); $test = new TestHandler();
$handler = new BufferHandler($test); $handler = new BufferHandler($test);
$handler->handle($this->getRecord(Logger::WARNING)); $handler->handle($this->getRecord(Level::Warning));
$handler->handle($this->getRecord(Logger::DEBUG)); $handler->handle($this->getRecord(Level::Debug));
$this->shutdownCheckHandler = $test; $this->shutdownCheckHandler = $test;
register_shutdown_function([$this, 'checkPropagation']); register_shutdown_function([$this, 'checkPropagation']);
} }
@@ -65,10 +65,10 @@ class BufferHandlerTest extends TestCase
{ {
$test = new TestHandler(); $test = new TestHandler();
$handler = new BufferHandler($test, 2); $handler = new BufferHandler($test, 2);
$handler->handle($this->getRecord(Logger::DEBUG)); $handler->handle($this->getRecord(Level::Debug));
$handler->handle($this->getRecord(Logger::DEBUG)); $handler->handle($this->getRecord(Level::Debug));
$handler->handle($this->getRecord(Logger::INFO)); $handler->handle($this->getRecord(Level::Info));
$handler->handle($this->getRecord(Logger::WARNING)); $handler->handle($this->getRecord(Level::Warning));
$handler->close(); $handler->close();
$this->assertTrue($test->hasWarningRecords()); $this->assertTrue($test->hasWarningRecords());
$this->assertTrue($test->hasInfoRecords()); $this->assertTrue($test->hasInfoRecords());
@@ -81,22 +81,22 @@ class BufferHandlerTest extends TestCase
public function testHandleBufferLimitWithFlushOnOverflow() public function testHandleBufferLimitWithFlushOnOverflow()
{ {
$test = new TestHandler(); $test = new TestHandler();
$handler = new BufferHandler($test, 3, Logger::DEBUG, true, true); $handler = new BufferHandler($test, 3, Level::Debug, true, true);
// send two records // send two records
$handler->handle($this->getRecord(Logger::DEBUG)); $handler->handle($this->getRecord(Level::Debug));
$handler->handle($this->getRecord(Logger::DEBUG)); $handler->handle($this->getRecord(Level::Debug));
$handler->handle($this->getRecord(Logger::DEBUG)); $handler->handle($this->getRecord(Level::Debug));
$this->assertFalse($test->hasDebugRecords()); $this->assertFalse($test->hasDebugRecords());
$this->assertCount(0, $test->getRecords()); $this->assertCount(0, $test->getRecords());
// overflow // overflow
$handler->handle($this->getRecord(Logger::INFO)); $handler->handle($this->getRecord(Level::Info));
$this->assertTrue($test->hasDebugRecords()); $this->assertTrue($test->hasDebugRecords());
$this->assertCount(3, $test->getRecords()); $this->assertCount(3, $test->getRecords());
// should buffer again // should buffer again
$handler->handle($this->getRecord(Logger::WARNING)); $handler->handle($this->getRecord(Level::Warning));
$this->assertCount(3, $test->getRecords()); $this->assertCount(3, $test->getRecords());
$handler->close(); $handler->close();
@@ -111,11 +111,11 @@ class BufferHandlerTest extends TestCase
public function testHandleLevel() public function testHandleLevel()
{ {
$test = new TestHandler(); $test = new TestHandler();
$handler = new BufferHandler($test, 0, Logger::INFO); $handler = new BufferHandler($test, 0, Level::Info);
$handler->handle($this->getRecord(Logger::DEBUG)); $handler->handle($this->getRecord(Level::Debug));
$handler->handle($this->getRecord(Logger::INFO)); $handler->handle($this->getRecord(Level::Info));
$handler->handle($this->getRecord(Logger::WARNING)); $handler->handle($this->getRecord(Level::Warning));
$handler->handle($this->getRecord(Logger::DEBUG)); $handler->handle($this->getRecord(Level::Debug));
$handler->close(); $handler->close();
$this->assertTrue($test->hasWarningRecords()); $this->assertTrue($test->hasWarningRecords());
$this->assertTrue($test->hasInfoRecords()); $this->assertTrue($test->hasInfoRecords());
@@ -129,8 +129,8 @@ class BufferHandlerTest extends TestCase
{ {
$test = new TestHandler(); $test = new TestHandler();
$handler = new BufferHandler($test, 0); $handler = new BufferHandler($test, 0);
$handler->handle($this->getRecord(Logger::DEBUG)); $handler->handle($this->getRecord(Level::Debug));
$handler->handle($this->getRecord(Logger::INFO)); $handler->handle($this->getRecord(Level::Info));
$handler->flush(); $handler->flush();
$this->assertTrue($test->hasInfoRecords()); $this->assertTrue($test->hasInfoRecords());
$this->assertTrue($test->hasDebugRecords()); $this->assertTrue($test->hasDebugRecords());
@@ -149,7 +149,7 @@ class BufferHandlerTest extends TestCase
return $record; return $record;
}); });
$handler->handle($this->getRecord(Logger::WARNING)); $handler->handle($this->getRecord(Level::Warning));
$handler->flush(); $handler->flush();
$this->assertTrue($test->hasWarningRecords()); $this->assertTrue($test->hasWarningRecords());
$records = $test->getRecords(); $records = $test->getRecords();

View File

@@ -12,7 +12,7 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Test\TestCase; use Monolog\Test\TestCase;
use Monolog\Logger; use Monolog\Level;
/** /**
* @covers Monolog\Handler\ChromePHPHandler * @covers Monolog\Handler\ChromePHPHandler
@@ -34,8 +34,8 @@ class ChromePHPHandlerTest extends TestCase
$handler = new TestChromePHPHandler(); $handler = new TestChromePHPHandler();
$handler->setFormatter($this->getIdentityFormatter()); $handler->setFormatter($this->getIdentityFormatter());
$handler->handle($this->getRecord(Logger::DEBUG)); $handler->handle($this->getRecord(Level::Debug));
$handler->handle($this->getRecord(Logger::WARNING)); $handler->handle($this->getRecord(Level::Warning));
$expected = [ $expected = [
'X-ChromeLogger-Data' => base64_encode(utf8_encode(json_encode([ 'X-ChromeLogger-Data' => base64_encode(utf8_encode(json_encode([
@@ -65,11 +65,11 @@ class ChromePHPHandlerTest extends TestCase
public function testHeadersOverflow() public function testHeadersOverflow()
{ {
$handler = new TestChromePHPHandler(); $handler = new TestChromePHPHandler();
$handler->handle($this->getRecord(Logger::DEBUG)); $handler->handle($this->getRecord(Level::Debug));
$handler->handle($this->getRecord(Logger::WARNING, str_repeat('a', 2 * 1024))); $handler->handle($this->getRecord(Level::Warning, str_repeat('a', 2 * 1024)));
// overflow chrome headers limit // 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 = [ $expected = [
'X-ChromeLogger-Data' => base64_encode(utf8_encode(json_encode([ 'X-ChromeLogger-Data' => base64_encode(utf8_encode(json_encode([
@@ -106,13 +106,13 @@ class ChromePHPHandlerTest extends TestCase
{ {
$handler = new TestChromePHPHandler(); $handler = new TestChromePHPHandler();
$handler->setFormatter($this->getIdentityFormatter()); $handler->setFormatter($this->getIdentityFormatter());
$handler->handle($this->getRecord(Logger::DEBUG)); $handler->handle($this->getRecord(Level::Debug));
$handler->handle($this->getRecord(Logger::WARNING)); $handler->handle($this->getRecord(Level::Warning));
$handler2 = new TestChromePHPHandler(); $handler2 = new TestChromePHPHandler();
$handler2->setFormatter($this->getIdentityFormatter()); $handler2->setFormatter($this->getIdentityFormatter());
$handler2->handle($this->getRecord(Logger::DEBUG)); $handler2->handle($this->getRecord(Level::Debug));
$handler2->handle($this->getRecord(Logger::WARNING)); $handler2->handle($this->getRecord(Level::Warning));
$expected = [ $expected = [
'X-ChromeLogger-Data' => base64_encode(utf8_encode(json_encode([ 'X-ChromeLogger-Data' => base64_encode(utf8_encode(json_encode([

View File

@@ -12,13 +12,13 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Test\TestCase; use Monolog\Test\TestCase;
use Monolog\Logger; use Monolog\Level;
class CouchDBHandlerTest extends TestCase class CouchDBHandlerTest extends TestCase
{ {
public function testHandle() 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(); $handler = new CouchDBHandler();

View File

@@ -11,8 +11,8 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Level;
use Monolog\Test\TestCase; use Monolog\Test\TestCase;
use Monolog\Logger;
class DeduplicationHandlerTest extends TestCase class DeduplicationHandlerTest extends TestCase
{ {
@@ -23,10 +23,10 @@ class DeduplicationHandlerTest extends TestCase
{ {
$test = new TestHandler(); $test = new TestHandler();
@unlink(sys_get_temp_dir().'/monolog_dedup.log'); @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(Level::Debug));
$handler->handle($this->getRecord(Logger::INFO)); $handler->handle($this->getRecord(Level::Info));
$handler->flush(); $handler->flush();
@@ -43,10 +43,10 @@ class DeduplicationHandlerTest extends TestCase
{ {
$test = new TestHandler(); $test = new TestHandler();
@unlink(sys_get_temp_dir().'/monolog_dedup.log'); @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(Level::Error, 'Foo:bar'));
$handler->handle($this->getRecord(Logger::CRITICAL, "Foo\nbar")); $handler->handle($this->getRecord(Level::Critical, "Foo\nbar"));
$handler->flush(); $handler->flush();
@@ -64,10 +64,10 @@ class DeduplicationHandlerTest extends TestCase
public function testFlushSkipsIfLogExists() public function testFlushSkipsIfLogExists()
{ {
$test = new TestHandler(); $test = new TestHandler();
$handler = new DeduplicationHandler($test, sys_get_temp_dir().'/monolog_dedup.log', 0); $handler = new DeduplicationHandler($test, sys_get_temp_dir().'/monolog_dedup.log', Level::Debug);
$handler->handle($this->getRecord(Logger::ERROR, 'Foo:bar')); $handler->handle($this->getRecord(Level::Error, 'Foo:bar'));
$handler->handle($this->getRecord(Logger::CRITICAL, "Foo\nbar")); $handler->handle($this->getRecord(Level::Critical, "Foo\nbar"));
$handler->flush(); $handler->flush();
@@ -85,11 +85,11 @@ class DeduplicationHandlerTest extends TestCase
public function testFlushPassthruIfLogTooOld() public function testFlushPassthruIfLogTooOld()
{ {
$test = new TestHandler(); $test = new TestHandler();
$handler = new DeduplicationHandler($test, sys_get_temp_dir().'/monolog_dedup.log', 0); $handler = new DeduplicationHandler($test, sys_get_temp_dir().'/monolog_dedup.log', Level::Debug);
$record = $this->getRecord(Logger::ERROR, datetime: new \DateTimeImmutable('+62seconds')); $record = $this->getRecord(Level::Error, datetime: new \DateTimeImmutable('+62seconds'));
$handler->handle($record); $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->handle($record);
$handler->flush(); $handler->flush();
@@ -109,14 +109,14 @@ class DeduplicationHandlerTest extends TestCase
{ {
$test = new TestHandler(); $test = new TestHandler();
@unlink(sys_get_temp_dir().'/monolog_dedup.log'); @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 // 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); $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); $handler->handle($record2);
$record3 = $this->getRecord(Logger::CRITICAL, datetime: new \DateTimeImmutable('-30seconds')); $record3 = $this->getRecord(Level::Critical, datetime: new \DateTimeImmutable('-30seconds'));
$handler->handle($record3); $handler->handle($record3);
// log is written as none of them are duplicate // log is written as none of them are duplicate
@@ -137,8 +137,8 @@ class DeduplicationHandlerTest extends TestCase
$this->assertFalse($test->hasCriticalRecords()); $this->assertFalse($test->hasCriticalRecords());
// log new records, duplicate log gets GC'd at the end of this flush call // log new records, duplicate log gets GC'd at the end of this flush call
$handler->handle($record = $this->getRecord(Logger::ERROR)); $handler->handle($record = $this->getRecord(Level::Error));
$handler->handle($record2 = $this->getRecord(Logger::CRITICAL)); $handler->handle($record2 = $this->getRecord(Level::Critical));
$handler->flush(); $handler->flush();
// log should now contain the new errors and the previous one that was recent enough // log should now contain the new errors and the previous one that was recent enough

View File

@@ -12,7 +12,7 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Test\TestCase; use Monolog\Test\TestCase;
use Monolog\Logger; use Monolog\Level;
class DoctrineCouchDBHandlerTest extends TestCase class DoctrineCouchDBHandlerTest extends TestCase
{ {
@@ -30,12 +30,12 @@ class DoctrineCouchDBHandlerTest extends TestCase
->disableOriginalConstructor() ->disableOriginalConstructor()
->getMock(); ->getMock();
$record = $this->getRecord(Logger::WARNING, 'test', ['data' => new \stdClass, 'foo' => 34]); $record = $this->getRecord(Level::Warning, 'test', ['data' => new \stdClass, 'foo' => 34]);
$expected = [ $expected = [
'message' => 'test', 'message' => 'test',
'context' => ['data' => ['stdClass' => []], 'foo' => 34], 'context' => ['data' => ['stdClass' => []], 'foo' => 34],
'level' => Logger::WARNING, 'level' => Level::Warning->value,
'level_name' => 'WARNING', 'level_name' => 'WARNING',
'channel' => 'test', 'channel' => 'test',
'datetime' => (string) $record->datetime, 'datetime' => (string) $record->datetime,

View File

@@ -14,7 +14,7 @@ namespace Monolog\Handler;
use Monolog\Formatter\ElasticaFormatter; use Monolog\Formatter\ElasticaFormatter;
use Monolog\Formatter\NormalizerFormatter; use Monolog\Formatter\NormalizerFormatter;
use Monolog\Test\TestCase; use Monolog\Test\TestCase;
use Monolog\Logger; use Monolog\Level;
use Monolog\LogRecord; use Monolog\LogRecord;
use Elastica\Client; use Elastica\Client;
use Elastica\Request; use Elastica\Request;
@@ -58,7 +58,7 @@ class ElasticaHandlerTest extends TestCase
public function testHandle() public function testHandle()
{ {
// log message // 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 // format expected result
$formatter = new ElasticaFormatter($this->options['index'], $this->options['type']); $formatter = new ElasticaFormatter($this->options['index'], $this->options['type']);
@@ -158,7 +158,7 @@ class ElasticaHandlerTest extends TestCase
*/ */
public function testHandleIntegration() 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 = $msg->toArray();
$expected['datetime'] = $msg['datetime']->format(\DateTime::ISO8601); $expected['datetime'] = $msg['datetime']->format(\DateTime::ISO8601);
@@ -204,7 +204,7 @@ class ElasticaHandlerTest extends TestCase
*/ */
public function testHandleIntegrationNewESVersion() 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 = (array) $msg;
$expected['datetime'] = $msg['datetime']->format(\DateTime::ISO8601); $expected['datetime'] = $msg['datetime']->format(\DateTime::ISO8601);

View File

@@ -15,7 +15,7 @@ use Elasticsearch\ClientBuilder;
use Monolog\Formatter\ElasticsearchFormatter; use Monolog\Formatter\ElasticsearchFormatter;
use Monolog\Formatter\NormalizerFormatter; use Monolog\Formatter\NormalizerFormatter;
use Monolog\Test\TestCase; use Monolog\Test\TestCase;
use Monolog\Logger; use Monolog\Level;
use Elasticsearch\Client; use Elasticsearch\Client;
class ElasticsearchHandlerTest extends TestCase class ElasticsearchHandlerTest extends TestCase
@@ -56,7 +56,7 @@ class ElasticsearchHandlerTest extends TestCase
public function testHandle() public function testHandle()
{ {
// log message // 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 // format expected result
$formatter = new ElasticsearchFormatter($this->options['index'], $this->options['type']); $formatter = new ElasticsearchFormatter($this->options['index'], $this->options['type']);
@@ -172,7 +172,7 @@ class ElasticsearchHandlerTest extends TestCase
*/ */
public function testHandleIntegration() 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 = $msg->toArray();
$expected['datetime'] = $msg['datetime']->format(\DateTime::ISO8601); $expected['datetime'] = $msg['datetime']->format(\DateTime::ISO8601);

Some files were not shown because too many files have changed in this diff Show More