DynamoDbHandler.php 2.1 KB

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