CouchDBHandler.php 2.0 KB

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