Example #1
0
 /**
  * @param int $level
  * @throws CM_Exception_Invalid
  */
 public function setMinLevel($level)
 {
     $level = (int) $level;
     if (CM_Log_Logger::hasLevel($level)) {
         $this->_minLevel = $level;
     }
 }
Example #2
0
 public function prepare(CM_Frontend_Environment $environment, CM_Frontend_ViewResponse $viewResponse)
 {
     $level = $this->_params->has('level') ? $this->_params->getInt('level') : null;
     if (null !== $level && !CM_Log_Logger::hasLevel($level)) {
         throw new CM_Exception_InvalidParam('Invalid `level` param');
     }
     $levelList = $level ? [$level] : null;
     $type = $this->_params->has('type') ? $this->_params->getInt('type') : null;
     if (null !== $type && !CM_Paging_Log::isValidType($type)) {
         throw new CM_Exception_InvalidParam('Invalid `type` param');
     }
     $aggregate = $this->_params->has('aggregate') ? $this->_params->getInt('aggregate') : null;
     $urlPage = $this->_params->has('urlPage') ? $this->_params->getString('urlPage') : null;
     $urlParams = $this->_params->has('urlParams') ? $this->_params->getArray('urlParams') : null;
     $aggregationPeriod = $aggregate;
     if (0 === $aggregationPeriod) {
         $deployStamp = CM_App::getInstance()->getDeployVersion();
         $aggregationPeriod = time() - $deployStamp;
     }
     $logList = new CM_Paging_Log($levelList, $type, (bool) $aggregationPeriod, $aggregationPeriod);
     $logList->setPage($this->_params->getPage(), $this->_params->getInt('count', 50));
     $viewResponse->setData(['level' => $level, 'type' => $type, 'logList' => $logList, 'aggregate' => $aggregate, 'aggregationPeriod' => $aggregationPeriod, 'aggregationPeriodList' => array(3600, 86400, 7 * 86400, 31 * 86400), 'urlPage' => $urlPage, 'urlParams' => $urlParams, 'levelMap' => array_flip(CM_Log_Logger::getLevels())]);
     $viewResponse->getJs()->setProperty('level', $level);
     $viewResponse->getJs()->setProperty('type', $type);
 }
Example #3
0
 /**
  * @param array            $filterLevelList
  * @param int|boolean|null $filterType
  * @param boolean|null     $aggregate
  * @param int|null         $ageMax
  * @throws CM_Exception_Invalid
  */
 public function __construct(array $filterLevelList = null, $filterType = null, $aggregate = null, $ageMax = null)
 {
     if (null !== $filterLevelList) {
         foreach ($filterLevelList as $level) {
             $level = (int) $level;
             if (!CM_Log_Logger::hasLevel($level)) {
                 throw new CM_Exception_Invalid('Log level does not exist.', null, ['level' => $level]);
             }
         }
     }
     if (null !== $filterType && false !== $filterType && !self::isValidType((int) $filterType)) {
         throw new CM_Exception_Invalid('Type is not a children of CM_Paging_Log.');
     }
     if (null !== $ageMax) {
         $ageMax = (int) $ageMax;
     }
     $this->_filterLevelList = $filterLevelList;
     $this->_filterType = $filterType;
     $this->_ageMax = $ageMax;
     $criteria = $this->_getCriteria();
     if (true === $aggregate) {
         $aggregate = [['$match' => $criteria], ['$group' => ['_id' => ['level' => '$level', 'message' => '$message', 'exception_message' => '$context.exception.message', 'exception_class' => '$context.exception.class', 'exception_line' => '$context.exception.line', 'exception_file' => '$context.exception.file'], 'count' => ['$sum' => 1], 'createdAt' => ['$max' => '$createdAt'], 'exception' => ['$last' => '$context.exception']]], ['$sort' => ['count' => -1]], ['$project' => ['level' => '$_id.level', 'message' => '$_id.message', 'exception' => '$exception', 'count' => '$count', 'createdAt' => '$createdAt', '_id' => false]]];
         $source = new CM_PagingSource_MongoDb(self::COLLECTION_NAME, null, null, $aggregate);
     } else {
         $sorting = empty($criteria) ? ['_id' => -1] : ['createdAt' => -1];
         $source = new CM_PagingSource_MongoDb(self::COLLECTION_NAME, $criteria, null, null, $sorting);
     }
     parent::__construct($source);
 }
