]> git.mxchange.org Git - friendica.git/blobdiff - src/Util/Logger/SyslogLogger.php
Remove uneeded variable.
[friendica.git] / src / Util / Logger / SyslogLogger.php
index 3734e688e998503e49398221c3c67bce72a242ba..83c3fc3ce57e8707ebc4891fb7e564fba199eb65 100644 (file)
@@ -3,18 +3,20 @@
 namespace Friendica\Util\Logger;
 
 use Friendica\Network\HTTPException\InternalServerErrorException;
-use Psr\Log\InvalidArgumentException;
-use Psr\Log\LoggerInterface;
+use Friendica\Util\Introspection;
 use Psr\Log\LogLevel;
 
 /**
  * A Logger instance for syslogging (fast, but simple)
  * @see http://php.net/manual/en/function.syslog.php
  */
-class SyslogLogger implements LoggerInterface
+class SyslogLogger extends AbstractLogger
 {
+       const IDENT = 'Friendica';
+
        /**
         * Translates LogLevel log levels to syslog log priorities.
+        * @var array
         */
        private $logLevels = [
                LogLevel::DEBUG     => LOG_DEBUG,
@@ -28,10 +30,19 @@ class SyslogLogger implements LoggerInterface
        ];
 
        /**
-        * The standard ident of the syslog (added to each message)
-        * @var string
+        * Translates log priorities to string outputs
+        * @var array
         */
-       private $ident;
+       private $logToString = [
+               LOG_DEBUG   => 'DEBUG',
+               LOG_INFO    => 'INFO',
+               LOG_NOTICE  => 'NOTICE',
+               LOG_WARNING => 'WARNING',
+               LOG_ERR     => 'ERROR',
+               LOG_CRIT    => 'CRITICAL',
+               LOG_ALERT   => 'ALERT',
+               LOG_EMERG   => 'EMERGENCY'
+       ];
 
        /**
         * Indicates what logging options will be used when generating a log message
@@ -56,26 +67,47 @@ class SyslogLogger implements LoggerInterface
        private $logLevel;
 
        /**
-        * The Introspector for the current call
-        * @var Introspection
+        * A error message of the current operation
+        * @var string
         */
-       private $introspection;
+       private $errorMessage;
 
        /**
-        * @param string $channel     The channel (Syslog ident)
-        * @param string $level    The minimum loglevel at which this logger will be triggered
+        * {@inheritdoc}
+        * @param string $level       The minimum loglevel at which this logger will be triggered
         * @param int    $logOpts     Indicates what logging options will be used when generating a log message
         * @param int    $logFacility Used to specify what type of program is logging the message
         *
-        * @throws InternalServerErrorException if the loglevel isn't valid
+        * @throws \Exception
         */
        public function __construct($channel, Introspection $introspection, $level = LogLevel::NOTICE, $logOpts = LOG_PID, $logFacility = LOG_USER)
        {
-               $this->ident = $channel;
+               parent::__construct($channel, $introspection);
                $this->logOpts = $logOpts;
                $this->logFacility = $logFacility;
                $this->logLevel = $this->mapLevelToPriority($level);
-               $this->introspection = $introspection;
+               $this->introspection->addClasses(array(self::class));
+       }
+
+       /**
+        * Adds a new entry to the syslog
+        *
+        * @param int    $level
+        * @param string $message
+        * @param array  $context
+        *
+        * @throws InternalServerErrorException if the syslog isn't available
+        */
+       protected function addEntry($level, $message, $context = [])
+       {
+               $logLevel = $this->mapLevelToPriority($level);
+
+               if ($logLevel > $this->logLevel) {
+                       return;
+               }
+
+               $formattedLog = $this->formatLog($logLevel, $message, $context);
+               $this->write($logLevel, $formattedLog);
        }
 
        /**
@@ -90,126 +122,85 @@ class SyslogLogger implements LoggerInterface
        public function mapLevelToPriority($level)
        {
                if (!array_key_exists($level, $this->logLevels)) {
-                       throw new InvalidArgumentException('LogLevel \'' . $level . '\' isn\'t valid.');
+                       throw new \InvalidArgumentException(sprintf('The level "%s" is not valid.', $level));
                }
 
                return $this->logLevels[$level];
        }
 
        /**
-        * Writes a message to the syslog
-        *
-        * @param int    $priority The Priority ( @see http://php.net/manual/en/function.syslog.php#refsect1-function.syslog-parameters )
-        * @param string $message The message of the log
-        * @throws InternalServerErrorException if syslog cannot be used
+        * Closes the Syslog
         */
-       private function write($priority, $message)
-       {
-               if (!openlog($this->ident, $this->logOpts, $this->logFacility)) {
-                       throw new InternalServerErrorException('Can\'t open syslog for ident "' . $this->ident . '" and facility "' . $this->logFacility . '""');
-               }
-
-               syslog($priority, $message);
-       }
-
        public function close()
        {
                closelog();
        }
 
-       private function formatLog($level, $message, $context = [])
-       {
-               $logMessage  = '';
-
-               $logMessage .= $this->ident . ' ';
-               $logMessage .= '[' . $level . ']: ';
-               $logMessage .= $message . ' ';
-               $logMessage .= json_encode($context) . ' - ';
-               $logMessage .= json_encode($this->introspection->getRecord());
-
-               return $logMessage;
-       }
-
-       private function addEntry($level, $message, $context = [])
-       {
-               if ($level >= $this->logLevel) {
-                       return;
-               }
-
-               $formattedLog = $this->formatLog($level, $message, $context);
-               $this->write($level, $formattedLog);
-       }
-
        /**
-        * {@inheritdoc}
+        * Writes a message to the syslog
+        * @see http://php.net/manual/en/function.syslog.php#refsect1-function.syslog-parameters
+        *
+        * @param int    $priority The Priority
+        * @param string $message  The message of the log
+        *
+        * @throws InternalServerErrorException if syslog cannot be used
         */
-       public function emergency($message, array $context = array())
+       private function write($priority, $message)
        {
-               $this->addEntry(LOG_EMERG, $message, $context);
-       }
+               set_error_handler([$this, 'customErrorHandler']);
+               $opened = openlog(self::IDENT, $this->logOpts, $this->logFacility);
+               restore_error_handler();
 
-       /**
-        * {@inheritdoc}
-        */
-       public function alert($message, array $context = array())
-       {
-               $this->addEntry(LOG_ALERT, $message, $context);
-       }
+               if (!$opened) {
+                       throw new \UnexpectedValueException(sprintf('Can\'t open syslog for ident "%s" and facility "%s": ' . $this->errorMessage, $this->channel, $this->logFacility));
+               }
 
-       /**
-        * {@inheritdoc}
-        */
-       public function critical($message, array $context = array())
-       {
-               $this->addEntry(LOG_CRIT, $message, $context);
+               $this->syslogWrapper($priority, $message);
        }
 
        /**
-        * {@inheritdoc}
+        * Formats a log record for the syslog output
+        *
+        * @param int    $level   The loglevel/priority
+        * @param string $message The message
+        * @param array  $context The context of this call
+        *
+        * @return string the formatted syslog output
         */
-       public function error($message, array $context = array())
+       private function formatLog($level, $message, $context = [])
        {
-               $this->addEntry(LOG_ERR, $message, $context);
-       }
+               $record = $this->introspection->getRecord();
+               $record = array_merge($record, ['uid' => $this->logUid]);
+               $logMessage = '';
 
-       /**
-        * {@inheritdoc}
-        */
-       public function warning($message, array $context = array())
-       {
-               $this->addEntry(LOG_WARNING, $message, $context);
-       }
+               $logMessage .= $this->channel . ' ';
+               $logMessage .= '[' . $this->logToString[$level] . ']: ';
+               $logMessage .= $this->psrInterpolate($message, $context) . ' ';
+               $logMessage .= @json_encode($context) . ' - ';
+               $logMessage .= @json_encode($record);
 
-       /**
-        * {@inheritdoc}
-        */
-       public function notice($message, array $context = array())
-       {
-               $this->addEntry(LOG_NOTICE, $message, $context);
+               return $logMessage;
        }
 
-       /**
-        * {@inheritdoc}
-        */
-       public function info($message, array $context = array())
+       private function customErrorHandler($code, $msg)
        {
-               $this->addEntry(LOG_INFO, $message, $context);
+               $this->errorMessage = preg_replace('{^(fopen|mkdir)\(.*?\): }', '', $msg);
        }
 
        /**
-        * {@inheritdoc}
+        * A syslog wrapper to make syslog functionality testable
+        *
+        * @param int    $level The syslog priority
+        * @param string $entry The message to send to the syslog function
         */
-       public function debug($message, array $context = array())
+       protected function syslogWrapper($level, $entry)
        {
-               $this->addEntry(LOG_DEBUG, $message, $context);
-       }
+               set_error_handler([$this, 'customErrorHandler']);
+               $written = syslog($level, $entry);
+               restore_error_handler();
 
-       /**
-        * {@inheritdoc}
-        */
-       public function log($level, $message, array $context = array())
-       {
-               $logLevel = $this->mapLevelToPriority($level);
-               $this->addEntry($logLevel, $message, $context);
+               if (!$written) {
+                       throw new \UnexpectedValueException(sprintf('Can\'t write into syslog for ident "%s" and facility "%s": ' . $this->errorMessage, $this->channel, $this->logFacility));
+               }
        }
 }