From 2c20b32b8d9a0cd12346867dd1c685cb42e540f2 Mon Sep 17 00:00:00 2001 From: Robin Kunde Date: Thu, 18 Dec 2014 12:06:07 -0500 Subject: [PATCH] added support for log levels --- ApnsPHP/Abstract.php | 29 ++++--------- ApnsPHP/Feedback.php | 10 ++--- ApnsPHP/Log/Embedded.php | 86 +++++++++++++++++++++++++++++++++++++-- ApnsPHP/Log/Interface.php | 43 +++++++++++++++++++- ApnsPHP/Push.php | 18 ++++---- ApnsPHP/Push/Server.php | 18 ++++---- 6 files changed, 157 insertions(+), 47 deletions(-) diff --git a/ApnsPHP/Abstract.php b/ApnsPHP/Abstract.php index 22e53c66..36833e38 100644 --- a/ApnsPHP/Abstract.php +++ b/ApnsPHP/Abstract.php @@ -96,6 +96,8 @@ public function __construct($nEnvironment, $sProviderCertificateFile) $this->_nWriteInterval = self::WRITE_INTERVAL; $this->_nConnectRetryInterval = self::CONNECT_RETRY_INTERVAL; $this->_nSocketSelectTimeout = self::SOCKET_SELECT_TIMEOUT; + + $this->_logger = new ApnsPHP_Log_Embedded(); } /** @@ -190,7 +192,7 @@ public function getCertificateAuthority() /** * Set the write interval. * - * After each socket write operation we are sleeping for this + * After each socket write operation we are sleeping for this * time interval. To speed up the sending operations, use Zero * as parameter but some messages may be lost. * @@ -333,12 +335,12 @@ public function connect() try { $bConnected = $this->_connect(); } catch (ApnsPHP_Exception $e) { - $this->_log('ERROR: ' . $e->getMessage()); + $this->_logger->error($e->getMessage()); if ($nRetry >= $this->_nConnectRetryTimes) { throw $e; } else { - $this->_log( - "INFO: Retry to connect (" . ($nRetry+1) . + $this->_logger->info( + "Retry to connect (" . ($nRetry+1) . "/{$this->_nConnectRetryTimes})..." ); usleep($this->_nConnectRetryInterval); @@ -356,7 +358,7 @@ public function connect() public function disconnect() { if (is_resource($this->_hSocket)) { - $this->_log('INFO: Disconnected.'); + $this->_logger->info('Disconnected.'); return fclose($this->_hSocket); } return false; @@ -373,7 +375,7 @@ protected function _connect() $sURL = $this->_aServiceURLs[$this->_nEnvironment]; unset($aURLs); - $this->_log("INFO: Trying {$sURL}..."); + $this->_logger->info("Trying {$sURL}..."); /** * @see http://php.net/manual/en/context.ssl.php @@ -401,21 +403,8 @@ protected function _connect() stream_set_blocking($this->_hSocket, 0); stream_set_write_buffer($this->_hSocket, 0); - $this->_log("INFO: Connected to {$sURL}."); + $this->_logger->info("Connected to {$sURL}."); return true; } - - /** - * Logs a message through the Logger. - * - * @param $sMessage @type string The message. - */ - protected function _log($sMessage) - { - if (!isset($this->_logger)) { - $this->_logger = new ApnsPHP_Log_Embedded(); - } - $this->_logger->log($sMessage); - } } diff --git a/ApnsPHP/Feedback.php b/ApnsPHP/Feedback.php index a13d5320..be5894a7 100644 --- a/ApnsPHP/Feedback.php +++ b/ApnsPHP/Feedback.php @@ -70,11 +70,11 @@ public function receive() $this->_aFeedback = array(); $sBuffer = ''; while (!feof($this->_hSocket)) { - $this->_log('INFO: Reading...'); + $this->_logger->info('Reading...'); $sBuffer .= $sCurrBuffer = fread($this->_hSocket, 8192); $nCurrBufferLen = strlen($sCurrBuffer); if ($nCurrBufferLen > 0) { - $this->_log("INFO: {$nCurrBufferLen} bytes read."); + $this->_logger->info("{$nCurrBufferLen} bytes read."); } unset($sCurrBuffer, $nCurrBufferLen); @@ -85,7 +85,7 @@ public function receive() $sFeedbackTuple = substr($sBuffer, 0, $nFeedbackTupleLen); $sBuffer = substr($sBuffer, $nFeedbackTupleLen); $this->_aFeedback[] = $aFeedback = $this->_parseBinaryTuple($sFeedbackTuple); - $this->_log(sprintf("INFO: New feedback tuple: timestamp=%d (%s), tokenLength=%d, deviceToken=%s.", + $this->_logger->info(sprintf("New feedback tuple: timestamp=%d (%s), tokenLength=%d, deviceToken=%s.", $aFeedback['timestamp'], date('Y-m-d H:i:s', $aFeedback['timestamp']), $aFeedback['tokenLength'], $aFeedback['deviceToken'] )); @@ -97,7 +97,7 @@ public function receive() $null = NULL; $nChangedStreams = stream_select($read, $null, $null, 0, $this->_nSocketSelectTimeout); if ($nChangedStreams === false) { - $this->_log('WARNING: Unable to wait for a stream availability.'); + $this->_logger->warning('Unable to wait for a stream availability.'); break; } } @@ -114,4 +114,4 @@ protected function _parseBinaryTuple($sBinaryTuple) { return unpack('Ntimestamp/ntokenLength/H*deviceToken', $sBinaryTuple); } -} \ No newline at end of file +} diff --git a/ApnsPHP/Log/Embedded.php b/ApnsPHP/Log/Embedded.php index bfe10f3a..d3a2e0f8 100644 --- a/ApnsPHP/Log/Embedded.php +++ b/ApnsPHP/Log/Embedded.php @@ -30,15 +30,95 @@ */ class ApnsPHP_Log_Embedded implements ApnsPHP_Log_Interface { + const + STATUS = 0, + INFO = 1, + WARNING = 2, + ERROR = 3; + + protected $logLevelDescriptions = array( + self::STATUS => 'STATUS', + self::INFO => 'INFO', + self::WARNING => 'WARNING', + self::ERROR => 'ERROR', + ); + + protected $logLevel = 0; + /** * Logs a message. * * @param $sMessage @type string The message. + * @param $nLevel @type int The log level. */ - public function log($sMessage) + public function log($sMessage, $nLevel) { - printf("%s ApnsPHP[%d]: %s\n", - date('r'), getmypid(), trim($sMessage) + if ($nLevel < $this->logLevel) return; + + printf("%s ApnsPHP[%d]: %s: %s\n", + date('r'), getmypid(), $this->logLevelDescriptions[$nLevel], trim($sMessage) ); } + + /** + * Set the minimum log level of messages that should be logged. + */ + public function getLogLevel() + { + return $this->logLevel; + } + + /** + * Sets the minimum log level of messages that should be logged. + * + * @param $nLevel @type int The log level. + */ + public function setLogLevel($nLevel) + { + if (!isset($this->logLevelDescriptions[$nLevel])) { + throw new ApnsPHP_Exception('Unknown Log Level: ' . $nLevel); + } + + $this->logLevel = $nLevel; + } + + /** + * Logs a status message. + * + * @param $sMessage @type string The message. + */ + public function status($sMessage) + { + $this->log($sMessage, self::STATUS); + } + + /** + * Logs an info message. + * + * @param $sMessage @type string The message. + */ + public function info($sMessage) + { + $this->log($sMessage, self::INFO); + } + + /** + * Logs a warning message. + * + * @param $sMessage @type string The message. + */ + public function warning($sMessage) + { + $this->log($sMessage, self::WARNING); + } + + /** + * Logs an error message. + * + * @param $sMessage @type string The message. + */ + public function error($sMessage) + { + $this->log($sMessage, self::ERROR); + } } diff --git a/ApnsPHP/Log/Interface.php b/ApnsPHP/Log/Interface.php index a53b2c56..ab106ea9 100644 --- a/ApnsPHP/Log/Interface.php +++ b/ApnsPHP/Log/Interface.php @@ -36,6 +36,47 @@ interface ApnsPHP_Log_Interface * Logs a message. * * @param $sMessage @type string The message. + * @param $level @type int The log level. */ - public function log($sMessage); + public function log($sMessage, $level); + + /** + * Set the minimum log level of messages that should be logged. + */ + public function getLogLevel(); + + /** + * Sets the minimum log level of messages that should be logged. + * + * @param $nLevel @type int The log level. + */ + public function setLogLevel($nLevel); + + /** + * Logs a status message. + * + * @param $sMessage @type string The message. + */ + public function status($sMessage); + + /** + * Logs an info message. + * + * @param $sMessage @type string The message. + */ + public function info($sMessage); + + /** + * Logs a warning message. + * + * @param $sMessage @type string The message. + */ + public function warning($sMessage); + + /** + * Logs an error message. + * + * @param $sMessage @type string The message. + */ + public function error($sMessage); } diff --git a/ApnsPHP/Push.php b/ApnsPHP/Push.php index f73f3ad1..7472f237 100644 --- a/ApnsPHP/Push.php +++ b/ApnsPHP/Push.php @@ -134,7 +134,7 @@ public function send() $this->_aErrors = array(); $nRun = 1; while (($nMessages = count($this->_aMessageQueue)) > 0) { - $this->_log("INFO: Sending messages queue, run #{$nRun}: $nMessages message(s) left in queue."); + $this->_logger->info("Sending messages queue, run #{$nRun}: $nMessages message(s) left in queue."); $bError = false; foreach($this->_aMessageQueue as $k => &$aMessage) { @@ -150,18 +150,18 @@ public function send() if (!empty($aMessage['ERRORS'])) { foreach($aMessage['ERRORS'] as $aError) { if ($aError['statusCode'] == 0) { - $this->_log("INFO: Message ID {$k} {$sCustomIdentifier} has no error ({$aError['statusCode']}), removing from queue..."); + $this->_logger->info("Message ID {$k} {$sCustomIdentifier} has no error ({$aError['statusCode']}), removing from queue..."); $this->_removeMessageFromQueue($k); continue 2; } else if ($aError['statusCode'] > 1 && $aError['statusCode'] <= 8) { - $this->_log("WARNING: Message ID {$k} {$sCustomIdentifier} has an unrecoverable error ({$aError['statusCode']}), removing from queue without retrying..."); + $this->_logger->warning("Message ID {$k} {$sCustomIdentifier} has an unrecoverable error ({$aError['statusCode']}), removing from queue without retrying..."); $this->_removeMessageFromQueue($k, true); continue 2; } } if (($nErrors = count($aMessage['ERRORS'])) >= $this->_nSendRetryTimes) { - $this->_log( - "WARNING: Message ID {$k} {$sCustomIdentifier} has {$nErrors} errors, removing from queue..." + $this->_logger->warning( + "Message ID {$k} {$sCustomIdentifier} has {$nErrors} errors, removing from queue..." ); $this->_removeMessageFromQueue($k, true); continue; @@ -169,7 +169,7 @@ public function send() } $nLen = strlen($aMessage['BINARY_NOTIFICATION']); - $this->_log("STATUS: Sending message ID {$k} {$sCustomIdentifier} (" . ($nErrors + 1) . "/{$this->_nSendRetryTimes}): {$nLen} bytes."); + $this->_logger->status("Sending message ID {$k} {$sCustomIdentifier} (" . ($nErrors + 1) . "/{$this->_nSendRetryTimes}): {$nLen} bytes."); $aErrorMessage = null; if ($nLen !== ($nWritten = (int)@fwrite($this->_hSocket, $aMessage['BINARY_NOTIFICATION']))) { @@ -194,7 +194,7 @@ public function send() $null = NULL; $nChangedStreams = @stream_select($read, $null, $null, 0, $this->_nSocketSelectTimeout); if ($nChangedStreams === false) { - $this->_log('ERROR: Unable to wait for a stream availability.'); + $this->_logger->error('Unable to wait for a stream availability.'); break; } else if ($nChangedStreams > 0) { $bError = $this->_updateQueue(); @@ -339,7 +339,7 @@ protected function _updateQueue($aErrorMessage = null) unset($aStreamErrorMessage); } - $this->_log('ERROR: Unable to send message ID ' . + $this->_logger->error('Unable to send message ID ' . $aErrorMessage['identifier'] . ': ' . $aErrorMessage['statusMessage'] . ' (' . $aErrorMessage['statusCode'] . ').'); @@ -385,4 +385,4 @@ protected function _removeMessageFromQueue($nMessageID, $bError = false) } unset($this->_aMessageQueue[$nMessageID]); } -} \ No newline at end of file +} diff --git a/ApnsPHP/Push/Server.php b/ApnsPHP/Push/Server.php index bb120755..dac1b79b 100644 --- a/ApnsPHP/Push/Server.php +++ b/ApnsPHP/Push/Server.php @@ -126,13 +126,13 @@ public function onSignal($nSignal) case SIGQUIT: case SIGINT: if (($nPid = posix_getpid()) != $this->_nParentPid) { - $this->_log("INFO: Child $nPid received signal #{$nSignal}, shutdown..."); + $this->_logger->info("Child $nPid received signal #{$nSignal}, shutdown...", ApnsPHP_Log_Embedded::INFO); $this->_nRunningProcesses--; exit(0); } break; default: - $this->_log("INFO: Ignored signal #{$nSignal}."); + $this->_logger->info("Ignored signal #{$nSignal}."); break; } } @@ -146,7 +146,7 @@ public function onSignal($nSignal) public function onShutdown() { if (posix_getpid() == $this->_nParentPid) { - $this->_log('INFO: Parent shutdown, cleaning memory...'); + $this->_logger->info('Parent shutdown, cleaning memory...'); @shm_remove($this->_hShm) && @shm_detach($this->_hShm); @sem_remove($this->_hSem); } @@ -178,17 +178,17 @@ public function start() $this->_nCurrentProcess = $i; $this->_aPids[$i] = $nPid = pcntl_fork(); if ($nPid == -1) { - $this->_log('WARNING: Could not fork'); + $this->_logger->warning('Could not fork'); } else if ($nPid > 0) { // Parent process - $this->_log("INFO: Forked process PID {$nPid}"); + $this->_logger->info("Forked process PID {$nPid}"); $this->_nRunningProcesses++; } else { // Child process try { parent::connect(); } catch (ApnsPHP_Exception $e) { - $this->_log('ERROR: ' . $e->getMessage() . ', exiting...'); + $this->_logger->error($e->getMessage() . ', exiting...'); exit(1); } $this->_mainLoop(); @@ -276,7 +276,7 @@ protected function _mainLoop() pcntl_signal_dispatch(); if (posix_getppid() != $this->_nParentPid) { - $this->_log("INFO: Parent process {$this->_nParentPid} died unexpectedly, exiting..."); + $this->_logger->info("Parent process {$this->_nParentPid} died unexpectedly, exiting..."); break; } @@ -294,7 +294,7 @@ protected function _mainLoop() $nMessages = count($aQueue); if ($nMessages > 0) { - $this->_log('INFO: Process ' . ($this->_nCurrentProcess + 1) . " has {$nMessages} messages, sending..."); + $this->_logger->info('Process ' . ($this->_nCurrentProcess + 1) . " has {$nMessages} messages, sending..."); parent::send(); } else { usleep(self::MAIN_LOOP_USLEEP); @@ -335,4 +335,4 @@ protected function _setQueue($nQueueKey, $nProcess = 0, $aQueue = array()) } return shm_put_var($this->_hShm, $nQueueKey + $nProcess, $aQueue); } -} \ No newline at end of file +}