Skip to content

Commit

Permalink
Added possibility to set max length for level name in LineFormatter
Browse files Browse the repository at this point in the history
Closes #1850
  • Loading branch information
philipp-check24 authored and Seldaek committed Oct 27, 2023
1 parent 70f6ca0 commit 1feb860
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/Monolog/Formatter/LineFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/**
Expand Down Expand Up @@ -83,13 +84,30 @@ public function ignoreEmptyContextAndExtra(bool $ignore = true): self
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
*/
public function format(LogRecord $record): string
{
$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.'%')) {
Expand Down
34 changes: 34 additions & 0 deletions tests/Monolog/Formatter/LineFormatterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,40 @@ public function testFormatShouldNotStripInlineLineBreaksWhenFlagIsSet()

$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
Expand Down

0 comments on commit 1feb860

Please sign in to comment.