SqsHandler.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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\Logger;
  13. use Monolog\Utils;
  14. /**
  15. * Writes to any sqs queue.
  16. *
  17. * @author Martijn van Calker <git@amvc.nl>
  18. */
  19. class SqsHandler extends AbstractProcessingHandler
  20. {
  21. /** 256 KB in bytes - maximum message size in SQS */
  22. protected const MAX_MESSAGE_SIZE = 262144;
  23. /** 100 KB in bytes - head message size for new error log */
  24. protected const HEAD_MESSAGE_SIZE = 102400;
  25. /** @var SqsClient */
  26. private $client;
  27. /** @var string */
  28. private $queueUrl;
  29. public function __construct(SqsClient $sqsClient, string $queueUrl, $level = Logger::DEBUG, bool $bubble = true)
  30. {
  31. parent::__construct($level, $bubble);
  32. $this->client = $sqsClient;
  33. $this->queueUrl = $queueUrl;
  34. }
  35. /**
  36. * {@inheritdoc}
  37. */
  38. protected function write(array $record): void
  39. {
  40. if (!isset($record['formatted']) || 'string' !== gettype($record['formatted'])) {
  41. throw new \InvalidArgumentException('SqsHandler accepts only formatted records as a string');
  42. }
  43. $messageBody = $record['formatted'];
  44. if (strlen($messageBody) >= static::MAX_MESSAGE_SIZE) {
  45. $messageBody = Utils::substr($messageBody, 0, static::HEAD_MESSAGE_SIZE);
  46. }
  47. $this->client->sendMessage([
  48. 'QueueUrl' => $this->queueUrl,
  49. 'MessageBody' => $messageBody,
  50. ]);
  51. }
  52. }