Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added support for log levels #78

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 9 additions & 20 deletions ApnsPHP/Abstract.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}

/**
Expand Down Expand Up @@ -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.
*
Expand Down Expand Up @@ -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);
Expand All @@ -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;
Expand All @@ -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
Expand Down Expand Up @@ -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);
}
}
10 changes: 5 additions & 5 deletions ApnsPHP/Feedback.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand All @@ -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']
));
Expand All @@ -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;
}
}
Expand All @@ -114,4 +114,4 @@ protected function _parseBinaryTuple($sBinaryTuple)
{
return unpack('Ntimestamp/ntokenLength/H*deviceToken', $sBinaryTuple);
}
}
}
86 changes: 83 additions & 3 deletions ApnsPHP/Log/Embedded.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
43 changes: 42 additions & 1 deletion ApnsPHP/Log/Interface.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
18 changes: 9 additions & 9 deletions ApnsPHP/Push.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -150,26 +150,26 @@ 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;
}
}

$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']))) {
Expand All @@ -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();
Expand Down Expand Up @@ -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'] . ').');

Expand Down Expand Up @@ -385,4 +385,4 @@ protected function _removeMessageFromQueue($nMessageID, $bError = false)
}
unset($this->_aMessageQueue[$nMessageID]);
}
}
}
18 changes: 9 additions & 9 deletions ApnsPHP/Push/Server.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
Expand All @@ -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);
}
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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;
}

Expand All @@ -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);
Expand Down Expand Up @@ -335,4 +335,4 @@ protected function _setQueue($nQueueKey, $nProcess = 0, $aQueue = array())
}
return shm_put_var($this->_hShm, $nQueueKey + $nProcess, $aQueue);
}
}
}