mirror of
https://github.com/Seldaek/monolog.git
synced 2025-08-06 05:07:36 +02:00
Added possibility to set max length for level name in LineFormatter
Closes #1850
This commit is contained in:
committed by
Jordi Boggiano
parent
70f6ca05b9
commit
1feb860c33
@@ -31,6 +31,7 @@ class LineFormatter extends NormalizerFormatter
|
||||
protected bool $allowInlineLineBreaks;
|
||||
protected bool $ignoreEmptyContextAndExtra;
|
||||
protected bool $includeStacktraces;
|
||||
protected ?int $maxLevelNameLength = null;
|
||||
protected Closure|null $stacktracesParser = null;
|
||||
|
||||
/**
|
||||
@@ -83,6 +84,19 @@ class LineFormatter extends NormalizerFormatter
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Allows cutting the level name to get fixed-length levels like INF for INFO, ERR for ERROR if you set this to 3 for example
|
||||
*
|
||||
* @param int|null $maxLevelNameLength Maximum characters for the level name. Set null for infinite length (default)
|
||||
* @return $this
|
||||
*/
|
||||
public function setMaxLevelNameLength(?int $maxLevelNameLength = null): self
|
||||
{
|
||||
$this->maxLevelNameLength = $maxLevelNameLength;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
@@ -90,6 +104,10 @@ class LineFormatter extends NormalizerFormatter
|
||||
{
|
||||
$vars = parent::format($record);
|
||||
|
||||
if ($this->maxLevelNameLength !== null) {
|
||||
$vars['level_name'] = substr($vars['level_name'], 0, $this->maxLevelNameLength);
|
||||
}
|
||||
|
||||
$output = $this->format;
|
||||
foreach ($vars['extra'] as $var => $val) {
|
||||
if (false !== strpos($output, '%extra.'.$var.'%')) {
|
||||
|
@@ -276,6 +276,40 @@ class LineFormatterTest extends TestCase
|
||||
|
||||
$this->assertMatchesRegularExpression('/foo\nbar/', $message);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider providerMaxLevelNameLength
|
||||
*/
|
||||
public function testMaxLevelNameLength(?int $maxLength, Level $logLevel, string $expectedLevelName): void
|
||||
{
|
||||
$formatter = new LineFormatter(maxLevelNameLength: $maxLength);
|
||||
$message = $formatter->format($this->getRecord(message: "foo\nbar", level: $logLevel));
|
||||
|
||||
$this->assertStringContainsString("test.$expectedLevelName:", $message);
|
||||
}
|
||||
|
||||
public static function providerMaxLevelNameLength(): array
|
||||
{
|
||||
return [
|
||||
'info_no_max_length' => [
|
||||
'max_length' => null,
|
||||
'level' => Level::Info,
|
||||
'expected_level_name' => 'INFO',
|
||||
],
|
||||
|
||||
'error_max_length_3' => [
|
||||
'max_length' => 3,
|
||||
'level' => Level::Error,
|
||||
'expected_level_name' => 'ERR',
|
||||
],
|
||||
|
||||
'debug_max_length_2' => [
|
||||
'max_length' => 2,
|
||||
'level' => Level::Debug,
|
||||
'expected_level_name' => 'DE',
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
class TestFoo
|
||||
|
Reference in New Issue
Block a user