Example #4
0
 /**
  * @param CM_Log_Record $record
  * @return array
  */
 protected function _formatRecord(CM_Log_Record $record)
 {
     $levelsMapping = array_flip(CM_Log_Logger::getLevels());
     $context = $record->getContext();
     $result = ['message' => (string) $record->getMessage(), 'level' => strtolower($levelsMapping[$record->getLevel()]), 'timestamp' => $record->getCreatedAt()->format('Y-m-d\\TH:i:s.uO')];
     $result = array_merge($result, $this->_contextFormatter->formatContext($context));
     return $result;
 }
Example #5
0
 /**
  * @param int            $level
  * @param string         $message
  * @param CM_Log_Context $context
  * @throws CM_Exception_Invalid
  */
 public function __construct($level, $message, CM_Log_Context $context)
 {
     $level = (int) $level;
     $message = (string) $message;
     if (!CM_Log_Logger::hasLevel($level)) {
         throw new CM_Exception_Invalid('Log level does not exist.', null, ['level' => $level]);
     }
     $this->_level = $level;
     $this->_message = $message;
     $this->_context = $context;
     $this->_createdAt = CM_Util::createDateTimeWithMillis();
 }
Example #6
0
 /**
  * @param Exception $exception
  * @param int|null  $severity
  */
 public function handleExceptionWithSeverity(Exception $exception, $severity)
 {
     $printException = true;
     if ($exception instanceof CM_Exception) {
         $printException = $severity >= $this->_getPrintSeverityMin();
     }
     if ($printException) {
         $this->_printException($exception);
     }
     $logLevel = CM_Log_Logger::severityToLevel($severity);
     $this->getServiceManager()->getLogger()->addMessage('Application error', $logLevel, (new CM_Log_Context())->setException($exception));
 }
Example #7
0
 /**
  * @param string $className
  * @return CM_Jobdistribution_Job_Abstract|null
  */
 protected function _instantiateJob($className)
 {
     try {
         /** @var CM_Jobdistribution_Job_Abstract $job */
         $job = new $className();
         if ($job instanceof CM_Service_ManagerAwareInterface) {
             /** @var CM_Service_ManagerAwareInterface $job */
             $job->setServiceManager($this->getServiceManager());
         }
         return $job;
     } catch (Exception $e) {
         $logLevel = CM_Log_Logger::exceptionToLevel($e);
         $context = new CM_Log_Context();
         $context->setException($e);
         $this->getServiceManager()->getLogger()->addMessage('Delayed queue error', $logLevel, $context);
         return null;
     }
 }
Example #8
0
 public function run()
 {
     $jobsRun = 0;
     while (true) {
         if ($jobsRun >= $this->_jobLimit) {
             return;
         }
         $workFailed = false;
         try {
             $jobsRun++;
             CM_Cache_Storage_Runtime::getInstance()->flush();
             $workFailed = !$this->_getGearmanWorker()->work();
         } catch (Exception $ex) {
             $this->getServiceManager()->getLogger()->addMessage('Worker failed', CM_Log_Logger::exceptionToLevel($ex), (new CM_Log_Context())->setException($ex));
         }
         if ($workFailed) {
             throw new CM_Exception_Invalid('Worker failed');
         }
     }
 }
