MongoDBHandler.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 Monolog\Logger;
  12. use Monolog\Formatter\NormalizerFormatter;
  13. /**
  14. * Logs to a MongoDB database.
  15. *
  16. * usage example:
  17. *
  18. * $log = new Logger('application');
  19. * $mongodb = new MongoDBHandler(new \Mongo("mongodb://localhost:27017"), "logs", "prod");
  20. * $log->pushHandler($mongodb);
  21. *
  22. * @author Thomas Tourlourat <thomas@tourlourat.com>
  23. */
  24. class MongoDBHandler extends AbstractProcessingHandler
  25. {
  26. protected $mongoCollection;
  27. public function __construct($mongo, $database, $collection, $level = Logger::DEBUG, $bubble = true)
  28. {
  29. if (!($mongo instanceof \MongoClient || $mongo instanceof \Mongo || $mongo instanceof \MongoDB\Client)) {
  30. throw new \InvalidArgumentException('MongoClient, Mongo or MongoDB\Client instance required');
  31. }
  32. $this->mongoCollection = $mongo->selectCollection($database, $collection);
  33. parent::__construct($level, $bubble);
  34. }
  35. protected function write(array $record)
  36. {
  37. if ($this->mongoCollection instanceof \MongoDB\Collection) {
  38. $this->mongoCollection->insertOne($record["formatted"]);
  39. } else {
  40. $this->mongoCollection->save($record["formatted"]);
  41. }
  42. }
  43. /**
  44. * {@inheritDoc}
  45. */
  46. protected function getDefaultFormatter()
  47. {
  48. return new NormalizerFormatter();
  49. }
  50. }