CouchDBHandler.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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\Formatter\JsonFormatter;
  12. use Monolog\Logger;
  13. /**
  14. * CouchDB handler
  15. *
  16. * @author Markus Bachmann <markus.bachmann@bachi.biz>
  17. */
  18. class CouchDBHandler extends AbstractProcessingHandler
  19. {
  20. private $options;
  21. public function __construct(array $options = array(), $level = Logger::DEBUG, $bubble = true)
  22. {
  23. $this->options = array_merge(array(
  24. 'host' => 'localhost',
  25. 'port' => 5984,
  26. 'dbname' => 'logger',
  27. 'username' => null,
  28. 'password' => null,
  29. ), $options);
  30. parent::__construct($level, $bubble);
  31. }
  32. /**
  33. * {@inheritDoc}
  34. */
  35. protected function write(array $record)
  36. {
  37. $basicAuth = null;
  38. if ($this->options['username']) {
  39. $basicAuth = sprintf('%s:%s@', $this->options['username'], $this->options['password']);
  40. }
  41. $url = 'http://'.$basicAuth.$this->options['host'].':'.$this->options['port'].'/'.$this->options['dbname'];
  42. $context = stream_context_create(array(
  43. 'http' => array(
  44. 'method' => 'POST',
  45. 'content' => $record['formatted'],
  46. 'ignore_errors' => true,
  47. 'max_redirects' => 0,
  48. 'header' => 'Content-type: application/json',
  49. ),
  50. ));
  51. if (false === @file_get_contents($url, null, $context)) {
  52. throw new \RuntimeException(sprintf('Could not connect to %s', $url));
  53. }
  54. }
  55. /**
  56. * {@inheritDoc}
  57. */
  58. protected function getDefaultFormatter()
  59. {
  60. return new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false);
  61. }
  62. }