DynamoDbHandler.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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\Sdk;
  12. use Aws\DynamoDb\DynamoDbClient;
  13. use Monolog\Formatter\FormatterInterface;
  14. use Aws\DynamoDb\Marshaler;
  15. use Monolog\Formatter\ScalarFormatter;
  16. use Monolog\Logger;
  17. /**
  18. * Amazon DynamoDB handler (http://aws.amazon.com/dynamodb/)
  19. *
  20. * @link https://github.com/aws/aws-sdk-php/
  21. * @author Andrew Lawson <adlawson@gmail.com>
  22. */
  23. class DynamoDbHandler extends AbstractProcessingHandler
  24. {
  25. public const DATE_FORMAT = 'Y-m-d\TH:i:s.uO';
  26. /**
  27. * @var DynamoDbClient
  28. */
  29. protected $client;
  30. /**
  31. * @var string
  32. */
  33. protected $table;
  34. /**
  35. * @var int
  36. */
  37. protected $version;
  38. /**
  39. * @var Marshaler
  40. */
  41. protected $marshaler;
  42. /**
  43. * @param int|string $level
  44. */
  45. public function __construct(DynamoDbClient $client, string $table, $level = Logger::DEBUG, bool $bubble = true)
  46. {
  47. if (defined('Aws\Sdk::VERSION') && version_compare(Sdk::VERSION, '3.0', '>=')) {
  48. $this->version = 3;
  49. $this->marshaler = new Marshaler;
  50. } else {
  51. $this->version = 2;
  52. }
  53. $this->client = $client;
  54. $this->table = $table;
  55. parent::__construct($level, $bubble);
  56. }
  57. /**
  58. * {@inheritdoc}
  59. */
  60. protected function write(array $record): void
  61. {
  62. $filtered = $this->filterEmptyFields($record['formatted']);
  63. if ($this->version === 3) {
  64. $formatted = $this->marshaler->marshalItem($filtered);
  65. } else {
  66. $formatted = $this->client->formatAttributes($filtered);
  67. }
  68. $this->client->putItem([
  69. 'TableName' => $this->table,
  70. 'Item' => $formatted,
  71. ]);
  72. }
  73. protected function filterEmptyFields(array $record): array
  74. {
  75. return array_filter($record, function ($value) {
  76. return !empty($value) || false === $value || 0 === $value;
  77. });
  78. }
  79. /**
  80. * {@inheritdoc}
  81. */
  82. protected function getDefaultFormatter(): FormatterInterface
  83. {
  84. return new ScalarFormatter(self::DATE_FORMAT);
  85. }
  86. }