SqsHandler.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php declare(strict_types=1);
  2. /*
  3. * This file is part of the Monolog package.
  4. *
  5. * (c) Jordi Boggiano <j.boggiano@seld.be>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Monolog\Handler;
  11. use Aws\Sqs\SqsClient;
  12. use Monolog\Level;
  13. use Monolog\Utils;
  14. use Monolog\LogRecord;
  15. /**
  16. * Writes to any sqs queue.
  17. *
  18. * @author Martijn van Calker <git@amvc.nl>
  19. */
  20. class SqsHandler extends AbstractProcessingHandler
  21. {
  22. /** 256 KB in bytes - maximum message size in SQS */
  23. protected const MAX_MESSAGE_SIZE = 262144;
  24. /** 100 KB in bytes - head message size for new error log */
  25. protected const HEAD_MESSAGE_SIZE = 102400;
  26. private SqsClient $client;
  27. private string $queueUrl;
  28. public function __construct(SqsClient $sqsClient, string $queueUrl, $level = Level::Debug, bool $bubble = true)
  29. {
  30. parent::__construct($level, $bubble);
  31. $this->client = $sqsClient;
  32. $this->queueUrl = $queueUrl;
  33. }
  34. /**
  35. * @inheritDoc
  36. */
  37. protected function write(LogRecord $record): void
  38. {
  39. if (!isset($record->formatted) || 'string' !== gettype($record->formatted)) {
  40. throw new \InvalidArgumentException('SqsHandler accepts only formatted records as a string' . Utils::getRecordMessageForException($record));
  41. }
  42. $messageBody = $record->formatted;
  43. if (strlen($messageBody) >= static::MAX_MESSAGE_SIZE) {
  44. $messageBody = Utils::substr($messageBody, 0, static::HEAD_MESSAGE_SIZE);
  45. }
  46. $this->client->sendMessage([
  47. 'QueueUrl' => $this->queueUrl,
  48. 'MessageBody' => $messageBody,
  49. ]);
  50. }
  51. }