diff --git a/src/Monolog/Formatter/LineFormatter.php b/src/Monolog/Formatter/LineFormatter.php index 874e529b..7cebc77d 100644 --- a/src/Monolog/Formatter/LineFormatter.php +++ b/src/Monolog/Formatter/LineFormatter.php @@ -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.'%')) { diff --git a/tests/Monolog/Formatter/LineFormatterTest.php b/tests/Monolog/Formatter/LineFormatterTest.php index 831ccbc9..68d0abc5 100644 --- a/tests/Monolog/Formatter/LineFormatterTest.php +++ b/tests/Monolog/Formatter/LineFormatterTest.php @@ -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