DynamoDbHandler.php 2.4 KB

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