Example #9
0
 /**
  * @param Exception $exception
  */
 protected function _logException(Exception $exception)
 {
     $logLevel = CM_Log_Logger::exceptionToLevel($exception);
     $context = new CM_Log_Context();
     $context->setException($exception);
     CM_Service_Manager::getInstance()->getLogger()->addMessage('KickBox client error', $logLevel, $context);
 }
Example #10
0
 /**
  * @param string|string[] $channels
  * @param Closure         $callback
  * @return mixed return something else than null to exit the pubsub loop
  */
 public function subscribe($channels, Closure $callback)
 {
     $redisClient = $this->_createPredisClient($this->_config['host'], $this->_config['port'], $this->_config['database'], 60, -1);
     $pubsub = $redisClient->pubSubLoop(['subscribe' => $channels]);
     $response = null;
     /** @var stdClass $message */
     foreach ($pubsub as $message) {
         try {
             if ($message->kind == 'message') {
                 $response = $callback($message->channel, $message->payload);
             }
         } catch (Exception $e) {
             $this->getServiceManager()->getLogger()->addMessage('Redis message callback failed', CM_Log_Logger::exceptionToLevel($e), (new CM_Log_Context())->setException($e));
         }
         if (!is_null($response)) {
             break;
         }
     }
     return $response;
 }
Example #11
0
 /**
  * @param CM_Log_Record $record
  * @return array
  * @throws CM_Exception_Invalid
  */
 protected function _getRecordInfo(CM_Log_Record $record)
 {
     $computerInfo = $record->getContext()->getComputerInfo();
     return ['datetime' => $record->getCreatedAt()->format($this->_formatDate), 'levelname' => CM_Log_Logger::getLevelName($record->getLevel()), 'message' => $record->getMessage(), 'fqdn' => null === $computerInfo ? 'none' : $computerInfo->getFullyQualifiedDomainName(), 'phpVersion' => null === $computerInfo ? 'none' : $computerInfo->getPhpVersion()];
 }
Example #12
0
 protected function _registerCallbacks()
 {
     $this->_registerClockworkCallbacks('1 second', ['CM_Jobdistribution_DelayedQueue::queueOutstanding' => function () {
         $delayedQueue = $this->getServiceManager()->getDelayedJobQueue();
         $delayedQueue->queueOutstanding();
     }]);
     $this->_registerClockworkCallbacks('1 minute', array('CM_Model_User::offlineOld' => function () {
         CM_Model_User::offlineOld();
     }, 'CM_ModelAsset_User_Roles::deleteOld' => function () {
         CM_ModelAsset_User_Roles::deleteOld();
     }, 'CM_Paging_Useragent_Abstract::deleteOlder' => function () {
         CM_Paging_Useragent_Abstract::deleteOlder(100 * 86400);
     }, 'CM_File_UserContent_Temp::deleteOlder' => function () {
         CM_File_UserContent_Temp::deleteOlder(86400);
     }, 'CM_SVM_Model::deleteOldTrainings' => function () {
         CM_SVM_Model::deleteOldTrainings(3000);
     }, 'CM_Paging_Ip_Blocked::deleteOlder' => function () {
         CM_Paging_Ip_Blocked::deleteOld();
     }, 'CM_Captcha::deleteOlder' => function () {
         CM_Captcha::deleteOlder(3600);
     }, 'CM_Session::deleteExpired' => function () {
         CM_Session::deleteExpired();
     }, 'CM_MessageStream_Service::synchronize' => function () {
         CM_Service_Manager::getInstance()->getStreamMessage()->synchronize();
     }));
     if ($this->getServiceManager()->has('janus')) {
         $this->_registerClockworkCallbacks('1 minute', array('CM_Janus_Service::synchronize' => function () {
             $this->getServiceManager()->getJanus('janus')->synchronize();
         }, 'CM_Janus_Service::checkStreams' => function () {
             $this->getServiceManager()->getJanus('janus')->checkStreams();
         }));
     }
     $this->_registerClockworkCallbacks('15 minutes', array('CM_Action_Abstract::aggregate' => function () {
         CM_Action_Abstract::aggregate();
     }, 'CM_Action_Abstract::deleteTransgressionsOlder' => function () {
         CM_Action_Abstract::deleteTransgressionsOlder(3 * 31 * 86400);
     }, 'CM_Paging_Log::cleanup' => function () {
         $allLevelsList = array_values(CM_Log_Logger::getLevels());
         foreach (CM_Paging_Log::getClassChildren() as $pagingLogClass) {
             /** @type CM_Paging_Log $log */
             $log = new $pagingLogClass($allLevelsList);
             $log->cleanUp();
         }
         (new CM_Paging_Log($allLevelsList, false))->cleanUp();
         //deletes all untyped records
     }));
     if ($this->getServiceManager()->has('maxmind')) {
         $this->_registerClockworkCallbacks('8 days', array('CMService_MaxMind::upgrade' => function () {
             try {
                 /** @var CMService_MaxMind $maxMind */
                 $maxMind = $this->getServiceManager()->get('maxmind', 'CMService_MaxMind');
                 $maxMind->upgrade();
             } catch (Exception $exception) {
                 if (!is_a($exception, 'CM_Exception')) {
                     $exception = new CM_Exception($exception->getMessage(), null, ['file' => $exception->getFile(), 'line' => $exception->getLine(), 'trace' => $exception->getTraceAsString()]);
                 }
                 $exception->setSeverity(CM_Exception::FATAL);
                 throw $exception;
             }
         }));
     }
 }
