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\Logger;
15use Monolog\Formatter\FormatterInterface;
16use Monolog\Formatter\LogmaticFormatter;
17
18/**
19 * @author Julien Breux <julien.breux@gmail.com>
20 */
21class LogmaticHandler extends SocketHandler
22{
23    /**
24     * @var string
25     */
26    private $logToken;
27
28    /**
29     * @var string
30     */
31    private $hostname;
32
33    /**
34     * @var string
35     */
36    private $appname;
37
38    /**
39     * @param string     $token    Log token supplied by Logmatic.
40     * @param string     $hostname Host name supplied by Logmatic.
41     * @param string     $appname  Application name supplied by Logmatic.
42     * @param bool       $useSSL   Whether or not SSL encryption should be used.
43     *
44     * @throws MissingExtensionException If SSL encryption is set to true and OpenSSL is missing
45     */
46    public function __construct(
47        string $token,
48        string $hostname = '',
49        string $appname = '',
50        bool $useSSL = true,
51        $level = Logger::DEBUG,
52        bool $bubble = true,
53        bool $persistent = false,
54        float $timeout = 0.0,
55        float $writingTimeout = 10.0,
56        ?float $connectionTimeout = null,
57        ?int $chunkSize = null
58    ) {
59        if ($useSSL && !extension_loaded('openssl')) {
60            throw new MissingExtensionException('The OpenSSL PHP extension is required to use SSL encrypted connection for LogmaticHandler');
61        }
62
63        $endpoint = $useSSL ? 'ssl://api.logmatic.io:10515' : 'api.logmatic.io:10514';
64        $endpoint .= '/v1/';
65
66        parent::__construct(
67            $endpoint,
68            $level,
69            $bubble,
70            $persistent,
71            $timeout,
72            $writingTimeout,
73            $connectionTimeout,
74            $chunkSize
75        );
76
77        $this->logToken = $token;
78        $this->hostname = $hostname;
79        $this->appname  = $appname;
80    }
81
82    /**
83     * {@inheritDoc}
84     */
85    protected function generateDataStream(array $record): string
86    {
87        return $this->logToken . ' ' . $record['formatted'];
88    }
89
90    /**
91     * {@inheritDoc}
92     */
93    protected function getDefaultFormatter(): FormatterInterface
94    {
95        $formatter = new LogmaticFormatter();
96
97        if (!empty($this->hostname)) {
98            $formatter->setHostname($this->hostname);
99        }
100        if (!empty($this->appname)) {
101            $formatter->setAppname($this->appname);
102        }
103
104        return $formatter;
105    }
106}
107