1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* Phoole (PHP7.2+) |
5
|
|
|
* |
6
|
|
|
* @category Library |
7
|
|
|
* @package Phoole\Logger |
8
|
|
|
* @copyright Copyright (c) 2019 Hong Zhang |
9
|
|
|
*/ |
10
|
|
|
declare(strict_types=1); |
11
|
|
|
|
12
|
|
|
namespace Phoole\Logger\Handler; |
13
|
|
|
|
14
|
|
|
use Psr\Log\LogLevel; |
15
|
|
|
use Phoole\Logger\Entry\LogEntryInterface; |
16
|
|
|
use Phoole\Logger\Formatter\FormatterInterface; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* log to syslog on UNIX type system |
20
|
|
|
* |
21
|
|
|
* @package Phoole\Logger |
22
|
|
|
*/ |
23
|
|
|
class SyslogHandler extends HandlerAbstract |
24
|
|
|
{ |
25
|
|
|
/** |
26
|
|
|
* syslog facility |
27
|
|
|
* |
28
|
|
|
* @var int |
29
|
|
|
*/ |
30
|
|
|
protected $facility; |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* syslog options |
34
|
|
|
* |
35
|
|
|
* @var int |
36
|
|
|
*/ |
37
|
|
|
protected $logopts; |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* syslog levels |
41
|
|
|
* |
42
|
|
|
* @var array |
43
|
|
|
* @access protected |
44
|
|
|
*/ |
45
|
|
|
protected $priorities = [ |
46
|
|
|
LogLevel::DEBUG => \LOG_DEBUG, |
47
|
|
|
LogLevel::INFO => \LOG_INFO, |
48
|
|
|
LogLevel::NOTICE => \LOG_NOTICE, |
49
|
|
|
LogLevel::WARNING => \LOG_WARNING, |
50
|
|
|
LogLevel::ERROR => \LOG_ERR, |
51
|
|
|
LogLevel::CRITICAL => \LOG_CRIT, |
52
|
|
|
LogLevel::ALERT => \LOG_ALERT, |
53
|
|
|
LogLevel::EMERGENCY => \LOG_EMERG, |
54
|
|
|
]; |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @param int $facility |
58
|
|
|
* @param int $logOpts |
59
|
|
|
* @param FormatterInterface $formatter |
60
|
|
|
*/ |
61
|
|
|
public function __construct( |
62
|
|
|
int $facility = \LOG_USER, |
63
|
|
|
int $logOpts = \LOG_PID, |
64
|
|
|
?FormatterInterface $formatter = NULL |
65
|
|
|
) { |
66
|
|
|
$this->facility = $facility; |
67
|
|
|
$this->logopts = $logOpts; |
68
|
|
|
parent::__construct($formatter); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
/** |
72
|
|
|
* {@inheritDoc} |
73
|
|
|
*/ |
74
|
|
|
protected function write(LogEntryInterface $entry) |
75
|
|
|
{ |
76
|
|
|
$context = $entry->getContext(); |
77
|
|
|
$ident = $context['__channel'] ?? 'LOG'; |
78
|
|
|
if (!openlog($ident, $this->logopts, $this->facility)) { |
79
|
|
|
throw new \LogicException("openlog() failed"); |
80
|
|
|
} |
81
|
|
|
syslog( |
82
|
|
|
$this->priorities[$entry->getLevel()], |
83
|
|
|
$this->getFormatter()->format($entry) |
84
|
|
|
); |
85
|
|
|
closelog(); |
86
|
|
|
} |
87
|
|
|
} |