Example #13
0
 /**
  * @param Closure $regularCode
  * @param Closure $errorCode
  * @return mixed
  * @throws CM_Exception
  */
 protected function _runWithCatching(Closure $regularCode, Closure $errorCode)
 {
     try {
         return $regularCode();
     } catch (CM_Exception $ex) {
         $config = self::_getConfig();
         $exceptionsToCatch = $config->exceptionsToCatch;
         $catchPublicExceptions = !empty($config->catchPublicExceptions);
         $errorOptions = \Functional\first($exceptionsToCatch, function ($options, $exceptionClass) use($ex) {
             return is_a($ex, $exceptionClass);
         });
         $catchException = null !== $errorOptions;
         if ($catchException && isset($errorOptions['log']) && true === $errorOptions['log']) {
             $logLevel = isset($errorOptions['level']) ? $errorOptions['level'] : null;
             if (null === $logLevel) {
                 $logLevel = CM_Log_Logger::exceptionToLevel($ex);
             }
             $context = new CM_Log_Context();
             $context->setUser($this->getViewer());
             $context->setException($ex);
             $this->getServiceManager()->getLogger()->addMessage('Response processing error', $logLevel, $context);
         }
         if (!$catchException && ($catchPublicExceptions && $ex->isPublic())) {
             $errorOptions = [];
             $catchException = true;
         }
         if ($catchException) {
             return $errorCode($ex, $errorOptions);
         }
         throw $ex;
     }
 }
Example #14
0
 public function testStaticGetLevelNameException()
 {
     $exception = $this->catchException(function () {
         CM_Log_Logger::getLevelName(666);
     });
     $this->assertInstanceOf('CM_Exception_Invalid', $exception);
     /** @var CM_Exception_Invalid $exception */
     $this->assertSame('Level is not defined', $exception->getMessage());
     $this->assertSame(['level' => 666, 'availableLevels' => '100, 200, 300, 400, 500'], $exception->getMetaInfo());
 }
Example #15
0
 public function testStaticLogLevelMethods()
 {
     $this->assertSame('INFO', CM_Log_Logger::getLevelName(CM_Log_Logger::INFO));
     $this->assertNotEmpty(CM_Log_Logger::getLevels());
     $this->assertTrue(CM_Log_Logger::hasLevel(CM_Log_Logger::INFO));
     $this->assertFalse(CM_Log_Logger::hasLevel(666));
 }