1
0
mirror of https://github.com/Seldaek/monolog.git synced 2025-08-04 12:17:35 +02:00

Add ability to indent stack traces in LineFormatter, fixes #1835

This commit is contained in:
Jordi Boggiano
2023-10-27 16:19:09 +02:00
parent 5d317e2c6f
commit 8ff4ab5c94
2 changed files with 33 additions and 1 deletions

View File

@@ -32,6 +32,7 @@ class LineFormatter extends NormalizerFormatter
protected bool $ignoreEmptyContextAndExtra; protected bool $ignoreEmptyContextAndExtra;
protected bool $includeStacktraces; protected bool $includeStacktraces;
protected ?int $maxLevelNameLength = null; protected ?int $maxLevelNameLength = null;
protected string $indentStacktraces = '';
protected Closure|null $stacktracesParser = null; protected Closure|null $stacktracesParser = null;
/** /**
@@ -64,6 +65,19 @@ class LineFormatter extends NormalizerFormatter
return $this; return $this;
} }
/**
* Indent stack traces to separate them a bit from the main log record messages
*
* @param string $indent The string used to indent, for example " "
* @return $this
*/
public function indentStacktraces(string $indent): self
{
$this->indentStacktraces = $indent;
return $this;
}
/** /**
* @return $this * @return $this
*/ */
@@ -261,7 +275,11 @@ class LineFormatter extends NormalizerFormatter
$trace = $this->stacktracesParserCustom($trace); $trace = $this->stacktracesParserCustom($trace);
} }
return "\n[stacktrace]\n" . $trace . "\n"; if ($this->indentStacktraces !== '') {
$trace = str_replace("\n", "\n{$this->indentStacktraces}", $trace);
}
return "\n{$this->indentStacktraces}[stacktrace]\n{$this->indentStacktraces}" . $trace . "\n";
} }
private function stacktracesParserCustom(string $trace): string private function stacktracesParserCustom(string $trace): string

View File

@@ -13,6 +13,7 @@ namespace Monolog\Formatter;
use Monolog\Test\TestCase; use Monolog\Test\TestCase;
use Monolog\Level; use Monolog\Level;
use RuntimeException;
/** /**
* @covers Monolog\Formatter\LineFormatter * @covers Monolog\Formatter\LineFormatter
@@ -277,6 +278,19 @@ class LineFormatterTest extends TestCase
$this->assertMatchesRegularExpression('/foo\nbar/', $message); $this->assertMatchesRegularExpression('/foo\nbar/', $message);
} }
public function testIndentStackTraces(): void
{
$formatter = new LineFormatter();
$formatter->includeStacktraces();
//$formatter->allowInlineLineBreaks();
$formatter->indentStackTraces(' ');
$message = $formatter->format($this->getRecord(message: "foo", context: ['exception' => new RuntimeException('lala')]));
$this->assertStringContainsString(' [stacktrace]', $message);
$this->assertStringContainsString(' #0', $message);
$this->assertStringContainsString(' #1', $message);
}
/** /**
* @dataProvider providerMaxLevelNameLength * @dataProvider providerMaxLevelNameLength
*/ */