Skip to content

Commit

Permalink
Include record message/context/extra data when throwing an exception …
Browse files Browse the repository at this point in the history
…because the log cannot be opened, fixes #1630
  • Loading branch information
Seldaek committed Mar 14, 2022
1 parent e289293 commit c02d86f
Show file tree
Hide file tree
Showing 7 changed files with 39 additions and 10 deletions.
2 changes: 1 addition & 1 deletion src/Monolog/Handler/SqsHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public function __construct(SqsClient $sqsClient, string $queueUrl, $level = Log
protected function write(array $record): void
{
if (!isset($record['formatted']) || 'string' !== gettype($record['formatted'])) {
throw new \InvalidArgumentException('SqsHandler accepts only formatted records as a string');
throw new \InvalidArgumentException('SqsHandler accepts only formatted records as a string' . Utils::getRecordMessageForException($record));
}

$messageBody = $record['formatted'];
Expand Down
6 changes: 3 additions & 3 deletions src/Monolog/Handler/StreamHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ protected function write(array $record): void
if (!is_resource($this->stream)) {
$url = $this->url;
if (null === $url || '' === $url) {
throw new \LogicException('Missing stream url, the stream can not be opened. This may be caused by a premature call to close().');
throw new \LogicException('Missing stream url, the stream can not be opened. This may be caused by a premature call to close().' . Utils::getRecordMessageForException($record));
}
$this->createDir($url);
$this->errorMessage = null;
Expand All @@ -143,15 +143,15 @@ protected function write(array $record): void
if (!is_resource($stream)) {
$this->stream = null;

throw new \UnexpectedValueException(sprintf('The stream or file "%s" could not be opened in append mode: '.$this->errorMessage, $url));
throw new \UnexpectedValueException(sprintf('The stream or file "%s" could not be opened in append mode: '.$this->errorMessage, $url) . Utils::getRecordMessageForException($record));
}
stream_set_chunk_size($stream, $this->streamChunkSize);
$this->stream = $stream;
}

$stream = $this->stream;
if (!is_resource($stream)) {
throw new \LogicException('No stream was opened yet');
throw new \LogicException('No stream was opened yet' . Utils::getRecordMessageForException($record));
}

if ($this->useLocking) {
Expand Down
2 changes: 1 addition & 1 deletion src/Monolog/Handler/SwiftMailerHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ protected function buildMessage(string $content, array $records): Swift_Message
}

if (!$message instanceof Swift_Message) {
throw new \InvalidArgumentException('Could not resolve message as instance of Swift_Message or a callable returning it');
throw new \InvalidArgumentException('Could not resolve message as instance of Swift_Message or a callable returning it' . Utils::getRecordMessageForException($record));
}

if ($records) {
Expand Down
2 changes: 1 addition & 1 deletion src/Monolog/Handler/SyslogHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public function close(): void
protected function write(array $record): void
{
if (!openlog($this->ident, $this->logopts, $this->facility)) {
throw new \LogicException('Can\'t open syslog for ident "'.$this->ident.'" and facility "'.$this->facility.'"');
throw new \LogicException('Can\'t open syslog for ident "'.$this->ident.'" and facility "'.$this->facility.'"' . Utils::getRecordMessageForException($record));
}
syslog($this->logLevels[$record['level']], (string) $record['formatted']);
}
Expand Down
7 changes: 4 additions & 3 deletions src/Monolog/Handler/TelegramBotHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use RuntimeException;
use Monolog\Logger;
use Monolog\Utils;

/**
* Handler send logs to Telegram using Telegram Bot API.
Expand Down Expand Up @@ -247,12 +248,12 @@ protected function sendCurl(string $message): void

$result = Curl\Util::execute($ch);
if (!is_string($result)) {
throw new RuntimeException('Telegram API error. Description: No response');
throw new RuntimeException('Telegram API error. Description: No response' . Utils::getRecordMessageForException($record));
}
$result = json_decode($result, true);

if ($result['ok'] === false) {
throw new RuntimeException('Telegram API error. Description: ' . $result['description']);
throw new RuntimeException('Telegram API error. Description: ' . $result['description'] . Utils::getRecordMessageForException($record));
}
}

Expand All @@ -265,7 +266,7 @@ private function handleMessageLength(string $message): array
{
$truncatedMarker = ' (...truncated)';
if (!$this->splitLongMessages && strlen($message) > self::MAX_MESSAGE_LENGTH) {
return [substr($message, 0, self::MAX_MESSAGE_LENGTH - strlen($truncatedMarker)) . $truncatedMarker];
return [Utils::substr($message, 0, self::MAX_MESSAGE_LENGTH - strlen($truncatedMarker)) . $truncatedMarker];
}

return str_split($message, self::MAX_MESSAGE_LENGTH);
Expand Down
21 changes: 21 additions & 0 deletions src/Monolog/Utils.php
Original file line number Diff line number Diff line change
Expand Up @@ -260,4 +260,25 @@ public static function expandIniShorthandBytes($val)

return $val;
}

/**
* @param array<mixed> $record
*/
public static function getRecordMessageForException(array $record): string
{
$context = '';
$extra = '';
try {
if ($record['context']) {
$context = "\nContext: " . json_encode($record['context']);
}
if ($record['extra']) {
$extra = "\nExtra: " . json_encode($record['extra']);
}
} catch (\Throwable $e) {
// noop
}

return "\nThe exception occurred while attempting to log: " . $record['message'] . $context . $extra;
}
}
9 changes: 8 additions & 1 deletion tests/Monolog/Handler/StreamHandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -145,9 +145,16 @@ public function testWriteInvalidArgument($invalidArgument)
public function testWriteInvalidResource()
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessage('The stream or file "bogus://url" could not be opened in append mode: Failed to open stream: No such file or directory
The exception occurred while attempting to log: test
Context: {"foo":"bar"}
Extra: [1,2,3]');

$handler = new StreamHandler('bogus://url');
$handler->handle($this->getRecord());
$record = $this->getRecord();
$record['context'] = ['foo' => 'bar'];
$record['extra'] = [1, 2, 3];
$handler->handle($record);
}

/**
Expand Down

0 comments on commit c02d86f

Please sign in to comment.