Skip to content

Commit

Permalink
Convert level/levelName to enums (#1656)
Browse files Browse the repository at this point in the history
  • Loading branch information
Seldaek authored Apr 19, 2022
1 parent 248673e commit 2d006a8
Show file tree
Hide file tree
Showing 138 changed files with 1,295 additions and 1,214 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@ composer.phar
phpunit.xml
composer.lock
.DS_Store
.php_cs.cache
.php-cs-fixer.cache
.hg
.phpunit.result.cache
16 changes: 8 additions & 8 deletions .php_cs → .php-cs-fixer.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,8 @@
->in(__DIR__.'/tests')
;

return PhpCsFixer\Config::create()
->setUsingCache(true)
->setRiskyAllowed(true)
->setRules(array(
$config = new PhpCsFixer\Config();
return $config->setRules(array(
'@PSR2' => true,
// some rules disabled as long as 1.x branch is maintained
'binary_operator_spaces' => array(
Expand All @@ -30,11 +28,11 @@
'cast_spaces' => ['space' => 'single'],
'header_comment' => ['header' => $header],
'include' => true,
'class_attributes_separation' => ['elements' => ['method']],
'class_attributes_separation' => array('elements' => array('method' => 'one', 'trait_import' => 'none')),
'no_blank_lines_after_class_opening' => true,
'no_blank_lines_after_phpdoc' => true,
'no_empty_statement' => true,
'no_extra_consecutive_blank_lines' => true,
'no_extra_blank_lines' => true,
'no_leading_import_slash' => true,
'no_leading_namespace_whitespace' => true,
'no_trailing_comma_in_singleline_array' => true,
Expand All @@ -49,13 +47,15 @@
//'phpdoc_scalar' => true,
'phpdoc_trim' => true,
//'phpdoc_types' => true,
'psr0' => true,
'psr_autoloading' => ['dir' => 'src'],
//'array_syntax' => array('syntax' => 'short'),
'declare_strict_types' => true,
'single_blank_line_before_namespace' => true,
'standardize_not_equals' => true,
'ternary_operator_spaces' => true,
'trailing_comma_in_multiline_array' => true,
'trailing_comma_in_multiline' => true,
))
->setUsingCache(true)
->setRiskyAllowed(true)
->setFinder($finder)
;
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ use Monolog\Handler\StreamHandler;

// create a log channel
$log = new Logger('name');
$log->pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING));
$log->pushHandler(new StreamHandler('path/to/your.log', Level::Warning));

// add records to the log
$log->warning('Foo');
Expand All @@ -50,7 +50,7 @@ $log->error('Bar');

## Support Monolog Financially

Get supported Monolog and help fund the project with the [Tidelift Subscription](https://tidelift.com/subscription/pkg/packagist-monolog-monolog?utm_source=packagist-monolog-monolog&utm_medium=referral&utm_campaign=enterprise) or via [GitHub sponsorship](https://github.com/sponsors/Seldaek).
Get supported Monolog and help fund the project with the [Tidelift Subscription](https://tidelift.com/subscription/pkg/packagist-monolog-monolog?utm_source=packagist-monolog-monolog&utm_medium=referral&utm_campaign=enterprise) or via [GitHub sponsorship](https://github.com/sponsors/Seldaek).

Tidelift delivers commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use.

Expand Down
8 changes: 4 additions & 4 deletions doc/01-usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ use Monolog\Handler\FirePHPHandler;
// Create the logger
$logger = new Logger('my_logger');
// Now add some handlers
$logger->pushHandler(new StreamHandler(__DIR__.'/my_app.log', Logger::DEBUG));
$logger->pushHandler(new StreamHandler(__DIR__.'/my_app.log', Level::Debug));
$logger->pushHandler(new FirePHPHandler());

// You can now use your logger
Expand Down Expand Up @@ -170,7 +170,7 @@ use Monolog\Handler\StreamHandler;
use Monolog\Handler\FirePHPHandler;

// Create some handlers
$stream = new StreamHandler(__DIR__.'/my_app.log', Logger::DEBUG);
$stream = new StreamHandler(__DIR__.'/my_app.log', Level::Debug);
$firephp = new FirePHPHandler();

// Create the main logger of the app
Expand Down Expand Up @@ -205,7 +205,7 @@ You can choose between predefined formatter classes or write your own (e.g. a mu
> A very useful formatter to look at, is the `LineFormatter`.
>
> This formatter, as its name might indicate, is able to return a lineal string representation of the log record provided.
>
>
> It is also capable to interpolate values from the log record, into the output format template used by the formatter to generate the final result, and in order to do it, you need to provide the log record values you are interested in, in the output template string using the form %value%, e.g: "'%context.foo% => %extra.foo%'" , in this example the values $record->context["foo"] and $record->extra["foo"] will be rendered as part of th final result.
In the following example, we demonstrate how to:
Expand All @@ -229,7 +229,7 @@ $output = "%datetime% > %level_name% > %message% %context% %extra%\n";
$formatter = new LineFormatter($output, $dateFormat);

// Create a handler
$stream = new StreamHandler(__DIR__.'/my_app.log', Logger::DEBUG);
$stream = new StreamHandler(__DIR__.'/my_app.log', Level::Debug);
$stream->setFormatter($formatter);

// bind it to a logger object
Expand Down
2 changes: 1 addition & 1 deletion doc/04-extending.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class PDOHandler extends AbstractProcessingHandler
private $pdo;
private $statement;

public function __construct(PDO $pdo, $level = Logger::DEBUG, bool $bubble = true)
public function __construct(PDO $pdo, $level = Level::Debug, bool $bubble = true)
{
$this->pdo = $pdo;
parent::__construct($level, $bubble);
Expand Down
3 changes: 1 addition & 2 deletions doc/sockets.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ $handler = new SocketHandler('unix:///var/log/httpd_app_log.socket');
$handler->setPersistent(true);

// Now add the handler
$logger->pushHandler($handler, Logger::DEBUG);
$logger->pushHandler($handler, Level::Debug);

// You can now use your logger
$logger->info('My logger is now ready');
Expand All @@ -36,4 +36,3 @@ $logger->info('My logger is now ready');
In this example, using syslog-ng, you should see the log on the log server:

cweb1 [2012-02-26 00:12:03] my_logger.INFO: My logger is now ready [] []

28 changes: 16 additions & 12 deletions src/Monolog/Formatter/ChromePHPFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace Monolog\Formatter;

use Monolog\Level;
use Monolog\Logger;
use Monolog\LogRecord;

Expand All @@ -24,18 +25,21 @@ class ChromePHPFormatter implements FormatterInterface
/**
* Translates Monolog log levels to Wildfire levels.
*
* @var array<int, 'log'|'info'|'warn'|'error'>
* @return 'log'|'info'|'warn'|'error'
*/
private $logLevels = [
Logger::DEBUG => 'log',
Logger::INFO => 'info',
Logger::NOTICE => 'info',
Logger::WARNING => 'warn',
Logger::ERROR => 'error',
Logger::CRITICAL => 'error',
Logger::ALERT => 'error',
Logger::EMERGENCY => 'error',
];
private function toWildfireLevel(Level $level): string
{
return match ($level) {
Level::Debug => 'log',
Level::Info => 'info',
Level::Notice => 'info',
Level::Warning => 'warn',
Level::Error => 'error',
Level::Critical => 'error',
Level::Alert => 'error',
Level::Emergency => 'error',
};
}

/**
* {@inheritDoc}
Expand Down Expand Up @@ -64,7 +68,7 @@ public function format(LogRecord $record)
$record->channel,
$message,
$backtrace,
$this->logLevels[$record->level],
$this->toWildfireLevel($record->level),
];
}

Expand Down
4 changes: 2 additions & 2 deletions src/Monolog/Formatter/FlowdockFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public function format(LogRecord $record): array
{
$tags = [
'#logs',
'#' . strtolower($record->levelName),
'#' . strtolower($record->levelName->value),
'#' . $record->channel,
];

Expand All @@ -56,7 +56,7 @@ public function format(LogRecord $record): array
$subject = sprintf(
'in %s: %s - %s',
$this->source,
$record->levelName,
$record->levelName->value,
$this->getShortMessage($record->message)
);

Expand Down
6 changes: 3 additions & 3 deletions src/Monolog/Formatter/FluentdFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public function format(LogRecord $record): string
{
$tag = $record->channel;
if ($this->levelTag) {
$tag .= '.' . strtolower($record->levelName);
$tag .= '.' . strtolower($record->levelName->value);
}

$message = [
Expand All @@ -70,8 +70,8 @@ public function format(LogRecord $record): string
];

if (!$this->levelTag) {
$message['level'] = $record->level;
$message['level_name'] = $record->levelName;
$message['level'] = $record->level->value;
$message['level_name'] = $record->levelName->value;
}

return Utils::jsonEncode([$tag, $record->datetime->getTimestamp(), $message]);
Expand Down
32 changes: 15 additions & 17 deletions src/Monolog/Formatter/GelfMessageFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace Monolog\Formatter;

use Monolog\Level;
use Monolog\Logger;
use Gelf\Message;
use Monolog\Utils;
Expand All @@ -21,8 +22,6 @@
* @see http://docs.graylog.org/en/latest/pages/gelf.html
*
* @author Matt Lehner <[email protected]>
*
* @phpstan-import-type Level from \Monolog\Logger
*/
class GelfMessageFormatter extends NormalizerFormatter
{
Expand Down Expand Up @@ -50,21 +49,20 @@ class GelfMessageFormatter extends NormalizerFormatter

/**
* Translates Monolog log levels to Graylog2 log priorities.
*
* @var array<int, int>
*
* @phpstan-var array<Level, int>
*/
private $logLevels = [
Logger::DEBUG => 7,
Logger::INFO => 6,
Logger::NOTICE => 5,
Logger::WARNING => 4,
Logger::ERROR => 3,
Logger::CRITICAL => 2,
Logger::ALERT => 1,
Logger::EMERGENCY => 0,
];
private function getGraylog2Priority(Level $level): int
{
return match ($level) {
Level::Debug => 7,
Level::Info => 6,
Level::Notice => 5,
Level::Warning => 4,
Level::Error => 3,
Level::Critical => 2,
Level::Alert => 1,
Level::Emergency => 0,
};
}

public function __construct(?string $systemName = null, ?string $extraPrefix = null, string $contextPrefix = 'ctxt_', ?int $maxLength = null)
{
Expand Down Expand Up @@ -101,7 +99,7 @@ public function format(LogRecord $record): Message
->setTimestamp($record->datetime)
->setShortMessage((string) $record->message)
->setHost($this->systemName)
->setLevel($this->logLevels[$record->level]);
->setLevel($this->getGraylog2Priority($record->level));

// message length + system name length + 200 for padding / metadata
$len = 200 + strlen((string) $record->message) + strlen($this->systemName);
Expand Down
33 changes: 17 additions & 16 deletions src/Monolog/Formatter/HtmlFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace Monolog\Formatter;

use Monolog\Level;
use Monolog\Logger;
use Monolog\Utils;
use Monolog\LogRecord;
Expand All @@ -26,19 +27,20 @@ class HtmlFormatter extends NormalizerFormatter
{
/**
* Translates Monolog log levels to html color priorities.
*
* @var array<int, string>
*/
protected $logLevels = [
Logger::DEBUG => '#CCCCCC',
Logger::INFO => '#28A745',
Logger::NOTICE => '#17A2B8',
Logger::WARNING => '#FFC107',
Logger::ERROR => '#FD7E14',
Logger::CRITICAL => '#DC3545',
Logger::ALERT => '#821722',
Logger::EMERGENCY => '#000000',
];
protected function getLevelColor(Level $level): string
{
return match ($level) {
Level::Debug => '#CCCCCC',
Level::Info => '#28A745',
Level::Notice => '#17A2B8',
Level::Warning => '#FFC107',
Level::Error => '#FD7E14',
Level::Critical => '#DC3545',
Level::Alert => '#821722',
Level::Emergency => '#000000',
};
}

/**
* @param string|null $dateFormat The format of the timestamp: one supported by DateTime::format
Expand Down Expand Up @@ -69,14 +71,13 @@ protected function addRow(string $th, string $td = ' ', bool $escapeTd = true):
* Create a HTML h1 tag
*
* @param string $title Text to be in the h1
* @param int $level Error level
* @return string
*/
protected function addTitle(string $title, int $level): string
protected function addTitle(string $title, Level $level): string
{
$title = htmlspecialchars($title, ENT_NOQUOTES, 'UTF-8');

return '<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>';
}

/**
Expand All @@ -86,7 +87,7 @@ protected function addTitle(string $title, int $level): string
*/
public function format(LogRecord $record): string
{
$output = $this->addTitle($record->levelName, $record->level);
$output = $this->addTitle($record->levelName->value, $record->level);
$output .= '<table cellspacing="1" width="100%" class="monolog-output">';

$output .= $this->addRow('Message', (string) $record->message);
Expand Down
Loading

0 comments on commit 2d006a8

Please sign in to comment.