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\Utils;
16
17/**
18 * Logs to syslog service.
19 *
20 * usage example:
21 *
22 *   $log = new Logger('application');
23 *   $syslog = new SyslogHandler('myfacility', 'local6');
24 *   $formatter = new LineFormatter("%channel%.%level_name%: %message% %extra%");
25 *   $syslog->setFormatter($formatter);
26 *   $log->pushHandler($syslog);
27 *
28 * @author Sven Paulus <sven@karlsruhe.org>
29 */
30class SyslogHandler extends AbstractSyslogHandler
31{
32    /** @var string */
33    protected $ident;
34    /** @var int */
35    protected $logopts;
36
37    /**
38     * @param string     $ident
39     * @param string|int $facility Either one of the names of the keys in $this->facilities, or a LOG_* facility constant
40     * @param int        $logopts  Option flags for the openlog() call, defaults to LOG_PID
41     */
42    public function __construct(string $ident, $facility = LOG_USER, $level = Logger::DEBUG, bool $bubble = true, int $logopts = LOG_PID)
43    {
44        parent::__construct($facility, $level, $bubble);
45
46        $this->ident = $ident;
47        $this->logopts = $logopts;
48    }
49
50    /**
51     * {@inheritDoc}
52     */
53    public function close(): void
54    {
55        closelog();
56    }
57
58    /**
59     * {@inheritDoc}
60     */
61    protected function write(array $record): void
62    {
63        if (!openlog($this->ident, $this->logopts, $this->facility)) {
64            throw new \LogicException('Can\'t open syslog for ident "'.$this->ident.'" and facility "'.$this->facility.'"' . Utils::getRecordMessageForException($record));
65        }
66        syslog($this->logLevels[$record['level']], (string) $record['formatted']);
67    }
68}
69