1<?php declare(strict_types=1);
2
3/*
4 * This file is part of the Monolog package.
5 *
6 * (c) Jordi Boggiano <j.boggiano@seld.be>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Monolog\Handler;
13
14use Monolog\Formatter\FormatterInterface;
15use Monolog\Formatter\JsonFormatter;
16use Monolog\Logger;
17
18/**
19 * CouchDB handler
20 *
21 * @author Markus Bachmann <markus.bachmann@bachi.biz>
22 */
23class CouchDBHandler extends AbstractProcessingHandler
24{
25    /** @var mixed[] */
26    private $options;
27
28    /**
29     * @param mixed[] $options
30     */
31    public function __construct(array $options = [], $level = Logger::DEBUG, bool $bubble = true)
32    {
33        $this->options = array_merge([
34            'host'     => 'localhost',
35            'port'     => 5984,
36            'dbname'   => 'logger',
37            'username' => null,
38            'password' => null,
39        ], $options);
40
41        parent::__construct($level, $bubble);
42    }
43
44    /**
45     * {@inheritDoc}
46     */
47    protected function write(array $record): void
48    {
49        $basicAuth = null;
50        if ($this->options['username']) {
51            $basicAuth = sprintf('%s:%s@', $this->options['username'], $this->options['password']);
52        }
53
54        $url = 'http://'.$basicAuth.$this->options['host'].':'.$this->options['port'].'/'.$this->options['dbname'];
55        $context = stream_context_create([
56            'http' => [
57                'method'        => 'POST',
58                'content'       => $record['formatted'],
59                'ignore_errors' => true,
60                'max_redirects' => 0,
61                'header'        => 'Content-type: application/json',
62            ],
63        ]);
64
65        if (false === @file_get_contents($url, false, $context)) {
66            throw new \RuntimeException(sprintf('Could not connect to %s', $url));
67        }
68    }
69
70    /**
71     * {@inheritDoc}
72     */
73    protected function getDefaultFormatter(): FormatterInterface
74    {
75        return new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false);
76    }
77}
78