Skip to content

Commit 8ff4ab5

Browse files
committed
Add ability to indent stack traces in LineFormatter, fixes #1835
1 parent 5d317e2 commit 8ff4ab5

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

src/Monolog/Formatter/LineFormatter.php

+19-1
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ class LineFormatter extends NormalizerFormatter
3232
protected bool $ignoreEmptyContextAndExtra;
3333
protected bool $includeStacktraces;
3434
protected ?int $maxLevelNameLength = null;
35+
protected string $indentStacktraces = '';
3536
protected Closure|null $stacktracesParser = null;
3637

3738
/**
@@ -64,6 +65,19 @@ public function includeStacktraces(bool $include = true, ?Closure $parser = null
6465
return $this;
6566
}
6667

68+
/**
69+
* Indent stack traces to separate them a bit from the main log record messages
70+
*
71+
* @param string $indent The string used to indent, for example " "
72+
* @return $this
73+
*/
74+
public function indentStacktraces(string $indent): self
75+
{
76+
$this->indentStacktraces = $indent;
77+
78+
return $this;
79+
}
80+
6781
/**
6882
* @return $this
6983
*/
@@ -261,7 +275,11 @@ private function stacktracesParser(\Throwable $e): string
261275
$trace = $this->stacktracesParserCustom($trace);
262276
}
263277

264-
return "\n[stacktrace]\n" . $trace . "\n";
278+
if ($this->indentStacktraces !== '') {
279+
$trace = str_replace("\n", "\n{$this->indentStacktraces}", $trace);
280+
}
281+
282+
return "\n{$this->indentStacktraces}[stacktrace]\n{$this->indentStacktraces}" . $trace . "\n";
265283
}
266284

267285
private function stacktracesParserCustom(string $trace): string

tests/Monolog/Formatter/LineFormatterTest.php

+14
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
use Monolog\Test\TestCase;
1515
use Monolog\Level;
16+
use RuntimeException;
1617

1718
/**
1819
* @covers Monolog\Formatter\LineFormatter
@@ -277,6 +278,19 @@ public function testFormatShouldNotStripInlineLineBreaksWhenFlagIsSet()
277278
$this->assertMatchesRegularExpression('/foo\nbar/', $message);
278279
}
279280

281+
public function testIndentStackTraces(): void
282+
{
283+
$formatter = new LineFormatter();
284+
$formatter->includeStacktraces();
285+
//$formatter->allowInlineLineBreaks();
286+
$formatter->indentStackTraces(' ');
287+
$message = $formatter->format($this->getRecord(message: "foo", context: ['exception' => new RuntimeException('lala')]));
288+
289+
$this->assertStringContainsString(' [stacktrace]', $message);
290+
$this->assertStringContainsString(' #0', $message);
291+
$this->assertStringContainsString(' #1', $message);
292+
}
293+
280294
/**
281295
* @dataProvider providerMaxLevelNameLength
282296
*/

0 commit comments

Comments
 (0)