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