1
0
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:
Philipp Müller
2023-10-26 20:33:53 +02:00
committed by Jordi Boggiano
parent 70f6ca05b9
commit 1feb860c33
2 changed files with 52 additions and 0 deletions

View File

@@ -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.'%')) {

View File

@@ -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