SyslogTarget   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 1 Features 0
Metric Value
eloc 18
c 2
b 1
f 0
dl 0
loc 52
ccs 11
cts 11
cp 1
rs 10
wmc 3

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 1
A export() 0 10 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Log\Target\Syslog;
6
7
use Psr\Log\LogLevel;
8
use RuntimeException;
9
use Yiisoft\Log\Message;
10
use Yiisoft\Log\Target;
11
12
use const LOG_ALERT;
13
use const LOG_CRIT;
14
use const LOG_DEBUG;
15
use const LOG_EMERG;
16
use const LOG_ERR;
17
use const LOG_INFO;
18
use const LOG_NOTICE;
19
use const LOG_ODELAY;
20
use const LOG_PID;
21
use const LOG_USER;
22
use const LOG_WARNING;
23
24
/**
25
 * `SyslogTarget` writes log to syslog.
26
 */
27
final class SyslogTarget extends Target
28
{
29
    private const SYSLOG_LEVELS = [
30
        LogLevel::EMERGENCY => LOG_EMERG,
31
        LogLevel::ALERT => LOG_ALERT,
32
        LogLevel::CRITICAL => LOG_CRIT,
33
        LogLevel::ERROR => LOG_ERR,
34
        LogLevel::WARNING => LOG_WARNING,
35
        LogLevel::NOTICE => LOG_NOTICE,
36
        LogLevel::INFO => LOG_INFO,
37
        LogLevel::DEBUG => LOG_DEBUG,
38
    ];
39
40
    /**
41
     * @param string $identity The string that is prefixed to each message.
42
     * @param int $options Bit options to be used when generating a log message.
43
     * @param int $facility Used to specify what type of program is logging the message. This allows you to specify
44
     * (in your machine's syslog configuration) how messages coming from different facilities will be handled.
45
     *
46
     * @link https://www.php.net/openlog
47
     */
48 3
    public function __construct(
49
        private string $identity,
50
        private int $options = LOG_ODELAY | LOG_PID,
51
        private int $facility = LOG_USER
52
    ) {
53 3
        parent::__construct();
54
55 3
        $this->setFormat(static function (Message $message) {
56 1
            return "[{$message->level()}][{$message->context('category', '')}] {$message->message()}";
57 3
        });
58
    }
59
60
    /**
61
     * Writes log messages to syslog.
62
     *
63
     * @see https://www.php.net/openlog
64
     * @see https://www.php.net/syslog
65
     * @see https://www.php.net/closelog
66
     *
67
     * @throws RuntimeException If unable to export log through system log.
68
     */
69 2
    protected function export(): void
70
    {
71 2
        $formattedMessages = $this->getFormattedMessages();
72 2
        openlog($this->identity, $this->options, $this->facility);
73
74 2
        foreach ($this->getMessages() as $key => $message) {
75 2
            syslog(self::SYSLOG_LEVELS[$message->level()], $formattedMessages[$key]);
76
        }
77
78 2
        closelog();
79
    }
80
}
81