]> git.mxchange.org Git - friendica.git/blob - src/Util/Logger/SyslogLogger.php
Merge branch '2019.06-rc'
[friendica.git] / src / Util / Logger / SyslogLogger.php
1 <?php
2
3 namespace Friendica\Util\Logger;
4
5 use Friendica\Network\HTTPException\InternalServerErrorException;
6 use Friendica\Util\Introspection;
7 use Psr\Log\LogLevel;
8
9 /**
10  * A Logger instance for syslogging (fast, but simple)
11  * @see http://php.net/manual/en/function.syslog.php
12  */
13 class SyslogLogger extends AbstractLogger
14 {
15         const IDENT = 'Friendica';
16
17         /**
18          * Translates LogLevel log levels to syslog log priorities.
19          * @var array
20          */
21         private $logLevels = [
22                 LogLevel::DEBUG     => LOG_DEBUG,
23                 LogLevel::INFO      => LOG_INFO,
24                 LogLevel::NOTICE    => LOG_NOTICE,
25                 LogLevel::WARNING   => LOG_WARNING,
26                 LogLevel::ERROR     => LOG_ERR,
27                 LogLevel::CRITICAL  => LOG_CRIT,
28                 LogLevel::ALERT     => LOG_ALERT,
29                 LogLevel::EMERGENCY => LOG_EMERG,
30         ];
31
32         /**
33          * Translates log priorities to string outputs
34          * @var array
35          */
36         private $logToString = [
37                 LOG_DEBUG   => 'DEBUG',
38                 LOG_INFO    => 'INFO',
39                 LOG_NOTICE  => 'NOTICE',
40                 LOG_WARNING => 'WARNING',
41                 LOG_ERR     => 'ERROR',
42                 LOG_CRIT    => 'CRITICAL',
43                 LOG_ALERT   => 'ALERT',
44                 LOG_EMERG   => 'EMERGENCY'
45         ];
46
47         /**
48          * Indicates what logging options will be used when generating a log message
49          * @see http://php.net/manual/en/function.openlog.php#refsect1-function.openlog-parameters
50          *
51          * @var int
52          */
53         private $logOpts;
54
55         /**
56          * Used to specify what type of program is logging the message
57          * @see http://php.net/manual/en/function.openlog.php#refsect1-function.openlog-parameters
58          *
59          * @var int
60          */
61         private $logFacility;
62
63         /**
64          * The minimum loglevel at which this logger will be triggered
65          * @var int
66          */
67         private $logLevel;
68
69         /**
70          * A error message of the current operation
71          * @var string
72          */
73         private $errorMessage;
74
75         /**
76          * {@inheritdoc}
77          * @param string $level       The minimum loglevel at which this logger will be triggered
78          * @param int    $logOpts     Indicates what logging options will be used when generating a log message
79          * @param int    $logFacility Used to specify what type of program is logging the message
80          *
81          * @throws \Exception
82          */
83         public function __construct($channel, Introspection $introspection, $level = LogLevel::NOTICE, $logOpts = LOG_PID, $logFacility = LOG_USER)
84         {
85                 parent::__construct($channel, $introspection);
86                 $this->logOpts = $logOpts;
87                 $this->logFacility = $logFacility;
88                 $this->logLevel = $this->mapLevelToPriority($level);
89                 $this->introspection->addClasses(array(self::class));
90         }
91
92         /**
93          * Adds a new entry to the syslog
94          *
95          * @param int    $level
96          * @param string $message
97          * @param array  $context
98          *
99          * @throws InternalServerErrorException if the syslog isn't available
100          */
101         protected function addEntry($level, $message, $context = [])
102         {
103                 $logLevel = $this->mapLevelToPriority($level);
104
105                 if ($logLevel > $this->logLevel) {
106                         return;
107                 }
108
109                 $formattedLog = $this->formatLog($logLevel, $message, $context);
110                 $this->write($logLevel, $formattedLog);
111         }
112
113         /**
114          * Maps the LogLevel (@see LogLevel ) to a SysLog priority (@see http://php.net/manual/en/function.syslog.php#refsect1-function.syslog-parameters )
115          *
116          * @param string $level A LogLevel
117          *
118          * @return int The SysLog priority
119          *
120          * @throws \Psr\Log\InvalidArgumentException If the loglevel isn't valid
121          */
122         public function mapLevelToPriority($level)
123         {
124                 if (!array_key_exists($level, $this->logLevels)) {
125                         throw new \InvalidArgumentException(sprintf('The level "%s" is not valid.', $level));
126                 }
127
128                 return $this->logLevels[$level];
129         }
130
131         /**
132          * Closes the Syslog
133          */
134         public function close()
135         {
136                 closelog();
137         }
138
139         /**
140          * Writes a message to the syslog
141          * @see http://php.net/manual/en/function.syslog.php#refsect1-function.syslog-parameters
142          *
143          * @param int    $priority The Priority
144          * @param string $message  The message of the log
145          *
146          * @throws InternalServerErrorException if syslog cannot be used
147          */
148         private function write($priority, $message)
149         {
150                 set_error_handler([$this, 'customErrorHandler']);
151                 $opened = openlog(self::IDENT, $this->logOpts, $this->logFacility);
152                 restore_error_handler();
153
154                 if (!$opened) {
155                         throw new \UnexpectedValueException(sprintf('Can\'t open syslog for ident "%s" and facility "%s": ' . $this->errorMessage, $this->channel, $this->logFacility));
156                 }
157
158                 $this->syslogWrapper($priority, $message);
159         }
160
161         /**
162          * Formats a log record for the syslog output
163          *
164          * @param int    $level   The loglevel/priority
165          * @param string $message The message
166          * @param array  $context The context of this call
167          *
168          * @return string the formatted syslog output
169          */
170         private function formatLog($level, $message, $context = [])
171         {
172                 $record = $this->introspection->getRecord();
173                 $record = array_merge($record, ['uid' => $this->logUid]);
174                 $logMessage = '';
175
176                 $logMessage .= $this->channel . ' ';
177                 $logMessage .= '[' . $this->logToString[$level] . ']: ';
178                 $logMessage .= $this->psrInterpolate($message, $context) . ' ';
179                 $logMessage .= @json_encode($context) . ' - ';
180                 $logMessage .= @json_encode($record);
181
182                 return $logMessage;
183         }
184
185         private function customErrorHandler($code, $msg)
186         {
187                 $this->errorMessage = preg_replace('{^(fopen|mkdir)\(.*?\): }', '', $msg);
188         }
189
190         /**
191          * A syslog wrapper to make syslog functionality testable
192          *
193          * @param int    $level The syslog priority
194          * @param string $entry The message to send to the syslog function
195          */
196         protected function syslogWrapper($level, $entry)
197         {
198                 set_error_handler([$this, 'customErrorHandler']);
199                 $written = syslog($level, $entry);
200                 restore_error_handler();
201
202                 if (!$written) {
203                         throw new \UnexpectedValueException(sprintf('Can\'t write into syslog for ident "%s" and facility "%s": ' . $this->errorMessage, $this->channel, $this->logFacility));
204                 }
205         }
206 }