MongoDBHandler.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 MongoDB\Driver\BulkWrite;
  12. use MongoDB\Driver\Manager;
  13. use MongoDB\Client;
  14. use Monolog\Logger;
  15. use Monolog\Formatter\FormatterInterface;
  16. use Monolog\Formatter\MongoDBFormatter;
  17. /**
  18. * Logs to a MongoDB database.
  19. *
  20. * Usage example:
  21. *
  22. * $log = new \Monolog\Logger('application');
  23. * $client = new \MongoDB\Client('mongodb://localhost:27017');
  24. * $mongodb = new \Monolog\Handler\MongoDBHandler($client, 'logs', 'prod');
  25. * $log->pushHandler($mongodb);
  26. *
  27. * The above examples uses the MongoDB PHP library's client class; however, the
  28. * MongoDB\Driver\Manager class from ext-mongodb is also supported.
  29. */
  30. class MongoDBHandler extends AbstractProcessingHandler
  31. {
  32. private $collection;
  33. private $manager;
  34. private $namespace;
  35. /**
  36. * Constructor.
  37. *
  38. * @param Client|Manager $mongodb MongoDB library or driver client
  39. * @param string $database Database name
  40. * @param string $collection Collection name
  41. * @param string|int $level The minimum logging level at which this handler will be triggered
  42. * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
  43. */
  44. public function __construct($mongodb, string $database, string $collection, $level = Logger::DEBUG, bool $bubble = true)
  45. {
  46. if (!($mongodb instanceof Client || $mongodb instanceof Manager)) {
  47. throw new \InvalidArgumentException('MongoDB\Client or MongoDB\Driver\Manager instance required');
  48. }
  49. if ($mongodb instanceof Client) {
  50. $this->collection = $mongodb->selectCollection($database, $collection);
  51. } else {
  52. $this->manager = $mongodb;
  53. $this->namespace = $database . '.' . $collection;
  54. }
  55. parent::__construct($level, $bubble);
  56. }
  57. protected function write(array $record): void
  58. {
  59. if (isset($this->collection)) {
  60. $this->collection->insertOne($record['formatted']);
  61. }
  62. if (isset($this->manager, $this->namespace)) {
  63. $bulk = new BulkWrite;
  64. $bulk->insert($record["formatted"]);
  65. $this->manager->executeBulkWrite($this->namespace, $bulk);
  66. }
  67. }
  68. /**
  69. * {@inheritDoc}
  70. */
  71. protected function getDefaultFormatter(): FormatterInterface
  72. {
  73. return new MongoDBFormatter;
  74. }
  75. }