Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Escape control characters in log messages #22937

Merged
merged 2 commits into from
Jan 17, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading