Skip to content

Commit

Permalink
Escape control characters in log messages (#22937) (#22944)
Browse files Browse the repository at this point in the history
* Escape control characters in log messages

* Fix handling of line breaks
  • Loading branch information
sgiehl authored Jan 17, 2025
1 parent 7d302ba commit 0cf7297
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
2 changes: 2 additions & 0 deletions plugins/Monolog/Formatter/LineMessageFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ public function format(array $record)
$total = '';

foreach ($messages as $message) {
// escape control characters
$message = addcslashes($message, "\x00..\x09\x0B..\x1F\x7F");
$message = $this->prefixMessageWithRequestId($record, $message);
$total .= $this->formatMessage($class, $message, $date, $record);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public function testItShouldIndentMultilineMessage()
$formatter = new LineMessageFormatter('%level% %message%');

$record = array(
'message' => "Hello world\ntest\ntest",
'message' => "Hello world\ntest\x0Atest",
'datetime' => DateTime::createFromFormat('U', 0),
'level_name' => 'ERROR',
);
Expand Down Expand Up @@ -90,6 +90,25 @@ public function testItShouldSplitInlineLineBreaksIntoManyMessagesIfDisabled()
ERROR [1234] test
ERROR [1234] test
LOG;

$this->assertEquals($formatted, $formatter->format($record));
}

public function testItShouldEscapeControlCharacters()
{
$formatter = new LineMessageFormatter('%level% %message%', $allowInlineLineBreaks = false);

$record = array(
'message' => "Hello world\x1Btest\ntesttest",
'datetime' => DateTime::createFromFormat('U', 0),
'level_name' => 'ERROR',
);

$formatted = <<<LOG
ERROR Hello world\\033test
ERROR test\\033test
LOG;

$this->assertEquals($formatted, $formatter->format($record));
Expand Down

0 comments on commit 0cf7297

Please sign in to comment.